Un paseo por las nubes

Un blog acerca de Cloud Computing...
Using the Azure Websites Migration Assistant to migrate a DNN website

Last October the Azure Websites team released a new tool to run the migration of local websites to Azure in a super-super-easy way: just following an assistant that analyzes and migrates your website to the cloud, including local database dependencies, all in a few clicks.

Using Apurva’s words:

Now you can easily migrate to Azure Websites from your existing websites that run on Internet Information Service (IIS) 6 or later. Azure Websites Migration Assistant can analyze your IIS server installation, identify which sites can be migrated to Azure Websites, highlight any elements that cannot be migrated or are unsupported on the platform, and then migrate your websites and associated databases to Azure with just a few clicks.

So what came immediately to my mind was if the assistant would work correctly when trying to migrate a DNN website to Azure and how would be the experience. Two months later, finally I got time to run a test, and has been amazing!!

Let’s summarize the steps to follow in the case you want to move your website as well. Check the Tips and Tricks section before running the assistant for lessons learned, so perhaps you can avoid to fall into some known errors. Note that this tool is also open source and the code is available at CodePlex, so fixes and improvements are welcome!


Moving your DNN site to the cloud in 3 steps

To start the process, you will need to browse https://www.movemetothecloud.net and follow the instructions. The migration process has 3 steps:

1. Install the Migration Assistant tool (available at https://www.movemetothecloud.net/)

2. Run the readiness assessment

3. Migrate your site(s) (hey! You can move more than one site at time!)

The website I used for this test was a DNN Platform 7.3.4 default installation. Before starting the assistant I double checked that the site was working fine (see tips and tricks section to save time on known issues).


So after downloading the assistant the first screen appears to ask for the onpremise IIS server hosting the website to migrate. Since mine was my own laptop, I used the default option:


So after clicking next, the assistant contacts the IIS server and looks for possible candidates to migrate. I selected only the website I wanted to migrate unchecking all the others. You need to do it one by one, no unselect all option, but remember that you can contribute to the project!


The next step shows a readiness report where the verification results are shown. My report was not showing anything scary so I simply continued with the following step by clicking on the Upload button.


And now started the cool part, because all the website provisioning, SQL Database server, database, etc. it’s automatically created during by the assistant just by clicking some buttons. This remembered me the DNN Azure Accelerator project that does the same but deploying on Azure by using the Cloud Services flavor.


So when clicking on the “Begin Migration” button, the Azure AAD/Micosoft Account login page was shown to introduce my Azure subscription credentials:


After signing in, I selected the subscription I wanted to use and the datacenter location. I’m not sure if there is a bug on the tool or the datacenter location is not fully populated with all the options, but I could only deploy on Central US, no other option appeared. As this was a migration test was OK for me, but I would need to revisit this in the future when migrating other websites so I can choose the desired datacenter location.


In the next step you can select the SQL Server settings, so can choose between an existent one or just create a new one what is the default option. I also left the database name setting as default as well, but I manually set the website name to avoid portal alias issues after deploying on Azure (check Tip #2 under the Tips and Tricks section at the end of the post).


By clicking on the Customize settings link, you can also choose the website mode, the worker size, the web hosting plan (server farm) as well as the database edition. You can just use the defaults, but by my experience I would recommend at least a S1 database edition for performance reasons.


After clicking on the Create Website button, the migration process started by provisioning the needed resources, all smooth:


So once created, we start with the publish process by clicking on the Begin Publish button in order to start the website content upload as well as the database migration. By the logs being shown in this process and without confirming seeing the code at CodePlex, I suspect that this process is executed on two parallel threads, one uploading the content via webdeploy and the second by exporting/importing a .bacpac. It’s interesting because I’m very familiar running this type of migrations using just the same technique (note for myself: satisfy my curiosity spending a while reviewing the code at CodePlex).

Depending on the size of your site and the available bandwidth, this can take a long time. It is just a good moment for taking that cup of coffee.


And just after the long wait, the site apparently finished without issues!


Browsing the Azure Website for the first time brought the website fully migrated to Azure. The assistant did the corresponding modifications in the web.config to target the new database (curiously, the change was done directly on the web.config file and not using the website connection string settings).


Who wants more?


Tips and tricks

Tip #1: check your local database for SQL Database incompatibilities

The wizard runs really smooth and it’s awesome to see it working just by specifying some settings, but be aware that the assistant has its limitations and probably does not analyze all what your website needs. The list of elements verified during the analysis are listed at http://azure.microsoft.com/en-us/documentation/articles/web-sites-migration-from-iis-server and while the checks done are awesome, seems that is not running any check on the database, so when I tried to migrate a website that I knew that had SQL Database incompatibility issues, the problem arose very late, just when all the website was migrated and the data was being inserted (this was after an hour of data transfer).

NOTE: SQL Database Update V12 (Preview) has been announced which provides nearly complete compatibility with the Microsoft SQL Server engine, so the mentioned below does not apply by the time you are reading this post.


After a few minutes more the process stopped and gave a full error report, but no helpful info on the error or how to solve it.


So before running the Azure Websites Migration assistant, if you are going to move a website that has a database dependency like DNN, I strongly recommend to you to verify that the database is SQL Database compatible. There are several ways to accomplish that objective, here some suggestions:

1) Use the SSMS database migration wizard targeting a SQL Database as destination. I believe a similar process is used under the covers (export/import a .bacpac), so the same errors appears without having to wait for the last step

2) Use the always free SQL Azure Migration wizard available at CodePlex (https://sqlazuremw.codeplex.com/)

3) Use RedGate’s SQL Compare, my favorite! Check here for a free trial (http://www.red-gate.com/products/sql-development/sql-compare/)

Tip #2: Adding a cloud portal alias before the migration

After migrating your DNN website to Azure you can get a 404 error if you have more than one portal in your local install or you have set the “Add Automatic Portal Alias” to false. I have wrote more info about the issue at https://serverfault.com/questions/655441/iis-website-works-on-only-one-port-in-localhost-settings/657915#657915

To avoid the issue, just add a portal alias BEFORE running the migration wizard, so it’s already configured when migrated to the cloud. If you are going to use a website name “MyDNNWebsite” on the wizard, just add the portal alias “MyDNNWebsite.azurewebsites.net”



Other problems can arise, but I have to say that for DNN projects the assistant works like a charm. Congratulations to the Azure Websites team for this jewel, I’m excited with the promised improvements coming in the future.

Hope this helps!

Redis Caching Provider for DNN Platform

redis-300dpiTwo months ago I promised a gift for the friends at the DNNCon, a new open sourced DNN caching provider based on Redis. Today, I’m pleased to announce that I have implemented a first version of the provider and tested it on both on-premise and Azure environments.

This caching provider allows you to use a Redis cache server/cluster within DNN Platform, using a hybrid in-memory approach to increase cache performance (items are cached in the local memory and on Redis cache), and the publisher/subscriber feature to keep in sync all the in-memory caches from the webfarm. You must use Redis 2.8.17 or higher for an on-premises deployment. The caching provider is also Azure Redis cache compatible.

If you want to contribute to the caching provider, just go to https://github.com/davidjrh/dnn.rediscachingprovider and clone the repository.


Quick Start

  1. Provision a Redis cache to be used by your DNN instance. Perhaps one of the fastest ways to do it is to provision an Azure Redis cache by following the steps described at http://msdn.microsoft.com/en-us/library/dn690516.aspx, remember to provision the DNN instance on the same datacenter location to improve performance. You can also provision your Redis cache on your premises by following instructions provided at http://redis.io/download. The caching provider has been tested with the Win64 Redis port. Note that the DNN Redis Caching provider supports working with a shared Redis cache deployment, so you can reuse the same Redis cache deployment on several DNN websites.
  2. Download from the https://github.com/davidjrh/dnn.rediscachingprovider/tree/master/Release folder the latest version of the DNN Redis Caching provider
  3. Using the Extensions page of your DNN instance, upload and install the Redis caching provider. Once installed, will be the default caching provider.
  4. Open your web.config file and specify the RedisCachingProvider connection string in the ConnectionStrings section. If you are using Azure Redis cache, your connection string should look like this:


<add name="RedisCachingProvider" connectionString="mycache.redis.cache.windows.net,password={base64password},ssl=True" providerName="DotNetNuke.Providers.RedisCachingProvider" />



Advanced configuration

There are some attributes you can use to tweak or debug the caching provider. The initial set of configurable attributes are:

  • keyPrefix (default string.Empty): this attribute is used to add a prefix to each key stored on the Redis cache. This can be used to share the Redis cache between different DNN deployments. When no prefix is specified (default empty string), the current DNN Host Guid will be used so by default, the cached keys are partitioned by the Host identifier.
  • useCompression (boolean, default false): before inserting on the Redis cache, the value is compressed in order to save memory. The values are deflated when retrieved from the Redis cache. While using this parameter can save resources on the Redis server has a performance penalty because of the compression operations
  • silentMode (boolean, default true): when the silent mode is set to true and an exception occurs, is logged on the DNN instance log files under "/Portals/_default/Logs" and not raising an exception. Note that the in-memory cache is used before the Redis cache, so the site normally will continue working, but can end in out of sync caches. Keep an eye on the log files to verify that everything is working fine.

Hope this helps. Happy coding, and happy new year!!

La hora del código: ASP.net vNext

imageLlegó la hora de cerrar los eventos que tenemos programados desde TenerifeDev para este año, y hemos hecho unos cambios de última hora para el evento de este jueves aprovechando  el evento global “La Hora del Código”. Para los que no sepáis de que va, es “un movimiento mundial, llegando a decenas de millones de estudiantes en más de 180 países. Cualquier persona, en cualquier lugar puede organizar un evento Hora de Código. No se necesita experiencia y está destinado para edades entre 4 y 104 años”.

Por este motivo, hemos cambiado la sesión sobre SharePoint por una más general de mayor audiencia de Introducción a ASP.net vNext, en el mismo sitio y misma hora. Esta sesión iba a ser impartida por Tiberiu Covaci (MVP de ASP.net), pero por razones de última hora hemos cambiado su sesión para principios del año que viene. En esta ocasión, Santiago Porras (MVP Windows Platform) y David Rodriguez (MVP Azure) serán los encargados de conducir la sesión.

Ir a la página de registro gratuito

  • Evento: Introducción a ASP.net vNext
  • Descripción: Ven y conoce de primera mano cómo será la próxima versión de ASP.net, qué cosas cambian, dónde quedan los WebForms, cómo funcionan los controladores y qué le ha pasado al web.config. Santiago Porras, MVP de Windows Platform (@saintwukong) y David Rodriguez, MVP de Azure (@davidjrh) nos harán un recorrido por cada una de las novedades de la nueva plataforma para aplicaciones web y cloud. ASP.net vNext (aka ASP.NET 5), es completamente Open Source y está disponible en GitHub. ASP.NET 5 está actualmente en Preview.
  • Dónde: Salón de Grados de la ETSII
  • Cuándo: Jueves 11 de diciembre a las 18:00 GMT+0
  • Registro: registro gratuito en Eventbrite

Nos vemos el jueves!!

Posted: 9/12/2014 11:14 por David Rodríguez | con no comments
Archivado en: ,
TenerifeDev: eventos para cerrar el año

TenerifeDev250Hacía algo de tiempo, desde la LAN Party de verano, que desde TenerifeDev no hemos preparado ninguna sesión de esas que nos gustan, donde vamos a pasar una tarde compartiendo experiencias de desarrollo sobre tecnologías innovadoras.

Si aún no conoces nuestro grupo de usuarios, se trata de un grupo sin ánimo de lucro en el que  nos reunimos para compartir experiencias de desarrollo de software sobre tecnologías Microsoft, siendo nuestro punto de encuentro habitual la sala de Grados de la ETSII de San Cristóbal de La Laguna, Tenerife. Este año hemos estado algo liados y no nos hemos las veces que nos hubiera gustado, pero nos hemos puesto un  objetivo de reunirnos al menos una vez al mes con diversas temáticas de alto grado de interés tanto para los alumnos como para gente como nosotros, que seguimos en el ámbito del desarrollo de software de forma profesional, facilitando un punto de encuentro entre alumnos y empresas.


Próximos eventos

Después de hacer un hueco en la agenda, hemos conseguido cerrar las siguientes fechas y temáticas, para lo que resta de año:

  • 16 de Octubre de 18:00 a 19:30 - Introducción a Azure Websites y Responsive Design:
    no te pierdas de la mano de Santiago Porras (MVP en Windows Platform Development) y David Rodríguez (MVP en Microsoft Azure) una sesión de introducción al desarrollo sobre Azure Websites, viendo distintos aspectos como la creación del site, integración con GitHub y Visual Studio, copias de seguridad, así como la forma de implementar tus sitios web mediante un diseño responsivo que sea adapte a cualquier dispositivo. Como no, veremos algo de Windows 10 para abrir boca.
    Lugar: Aula de la FEULL, antigua torre de Químicas
  • 19 de Noviembre de 18:00 a 19:30 - Introducción a Azure Mobile Services y Aplicaciones Universales:
    no te pierdas de la mano de Santiago Porras (MVP en Windows Platform Development) y David Rodríguez (MVP en Microsoft Azure) una sesión de introducción al desarrollo de apps para dispositivos móviles, integrando notificaciones push, bases de datos en backend, uso de proveedores de identidad como Facebook o Twitter, y todo ello compartiendo código mediante la creación de aplicaciones universales, el nuevo modelo de desarrollo de apps multi-plataforma.
    Lugar: Salón de Grados de la ETSII
  • 11 de Diciembre de 18:00 a 19:30 - Desplegando SharePoint en la nube:
    no te pierdas de la mano de Alberto Díaz (MVP de SharePoint Server), una sesión sobre cómo desplegar una granja de servidores SharePoint sobre Microsoft Azure, con tips & tricks sobre rendimiento y manual de buenas prácticas, y todo en menos de 10 clicks.
    Lugar: Salón de Grados de la ETSII

TenerifeDev también eres tú

No olvides que tú también puedes dar una sesión y compartir tus inquietudes y tus experiencias. ¿Que te gustó lo que hiciste el fin de semana y quieres compartirlo? Adelante. ¿Que estás en un proyecto que crees que sería interesante para mostrarlo? ¡Todos queremos verlo!

Para ello es muy fácil, ponte en contacto con nosotros a través de cualquiera de los siguientes medios y lo organizamos sobre la marcha.

I got a new laptop: where is my Break key?

This post is in memoriam to those cool keyboard designers that happily remove keys from laptops, just because they run out of space or because they think that key is no longer being used, doing things more funny for IT guys that they don’t have anything to do but spend their time on looking how to change now from full screen mode while doing a Remote Desktop session.

Raiders of the lost key

I have to say that I am very happy with my DELL M3800 laptop, it’s a real black beast workstation (16GB RAM, two SSD disks, UHD touch screen with the weight, etc.) with a very low weight, only 1,88Kg, what it does ideal for having opened several Visual Studio sessions, some Hyper-V machines running and a lot of other tasks in background. Cool!

I normally have the laptop connected via USB 3.0 to the dock station so I normally use an external keyboard during working hours, and was yesterday while running my awesome Windows 10 Technical Preview using Hyper-V and went to full-screen mode and unpinned the top bar to hide the remote session options (wanted a more immersive experience). To go to full-screen mode I used the menu “Full-Screen” from the Hyper-V window, but when I tried to came back to my real desktop by using the “Ctrl+Alt+Break” key combination, where in the hell was my Break/Pause key?


DELL M3800 Keyboard Layout

And then, I discovered a world of frustrated DELL customers asking for the same thing. How this can happen? How can I solve this?


I’m going to post here the solution so you can use it as well, but I’m really writing this because I’m sure I will need to revisit this post in a near future after reinstalling my OS for whatever reason.

I first tried to use a simple PowerShell cmdlets by sending the keys combination, but this was not working because the keyboard hooks just sends the keys to the Guest OS, and not to the “hosting Hyper-V window”.

Then I tried to use AutoHotKey in my local session, and while it’s a highly recommended piece of software for other tasks, has the same problem than using PowerShell, the keys are not sent to the hosting Hyper-V process (there are some attempts of resolving it by looking for the process handle, but after spending some time on that path, anything worked).

I gave a try to On Screen Keyboard (run osk.exe in a command line), in both the host OS and the Guest OS, but had the same issue, didn’t work!

So the solution: remap a key in my keyboard. This comes from a DELL support forums thread but I’m going to complement the answer because the procedure explained there is not easy to follow and does not explain how to map whatever key you want. 

WARNING Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall the operating system. Modify the registry at your own risk.

Remapping a key by using Scancodes: the hard way

I noticed that I was never using the key “Insert” (must be a key that keyboard designers use a lot), so I decided to convert that key as my new “Break” key. To do this remap, you must to do some modifications in your registry and then logoff/login again into your profile (restarting the laptop also works, but the first method is faster).

To change a key for another, you must open your registry editor by running regedit.exe and finding the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout. There you can manually change the keyboard mappings but this is not an easy task since you will need to start wasting your time looking for the scancodes documentation:


If you want to go that path, I recommend you to visit this link with a good keyboard scancodes reference: http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html

Remapping a key by using Scancodes: the easy way

I was getting a headache reading all these documentation and then found an awesome Open Source tool called Sharpkeys and available at CodePlex that allows you to do this task without diving into any keyboard code reference. So here the final steps I followed:

  1. Download and install SharpKeys from CodePlex
  2. Run the app and click on the “Add” button to add a new key mapping
  3. From the left list, select the key you want to map in your keyboard (I used “Insert”). You can easily find another one by clicking on the “Type Key” button
  4. From the right list, select the key you want to target. In our case, and for the purpose of this post in pro of a human race with happy IT guys, we are going to specify “Unknown: 0xE046”, that is the Scancode for the <Pause/Break> key
  5. Click on OK and that will save the entry in your registry
  6. Logoff and logon again, and you will see now that by using <Ctrl>+<Alt>+<Insert> is now working as <Ctrl>+<Alt>+<Break>


Remapping a key by using Scancodes: the faster way

I have exported the registry key so if you want to use just the same mapping, changing the “Insert” key for the “Break” key without doing anything else, just download this file and open it to import it into your registry.

Hope this helps!

Solving OneDrive for Business 2013 synchronization issues

If you are reading this is probably because you have suffered synchronization issues while using OneDrive for Business 2013 to sync a SharePoint document library to your local file system, something really useful to work with offline files while disconnected from the network and allowing the utility to sync when coming online.

Which type of issues? Well, sounds bad, but one of the worst things I have experienced is that if a problem occurs when the sync starts, no sync is done at all, getting a popup window telling that somebody in your organization used, for example, a long file path. If OneDrive for Business founds something like this issue, it simply stops, does not continue with the other files. Bad.


So you go to the document library, and trying to figure out the full path that the bubble is omitting, you change the file name or folder to shorten it and solve the issue…and then another popup, and other, until you have solved all these issues. No way of knowing all the possible issues to fix them at the same time.

And solving all the issues can be a hard task, if you see the sync restrictions available at http://support.microsoft.com/kb/2933738, from long path names to illegal characters and well… files of 2GB in size (who is storing 2GB files on SharePoint Online? BTW, who is storing 1,9GB files on SharePoint Online?)

Anyway, I was tired of following this procedure to solve the items one by one and decided to build a PowerShell script to analyse the document library structure returning all the conflictive files in a single operation.

PowerShell to the rescue

I have built a PowerShell script available at https://github.com/davidjrh/o365tools/ that uses the SharePoint Server 2013 Client SDK assemblies to connect to a SharePoint Online site and start doing the analysis. You can specify a document library or let the cmdlet to look all the document libraries in the site. You can pass the credentials as a PSCredential parameter or introduce them in a secure popup window when requested. Also enabling the Verbose switch will show the full progress of the analyzed files.

.\Get-SPOInvalidFilesForSync.ps1 -SiteName "https://mytenant.sharepoint.com" 
                                 -DocumentLibraryName "My Documents" 
                                 -Credential $credentials 

-SiteName The SharePoint Online site's URL. Ensure to specify https

-DocumentLibraryName Optional. The name of the library to process

-Credential Optional. The credentials to be used to connect to SharePoint Online. If omitted, the script will pop up for input

-Verbose Optional. If specified, all verbose messages will be shown


Now you can go and customize this script and, for example, send an e-mail to the owner of that file asking for renaming it to fix the issue. Running this in an scheduled task is what I’ve finally do it.


SharePoint is good and OneDrive for Business is not bad. But PowerShell rulez.

Posted: 26/9/2014 16:51 por David Rodríguez | con no comments
Archivado en:
TenerifeDev en la TLP-Innova con Azure y aplicaciones universales

EntradaTLPComo much@s sabrán, la Tenerife LAN Party está a la vuelta de la esquina celebrándose del 15 al 20 de Julio, un evento que no hace más que crecer y crecer edición tras edición, y esta no ha sido menos. Las 2.000 entradas para el acceso al recinto ferial se agotaron en…2 minutos!!


Quizás una de las secciones que más atraen al mundo profesional es la TLP-Innova, un encuentro de comunicadores, programadores y profesionales que viven y trabajan en el entorno tecnológico. En esta edición hay dos novedades a destacar en cuanto la organización:

  • El evento tendrá lugar en el Auditorio de Tenerife Adán Martín del 16 al 19 de julio (cerca del recinto ferial donde se desarrolla la TLP, pero en un ambiente más profesional)
  • La entrada a todas las jornadas es totalmente GRATUITA

Las charlas y sesiones que se están cociendo están, creedme, para no perderse ni una. Podéis acceder al listado completo a través de este enlace: http://tlp-innova.com/actividades/

TenerifeDev quería poner su granito de arena y os hemos preparado un monográfico de tres sesiones sobre Azure donde podrás aprender las características más importantes de la plataforma, además de una sesión adicional sobre el desarrollo de aplicaciones universales. Os dejamos el detalles de las mismas:


Microsoft Azure

Fecha: Jueves 17, de 10:00am a 12:55pm
Ubicación: Sala de Cámara del Auditorio de Tenerife

10:00 – 10:55 - Microsoft Azure (I): todo lo que un desarrollador debería saber

Conoce las características que pueden hacer que el desarrollo de tus aplicaciones sea un juego de niños gracias a los Azure WebSites y Mobile Services y domina el los despliegues y el código con Visual Studio Online.

11:00 – 11:55 - Microsoft Azure (II): el cielo para IT Pros

A la hora de llevar tu solución a la nube es necesario pensar anteriormente las diferencias existentes entre esta y el escenario al que estamos acostumbrado dentro de nuestro datacenter. En esta sesión presentaremos las respuestas a las preguntas más comunes que recibimos: ¿en qué datacenter podemos colocar nuestras máquinas virtuales?, ¿cómo garantizamos la alta disponibilidad de nuestros servicios frente a posible fallos del hardware o actualizaciones del host?, ¿cómo gestionamos altas cargas de tráfico mediante el balanceador? ¿cómo podemos controlar el acceso a nuestras aplicaciones mediante el filtrado y ACLs? Y lo más importante, ¿cómo podemos prever el coste mensual de la infraestructura desplegada en la nube?

12:00 – 12:55 - Microsoft Azure (III): últimas novedades presentadas en el TechEd 2014

Desde su lanzamiento oficial en febrero de 2010, la plataforma Azure no ha parado de crecer tanto en el número de servicios para la construcción de soluciones basadas en la nube, como en la disponibilidad de la misma a lo largo de todo el globo. El pasado mes de mayo se presentaron en el TechEd de USA un gran número de nuevos servicios y actualizaciones que han dejado con la boca abierta a la comunidad técnica. ¿Te imaginas poder desplegar una aplicación que fue desarrollada en los años 90 en la nube y accesible desde un iPad o una tablet Android, todo sin tener que tocar una línea de código de la aplicación? Esta y muchas otras serán las cosas que veremos en esta sesión para concluir con las sesiones sobre Microsoft Azure.


Universal Apps para dominarlos a todos

Fecha: Jueves 17, de 10:00am a 12:50pm
Ubicación: Sala Multiusos B del Auditorio de Tenerife

13:00 – 13:50 - Universal Apps para dominarlos a todos

Las Universal Apps son el último paso que ha dado Microsoft para desarrollo de aplicaciones para Windows Phone 8.1 y Windows 8.1 incluyendo, como principal cambio, poder compartir casi la totalidad del código gracias al uso del núcleo Windows Runtime. En esta sesión veremos algunas de las principales características que harán que disfrutemos creando aplicaciones.


Como es habitual, tendremos sorpresas y algunos regalitos para los más “avispados”. ¡No faltéis!

Un saludo, y happy coding!

How to easily publish your own app through Azure RemoteApp Preview without uploading an image template

If you are playing with the Azure RemoteApp Preview (you can enable the features preview here: https://account.windowsazure.com/PreviewFeatures), you would like to publish your own WinForms applications without uploading a template image. If your application can run on the default Windows Server 2012 R2 that is available when creating a new RemoteApp service, you can follow these steps.

Copying files through the Open/Save as dialogs from any application like Word, Paint, etc. is available so... why not to copy and paste my App files through them? Sounds really silly, but it works! So... why not to enable the File Explorer to allow copying/pasting files from my file system to the remote VM and then publish the applications? Easy! Let’s see how to do it.

Publish File Explorer

Once you have created your RemoteApp service, let’s go and create a new shortcut for the File Explorer:

  1. Go to your RemoteApp service and then to the RemoteApp Programs tab
  2. Click on the “Publish > Publish programs using path”
  3. In the Name textbox type “File Explorer” and in the path type “%SystemRoot%\explorer.exe”image
  4. Click on OK

Now when opening the Microsoft RemoteApp client, the file explorer is available and after opening you will notice that you can copy files from your local system and then pasting them on this File System instance.


As example, you can copy a WinForms app to the remote file system as shown below. BTW, you can also copy an installer and run it by opening it later.


Now you can go to the “RemoteApp Programs” list and just create a new shortcut for your application.


Do you need to setup something else for your RemoteApp? You can easily publish cmd.exe and powershell.exe as well. No limits!

Remember that this is a service preview and lot of new features will be available soon. This is only to make things easier while testing your own RemoteApps in this phase.

Hope this help!

How to know which Azure VM image are you consuming?

MostMM02_iDiskIconA few days ago I was wondering if one of the SQL Servers I deployed some months before was provisioned using a SQL Server “pay-per-use” image or was done by using a clean Windows Server 2012 R2 image and then manually installed the SQL Server on it. At the beginning the question seemed  trivial, and that I could easily found that by simply logging into the VM and check the version number on SQL Server (i.e. by running SELECT @@version, or similar), but I was not really happy with what I found. Another way could be to check the billing details, the VM should be there in some way, but apart of the number of records that I had on those details plus the fact that those details were grouped by cloud service name, and that in some cases I would not have access to the billing information, this didn’t seem the correct path.

How to be immediately 100% sure that I was using one image instead of another? What if I have the same question about other “pay-per-use” VM image, and trying to found symptoms is not easy?

Looking at the Azure Portal

If you go to the Azure Portal and deploy a SQL Server VM via the VM Gallery, PowerShell or another way, you will currently find that in the VM dashboard there is a lot of information about the VM but no detail of what image are you paying for. The disk area shows you the current attached disks that in some way were used to initially provision the VM, but again, there is no information about which image was used:


PowerShell to the rescue

After the initial ideas, I found in the MSDN Virtual Machine REST API documentation that in the “GetRole” operation there is a way to obtain the source image name of the image used to create the OS disk:


Ok, almost there. So if there is a REST API, almost sure that there is a Cmdlet that uses that API, so before starting to build a REST client app, just tried to find it and hurra!…was there!

# Setup the credentials using a management certificate
$subscriptionName = '<your subscription Name>'
$subscriptionId='<your subscription Id>'
$thumbprint = ‘<the thumbprint of your management certificate>’
$mgmtCert = Get-Item cert:\\CurrentUser\My\$thumbprint
Set-AzureSubscription -SubscriptionName $subscriptionName -SubscriptionId $subscriptionId -Certificate $mgmtCert

# Select the subscription
Select-AzureSubscription $subscriptionName

# Obtain the source image name
$(Get-AzureVM -ServiceName sqlcosttest).VM.OSVirtualHardDisk.SourceImageName

By running this, you get different results from a VM that was provisioned by using a SQL Server image rather than a Windows Server one. The Source Image name can give you an idea of what are you paying for (this case I was paying for a SQL Server 2014 Enterprise on Windows Server 2012 R2, the April’s release):


With the VM Source Image Name you can now use the cmdlet Get-AzureVMImage to obtain the full information of the source image:


Running the cmdlet Get-AzureVMImage without parameters gives you the full list of current VM images ready to deploy.


After thinking twice, now seems obvious how to obtain the information I was looking for, and would be more obvious for those ones using Powershell day by day. It’s not my case, and day by day I learn a new highly useful cmdlet that will never forget. In fact, my RescueTime reports tell me that I’m increasing the time I daily spend on running Powershell cmdlets. Hopefully this helps you and encourages you to learn more about Azure cmdlets.

Un saludo and Happy Coding!

Cosas que debo llevar al Global Windows Azure Bootcamp

bootcampYa sólo quedan unos cuantos días para vernos en el evento Global Windows Azure Bootcamp y parece ser que estamos que lo petamos, hemos tenido que colgar el cartel de no quedan más entradas. Aún así, puedes registrarte a la lista de espera, ya que vamos a realizar un proceso de comprobación de asistencia para liberar las plazas que no vayan a utilizarse.

Recuerda que aparte de las estupendas sesiones que transcurrirán a lo largo del día, vamos a hacer historia con la mayor granja de servidores global colaborando en un proyecto de investigación científica para el diagnóstico temprano de la diabetes Tipo 2. Va a ser algo grande y que dará mucho que hablar sobre el potencial de la computación global, algo de lo que podrás sentirte orgulloso de haber puesto tu granito de arena y haber colaborado en ello.


Pulsa aquí para conocer más acerca del Global Windows Azure Bootcamp GlyQ-IQ lab

Para poder participar y colaborar en esta investigación es necesario que te prepares para ello. ¿Ya lo tienes todo listo? ¿Te acuerdas de lo que tenías que llevar al evento?

Activar suscripción de Windows Azure

No te preocupes, que no tienes que saber nada de biología molecular ni ser ingeniero en computación distribuida. Tan sólo tienes que llevar una cosa: una suscripción activa de Windows Azure.

Hay diversas formas de conseguir una suscripción de Windows Azure te animamos a hacerlo desde ya para evitar retrasos en la activación de la misma el día del evento:

  • Activar suscripción gratuita de 30 días.- siguiendo este enlace podrás activar una suscripción gratuita de un mes con un crédito de 150€, más que suficiente para desplegar hasta 20 servidores durante el transcurso del evento sin tener que poner un céntimo de tu bolsillo;

Activar suscripción gratuita de Windows Azure

  • Activar los beneficios de tu suscripción a MSDN.- los suscriptores de MSDN tienen como beneficio una suscripción a Azure de 150$ mensuales, cuyos recursos pueden también utilizarse para este evento. Hot Tip: ¿la empresa donde trabajas es Partner de Microsoft? Comprueba los beneficios de las competencias adquiridas y activa las suscripciones MSDN asociadas a las mismas!

OPCIONAL: llevar un portátil es opcional, aunque recomendable. No necesitarás llevar nada preinstalado ni instalarás nada allí. Simplemente se tratará de desplegar un servicio en Azure a través del mismo navegador, algo de lo que daremos más detalles en el día del evento. El área de “Azk the Expert” estará disponible a lo largo del día para solucionar cualquier problema que tengas.

Vamos a hacer historia. ¡Nos vemos el sábado!

¡Ya se acerca el Global Windows Azure Bootcamp!

bootcamp-300x202El próximo 29 de Marzo se va a desarrollar a lo largo del día y en cerca de 140 localizaciones a nivel del globo el mayor evento global sobre Windows Azure. Se trata de pasar un día aprendiendo y compartiendo conocimientos sobre la plataforma en la nube de Microsoft, a la vez que de forma simultánea se realiza una investigación para el diagnóstico temprano de la diabetes tipo 2.

Desde la comunidades técnicas de España hemos querido hacer un evento muy especial y lo vamos a concentrar en Madrid en la sede de Microsoft, donde estaremos todos los especialistas y MVPs que actualmente estamos día a día trabajando con la plataforma Azure.

La realización de este evento con los líderes de la comunidad de Windows Azure en España manteniendo la asistencia gratuita no sería posible sin la dedicación y duro trabajo de los presentadores, organizadores y contribuciones económicas de otras organizaciones para ayudar a financiar la logística del mismo. Muchas gracias a todos ellos.

El registro a este evento es gratuito -¡Sí! ¡Gratis!- y se realiza a través de Microsoft World Wide Events. Regístrate en el enlace siguientepara estar en Madrid y atender en persona al Windows Azure Bootcamp 2014 en Madrid. ¡No tardes, las plazas son limitadas!

Registro al Global Windows Azure Bootcamp – Madrid

Para más información, visita los siguientes enlaces:

¡Allí nos vemos!

Looking for a Surface 2 Pro 256GB using the Azure Cloud Power

SurfaceSince some weeks ago I have been trying to find a way of buying a Surface 2 Pro 256GB to definitively replace my development laptop. Some videos I have seen on YouTube like having 4 external displays brought my attention and after asking Joe Brinkman and Alberto Diaz about their experience working with the tablet as a dev machine both answered that definitively can replace my laptop (of course with the docking station). The final decision was taken after seeing another thread in the Surface Forums about the gaming experience like playing Call of Duty Ghosts on a Surface Pro 2.If that beast can move those types of games, for sure that can replace my current laptop.

And the problem started…

Looking for a Surface 2 on the stores

I have been trying to find a Surface 2 Pro 256GB in order to have the 8GB RAM in almost all the stores on Internet, and was really surprising that this model is Out of Stock in almost all of them. When finally found that the Microsoft Store at UK, I started to evaluate the problem of not getting the correct warranty if I’m in another country, different AC plugs than Spain, etc. The price it’s not low so the risk of having a problem without a store/warranty was not an option.


So the final decision was to buy it on Spain but same problem. Out of stock. I call the Microsoft Store and they didn’t know about when they could arrive. Bad thing.

I’m a developer, I don’t like doing things twice

I have been checking the Microsoft Store website twice a day since two weeks ago, and I was starting to be tired of doing it. So I was wondering if I could automate the process and receive some type of alert when the devices were in stock again. And then I found the how to create my new minion.

Looking into how the Store page works, I noticed that a GET WebAPI call is done to show the availability of the product:


More interesting was the result of that WebAPI call, since it’s an XML with the stock status for that product:


Idea! Idea! Idea!

If I didn’t want to check the website twice a day, what I would like was just to receive an alert of when the devices were in stock again. Would be nice to receive an e-mail on such event, and would love get an SMS on my mobile!

I always compare Azure and other cloud services like a Lego store. The pieces are there to build solutions, you only need to know about them. So let’s put some pieces in place:

  • Azure Mobile Services: in order to have a scheduled task looking for the device stock at the store. There are other options but the scheduler provided by Mobile Services is sufficient for this purpose and also free when using 1 scheduled task;
  • SendGrid: in order to receive an e-mail notification for stock changes. Again, there are other options but SendGrid offers a free tier for Azure subscribers that allows to accomplish this also for free;
  • Twilio: in order to receive SMS notifications for stock changes. Again, you can signup Twilio for free –no credit card needed- and send up to 1000 SMS (Azure subscribers get $10 when adding credit later to Twilio).

Cool, I love free stuff.

Adding some code to a scheduled task

So with the pieces in mind, the API keys from SendGrid and Twilio in my Notepad++, I started to create an empty Azure Mobile service through the management console.


The only thing inside the mobile service is just an scheduled task configured to run once per hour (my minions must work harder than me!!).


Finally the script code for the scheduler task. Note that I have hidden the API keys, e-mails and phone numbers:

function CheckAvailability() {
    try {
        var url = "http://surface.microsoftstore.com/store/mseea/es_ES/DisplayPage/id.ProductInventoryStatusXmlPage/productID.287012200?_=13";
        var request = require("request");
        request(url, function(error, r, body) {
                if (error) { return console.error(error); }
                if (r.statusCode != 200) { return console.error(r); }
                var xml2js = require('xml2js');
                var parser = new xml2js.Parser();                        
                parser.parseString(body, function (err, result) {
                    if (err) { return console.error(err); } 
                    if (result.InventoryStatusResponse.availableQuantity != "0") {
                    } else {
    catch(e) {

var SendGrid = require('sendgrid').SendGrid;

function sendNotifications(inventoryStatusResponse) {

function sendSMS(inventoryStatusResponse) {
    var httpRequest = require('request');
    var account_sid = "Your_Twilio_Account_SID_here";
    var auth_token = "Your_Twilio_Auth_Token_here";
    var from = "+345550000";
    var to="+3465550001";
    var message = 'The new Surface 2 Pro 256GB is now available at Microsoft Store. Units available: ' 
                    + inventoryStatusResponse.availableQuantity;
    // Create the request body
    var body = "From=" + from + "&To=" + to + "&Body=" + message;
    // Make the HTTP request to Twilio
        url: "https://" + account_sid + ":" + auth_token +
             "@api.twilio.com/2010-04-01/Accounts/" + account_sid + "/Messages.json",
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        body: body
    }, function (err, resp, body) {
        if (err) { return console.error(err); }

function sendEMail(inventoryStatusResponse) {
    console.log('Surface 2 Pro 256GB available at Microsoft Store. Units available: ' 
        + inventoryStatusResponse.availableQuantity + '. Sending notifications...');
    var api_user = 'Your_SendGrid_ApiUser';
    var api_key = 'Your_SendGrid_ApiKey';
    var sendgrid = new SendGrid(api_user, api_key);       
        to: 'foo@mydomain.com',
        from: 'bar@mydomain.com',
        subject:  'Surface 2 Pro 256GB available at Microsoft Store!',
        text:     'The new Surface 2 Pro 26GB is now available at Microsoft Store. Units available: ' 
                    + inventoryStatusResponse.availableQuantity
    }, function(success, message) {
        // If the email failed to send, log it as an error so we can investigate
        if (!success) {
        else {
            console.log('Email notification sent!');

Finally, by commenting the line checking for the availableQuantity != “0”, I got my initial notifications arriving to my devices:




The implementation shown above can be considered a proof of concept –BTW, probably I should not use the Store WebAPI without Microsoft confirmation- of things you can you can do by integrating different cloud services available today, and start using them for free.

The world has changed and is now cloud-connected.

Have you started to think cloud?

Saludos y Happy Coding!

Adding NewRelic support to a DNN Website running as an Azure Cloud Service

screensIn my last blog post announcing the DNN Azure Accelerator 2013 Q4 release, I commented that I was going to publish some posts about how to setup external startup tasks in order to include persistent changes on the cloud service instances without the need of rebuilding the cloud service package.

I will start today with a walkthrough to show how to add NewRelic monitoring to the deployed DNN instance by configuring an external startup task, step by step. I will be doing the same for MS Application Insights as well as other tips and tricks to increase the performance on IIS, just be a little patient these days Smile.

Signup for NewRelic Standard for free

One of the advantages of signing up for Azure, is that there is a lot of free stuff included with your subscriptions, thanks to the agreements done with third party companies like NewRelic. In this case, with each Azure subscription NewRelic gives a Standard subscription for one application giving you fully functional app performance management (includes server and real user management).

In order to activate your NewRelic Standard for free, follow these steps:

  1. In the Windows Azure Management console, click on “New > Store” to open the Store dialog. Once there scroll down until you find the NewRelic, and click on the Next button

    NewRelic Signup
  2. Select from the dropdown list the datacenter location where you want to use the services. You should use the same location where your DNN site will reside –or is currently running on.
  3. Click next to review the purchase of the free service, and click Finish to start provisioning.
  4. After a few seconds, the service will appear in the “Add-ons” section of the Management Portal. The most interesting links at the bottom will: show your current API Key and License Key, needed to deploy the agents later; redirect to the NewRelic Management portal where you can monitor your site once it’s deployed.


At this point, you have provisioned your free NewRelic Standard subscription. Let’s start configuring the DNN Cloud Service to start reporting in the “Applications” section.

Creating the external startup task for the DNN Azure Accelerator

In the NewRelic’s website, you can found how to modify an Azure cloud service package to start monitoring, and in fact, you can go that way by downloading the DNN Azure Accelerator source code from CodePlex. But in this case, instead of rebuilding the cloud service package with Visual Studio, what we are going to use is the new external startup task feature introduced in the latest release.

The steps to build the NewRelic external startup task are in summary:

  • Create a PowerShell cmdlet that will be executed on the role startup
  • Zip the cmdlet with the NewRelic’s agent and upload it to a public URL location
  • Specify the URL and License Key parameters in the “Startup.ExternalTasks” and “Startup.ExternalTasks.KeyValueSettings” configuration settings.

Let’s see one by one.

Create the PowerShell cmdlet

NewRelic provides two different type of agents depending on what you are going to monitor: the .NET Agent, that collects information of your .NET application, real time user monitoring, etc.; and the Server Agent, that collects information from a virtual machine perspective like CPU, memory, running processes, etc.

In this case we will simplify the PowerShell cmdlet to configure only the .NET Agent, but with some modifications you can deploy the server agent as well. Note that for the server agent you would need more than the free tier if you deploy more than one instance on the cloud service (I’m not 100% sure of this, something to ask to NewRelic’s sales support).

The following PowerShell script will install the NewRelic’s .NET Agent into a cloud service running the DNN Azure Accelerator. The license key, the application description and environment are taken from the new Role configuration setting “ExternalStartupTask.KeyValueSetting” that was introduced in the latest build. This value is a collection of key/value pairs, semicolon separated.

#    New Relic installation script for DNN Azure Accelerator (cloud services) - v2.18.35.0
#    This script install only the New Relic .NET Agent. The license key, the application description 
#   and environment are taken from the Role configuration setting "Startup.ExternalTasks.KeyValueSettings" 
#   (it's a collection of key=value pairs, separated by semicolon).

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition;
$newRelicAgentInstallationPath = Join-Path $scriptPath "NewRelicAgent_x64_2.18.35.0.msi"
$logPath = Join-Path $scriptPath "NewRelicInstall.log"

[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.WindowsAzure.ServiceRuntime")

# Writes in the installation log
function Append-Log($text)
    $((Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " - " + $text) >> $logPath
    foreach ($i in $input) {
        $((Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " - " + $i) >> $logPath


# Retrieves configuration settings from the cloud service configuration
function Get-ConfigurationSetting($key, $defaultValue = "")
    if ([Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::IsAvailable)
        Append-Log "The Role Environment is available. Looking the setting: " + $key
        return [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::GetConfigurationSettingValue($key)
    } else {
        Append-Log "The Role Environment isn't available"
    return $defaultValue

# Retrieves the external startup key/value pairs        
function Get-StartupTaskKeyValueParameters()
    $setting = Get-ConfigurationSetting -key "Startup.ExternalTasks.KeyValueSettings"
    Append-Log $("Startup.ExternalTasks.KeyValueSettings: " + $setting)
    $kvSettings = @{}

    $matches = [regex]::Matches($setting, "\s*(?<KEY>[^\=\s]+)\=\s*(?<VALUE>[^\;]+)(\;|$)", @("Ignorecase"));
    foreach ($match in $matches) {
        $kvSettings.Add($match.Captures[0].Groups["KEY"].Value.Trim(), $match.Captures[0].Groups["VALUE"].Value.Trim());

    return $kvSettings

# Installs a .msi file
function Install-MsiFile($msifile, $arguments)
    Start-Process `
         -file  $msifile `
         -arg $arguments `
         -passthru | wait-process

Append-Log "Getting startup task parameters..."
$settings = Get-StartupTaskKeyValueParameters
$licenseKey = $settings["NewRelic.LicenseKey"]
if (!$licenseKey) {
    Append-Log "ERROR: license key not specified. The NewRelic installation cannot be performed"
Append-Log $("License key: " + $licenseKey)

# New Relic Agent installation:
Append-Log "Installing New Relic .NET agent..."
Install-MsiFile $newRelicAgentInstallationPath $(" /norestart /quiet NR_LICENSE_KEY=" + $licenseKey + " INSTALLLEVEL=50 /lv* E:\nr_install.log")

# Modify the configuration file (application name and host in case we are in staging)
Append-Log "Changing the .NET agent configuration file..."
$path = Join-Path (get-item env:"ALLUSERSPROFILE").Value "New Relic\.NET Agent\newrelic.config"
[XML]$newRelicConfig = Get-Content $path

# Application name:
$newRelicConfig.configuration.application.name = $(if ($settings["NewRelic.AppDescription"]) { $settings["NewRelic.AppDescription"] } else { "My DNN Website" })
# Log level (info by default). We will set this to warning
$newRelicConfig.configuration.log.level = "warning"

# If we are in staging, we have to set the staging host
if ($settings["NewRelic.Environment"] -eq "Staging") {
    $newRelicConfig.configuration.service.SetAttribute("host", "staging-collector.newrelic.com")

# Restart IIS in order to load the new configuration
Append-Log "Restarting IIS..."
IISRESET >> $logPath
NET START W3SVC >> $logPath

Append-Log "Done!"

Zip the .NET agent and the script in one file

Note that in the previous script, the .NET agent .msi file was the release, that can be downloaded via NuGet. If you keep this script up to date, you only need to change the $scriptPath variable to match the latest version available. Also note that the script filename must be in the format “Task???.ps1” to tell the DNN Azure Accelerator that must execute this task.

You can download the full zipped external task from this URL:

Specify the settings in the service configuration file

Once you have uploaded the .zip file to a public location –test the URL from your browser first to verify that works-, you need to specify the following settings in the service configuration:

  • “Startup.ExternalTasks”: specify the public internet URL from where the .zip file containing the external startup task will be downloaded
  • “Startup.ExternalTasks.KeyValueSettings”: parameters for the NewRelic external startup task in the following format:

    ”NewRelic.LicenseKey=<LICENSEKEY>; NewRelic.AppDescription=<APPDESCRIPTION>; NewRelic.Environment=<DEPLOYMENTSLOT>”

    where the:
    <LICENSEKEY> is your NewRelic license key that appears in the “Connection info” window of the addon in the Azure Management portal (see step 4 of NR provisioning above)
    <APPDESCRIPTION> is a descriptive name for your DNN deployment
    <DEPLOYMENTSLOT> is the deployment slot of your cloud service: Production | Staging

You can specify these values on a running deployment with the latest DNN Azure Accelerator release and all the configuration will be done automatically, since the modification of the external startup tasks settings recycles the current worker role agents executing again all the startup tasks –the operation will take some minutes to finish.


If you are going to update your deployment from a previous version using a deployment upgrade, you can use the preferred service configuration files from the “/packages” subfolder. Note that you will need to manually replace the “@@” variables in the .cscfg. You can use the one that was previously uploaded to Azure Storage in the “dnn-packages” container as a guide.

Deploy the service with the Accelerator’s wizard

If you are going to deploy a complete new cloud service or you are going to update your current deployment by redeploying the service using the Accelerator wizard, you will need to manually specify the NewRelic startup tasks settings before running the wizard. In order to do this, open in the “/packages” subfolder the .cscfg file that you will use later for deploying in the wizard. As example, if I want to use the “Medium” packages to deploy “Medium-Sized” instances, I need to edit the “/packages/DNNAzureSingleAndMedium_2013Q4.cscfg” file –just use notepad.exe to edit these files-, and locate the “Startup.ExternalTasks” entries, and fill the settings with the values specified in the previous step:



Now run the wizard and follow all the steps until you have your site running. A few minutes later you will notice that in the NewRelic management portal the application starts reporting:



In this article we can follow how we can easily customize the cloud service deployments by using external startup tasks. The example shows how to add the New Relic .NET monitoring agent to a DNN instance running on Azure cloud services, without rebuilding the cloud service package.

Don’t miss the following article where I will be posting a similar one to add Microsoft Application Insights in the same way.

Saludos y Happy coding! and BTW, Happy New Year friends!!!

DNN Azure Accelerator 2013 Q4 Released

cloudWithOThe new version of the DNN Azure Accelerator 2013 Q4 is already available for download with new features and fixes. The package is available as usual at CodePlex:


In this version, the most interesting feature is the ability of specifying the location of external startup tasks without the need of rebuilding the cloud service packages. This functionality was best described in a previous post called “Configuring external startup tasks on an Azure cloud service”.

In the next days I will be posting some examples of startup tasks, like automating the installation of NewRelic or MS Application Insights agents, modifying IIS performance settings, etc.

Release Notes

New Features


  • Fixed an issue on the web role startup, causing an cycling error on deployments using the latest Guest OS agent releases (the symbolic link was not being correctly deleted from the temporal storage)
  • Added "Generate security audits" local security policy for the DNN appPool (needed by WCF services)
  • Changed defualt VHD size to 32GB on the wizard
  • Fixed the password verification on the wizard UI to allow passwords longer than 16 chars

Un saludo & Happy Coding!

¡Ya tenemos ganador de La Guerra de los Drones!

LaGuerraDeLosDrones_Logo_WhiteYa tenemos ganador del concurso de La Guerra de los Drones. Felicidades Marcos Lora Rosa (@magicheron), de La Garriga, Barcelona. Ha conseguido finalizar con éxito y en tiempo el desarrollo de la aplicación ARDrone Draw para Windows Phone 8 y publicarla en la Store. ¡Tu AR Drone 2.0 ya está en camino!

¿Cómo funciona la App?

La aplicación ganadora ha sido diseñada para Windows Phone 8 que permite al usuario controlar al dispositivo AR Drone 2.0 en el modo tradicional, que se basa en unos joysticks virtuales en la pantalla de la aplicación, o en un modo más innovador y divertido que se basa en dibujar trazados en pantalla y hacer que el drone lo siga. El interfaz de la app está muy ´limpio y cuidado así como las animaciones de los menús en los cambios de modo.


photo 1

photo 3

En el video siguiente puedes observar una demo de este modo de vuelo de “dibujo”, en el que al trazar en pantalla las curvas y pulsar el botón de iniciar animación, el ARDrone reproduce la trayectoria dibujada en pantalla.

De nuevo, nuestra más sincera enhorabuena y felicidades por el buen trabajo realizado.

¿Y no ha habido más ganadores?

Pues al cierre de esta edición el único concursante que había conseguido cumplir con todas las bases del concurso -desde la implementación hasta la publicación en la Store- había sido Marcos, por lo que decidimos cerrar esta primera edición del concurso premiando el esfuerzo.

¿Y el resto de apps que estaban en desarrollo o cerca de su finalización? No desesperéis. Hemos tomado nota del poco tiempo que ha habido para la implementación y publicación, pero tampoco queríamos perjudicar a los que habían conseguido cumplir con todos los requisitos. La solución a la que hemos llegado es una segunda edición del concurso, en la que tendréis más tiempo. Permaneced en sintonía.


Desde aquí agradecemos a Parrot y a Microsoft España el apoyo en la celebración de este concurso. Por supuesto, a todas las comunidades técnicas que se han involucrado dando charlas y dedicando parte de su tiempo a compartir un buen rato desarrollando apps de una forma diferente. Y por supuesto a ti, que has estado ahí y sin el que este concurso no hubiera tenido sentido.

Aprovechamos para desearos unas felices fiestas y un próspero año 2014.

La Guerra de los Drones.

Materiales del evento ARDrone + Azure Mobile Services

LaGuerraDeLosDrones_Logo_WhiteMadre mía la de cosas que tengo que hacer para poner las cosas al día. Aquí va una de las que estaban pendientes -mejor tarde que nunca- con los materiales del evento de TenerifeDev sobre el desarrollo de aplicaciones para ARDrone 2.0 y Windows Azure Mobile Services.


Imágenes del evento

Aquí os dejo algunas imágenes, aunque podéis acceder a todas las imágenes del evento a través de la web de TenerifeDev.




Configuring external startup tasks on an Azure cloud service

PaaSTaskWindows Azure cloud services support startup tasks to perform operations before a role starts, like installing a component, enabling a Windows feature, register a COM component, etc. by using .cmd files or just running Powershell scripts. The documentation for running startup tasks in Windows Azure is available on MSDN.

They are really powerful to setup things needed by your role. Since the startup tasks are packaged in your cloud service, the problem comes when you want to use the same cloud service for hundreds of deployments, and you need to customize at least some of these startup tasks per deployment. Or you just simply want to customize the startup tasks without rebuilding and/or redeploying your cloud service.

After thinking on different approaches to implement this scenario without adding more complexity to the application lifecycle management, a good way of doing it would be to have the opportunity to specify startup tasks on a location outside the cloud service package. In summary, to have a startup task that downloads a set of external startup tasks from an Uri and executes them in order.

Let’s see how this can be achieved.

You can download the example code from this Url: http://sdrv.ms/1dY86lt

Adding a startup task to download external startup tasks

ExternalStartupTasksIn the attached example, there is a solution containing a worker role and a cloud service project. The main aspects of this implementations are in the files:

  • ServiceDefinition.csdef
  • ServiceConfiguration.*.cscfg
  • WorkerRole.cs
  • scripts/SetupExternalTasks.cmd
  • scripts/SetupExternalTasks.ps1

Let’s check one by one to fully understand how this works.


In the service definition file (ServiceDefinition.csdef), what we are going to do is to specify a new startup task as follows:

      <Task executionContext="elevated" commandLine="scripts\SetupExternalTasks.cmd" taskType="simple">
          <Variable name="EMULATED">
            <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
          <Variable name="EXTERNALTASKURL">
            <RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/ConfigurationSettings/ConfigurationSetting[@name='Startup.ExternalTasksUrl']/@value" />

The startup task executes a script located on “scripts/SetupExternalTasks.cmd” in “simple” mode (the worker role OnStart event will not occur until the task completes, but you can change this behavior by modifying this attribute or by adding another task with the desired taskType). Two variables are passed:

  • EMULATED: to check if the task is being executed on the emulator or on Azure;
  • EXTERNALTASKURL: the Url of a zip file containing the external startup tasks;


This Url is configured in the ServiceConfiguration.*.cscfg files as any other setting:



As the startup tasks are executed before the role starts, any change on this setting would recycle the role to execute them again. The following code just do this:

        public override bool OnStart()
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            // Setup OnChanging event
            RoleEnvironment.Changing += RoleEnvironmentOnChanging;

            return base.OnStart();

        /// <summary>
        /// This event is called after configuration changes have been submited to Windows Azure but before they have been applied in this instance
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="RoleEnvironmentChangingEventArgs" /> instance containing the event data.</param>
        private void RoleEnvironmentOnChanging(object sender, RoleEnvironmentChangingEventArgs e)
            // Implements the changes after restarting the role instance
            foreach (RoleEnvironmentConfigurationSettingChange settingChange in e.Changes.Where(x => x is RoleEnvironmentConfigurationSettingChange))
                switch (settingChange.ConfigurationSettingName)
                    case "Startup.ExternalTasksUrl":
                        Trace.TraceWarning("The specified configuration changes can't be made on a running instance. Recycling...");
                        e.Cancel = true;


Now let’s take a look to the task that is executed at the beginning. The variables are checked to skip this setup if you are running on a development environment –you may want to remove/comment the first line- or if the Url setting is empty:

if "%EMULATED%"=="true" goto SKIP

cd %ROLEROOT%\approot\scripts
md %ROLEROOT%\approot\scripts\external

reg add HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /d Unrestricted /f
powershell .\SetupExternalTasks.ps1 -tasksUrl "%EXTERNALTASKURL%" >> ExternalTasks.log 2>> ExternalTasks_err.log


Then a folder “external” is created to store all the downloaded stuff inside, to don’t interfere with other scripts in the solution while downloading. Finally the powershell script is called with the Url as parameter. Both standard and error outputs are redirected to log files.


Finally, the powershell script that does all the work is called. Note that the script supports three types of external files: a “.cmd” file; a “.ps1” file; or a “.zip” file that can contain one or more startup tasks:

 param (
    [string]$tasksUrl = $(throw "-taskUrl is required."),
    [string]$localFolder = ""

# Function to unzip file contents
function Expand-ZIPFile($file, $destination)
    $shell = new-object -com shell.application
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
        # Unzip the file with 0x14 (overwrite silently)
        $shell.Namespace($destination).copyhere($item, 0x14)

# Function to write a log
function Write-Log($message) {
    $date = get-date -Format "yyyy-MM-dd HH:mm:ss"
    $content = "`n$date - $message"
    Add-Content $localfolder\SetupExternalTasks.log $content

 if ($tasksUrl -eq "") {

if ($localFolder -eq "") {
    $localFolder = "$pwd\External"

# Create folder if does not exist
Write-Log "Creating folder $localFolder"
New-Item -ItemType Directory -Force -Path $localFolder
cd $localFolder

$file = "$localFolder\ExternalTasks.cmd"

 if ($tasksUrl.ToLower().EndsWith(".zip")) {
    $file = "$localFolder\ExternalTasks.zip"
 if ($tasksUrl.ToLower().EndsWith(".ps1")) {
    $file = "$localFolder\ExternalTasks.ps1"

# Download the tasks file
Write-Log "Downloading external file $file"
$webclient = New-Object System.Net.WebClient

Write-Log "Download completed"

# If the tasks are zipped, unzip them first
 if ($tasksUrl.ToLower().EndsWith(".zip")) {
    Write-Log "Unzipping $localFolder\ExternalTasks.zip"
    Expand-ZIPFile -file "$localFolder\ExternalTasks.zip" -destination $localFolder
    Write-Log "Unzip completed"

    # When a .zip file is specied, only files called "Task???.cmd" and "Task???.ps1" will be executed
    # This allows to include assemblies and other file dependencies in the zip file
    Get-ChildItem $localFolder | Where-Object {$_.Name.ToLower() -match "task[0-9][0-9][0-9].[cmd|ps1]"} | Sort-Object $_.Name | ForEach-Object {
        Write-Log "Executing $localfolder\$_"        
        if ($_.Name.ToLower().EndsWith(".ps1")) {
            powershell.exe "$localFolder\$_"
        elseif ($_.Name.ToLower().EndsWith(".cmd")) {
            cmd.exe /C "$localFolder\$_"
 elseif ($tasksUrl.ToLower().EndsWith(".ps1")) {
    powershell.exe $file
 elseif ($tasksUrl.ToLower().EndsWith(".cmd")) {
    cmd.exe /C $file

 Write-Log "External tasks execution finished"

In the case of a “.zip” file, the scripts expects the startup tasks with the name “Task???.cmd” or “Task???.ps1”, and executes them in order. Note that you can package file dependencies in the zip file such as .msi files, assemblies, other .cmd/.ps1 files, etc. and only the tasks with this pattern will be called by the script.

Seeing it in action

The attached example downloads an external .zip file located at https://davidjrh.blob.core.windows.net/public/code/ExternalTaskExample.zip. This .zip file contains two tasks “Task001.cmd” and “Task002.cmd”. After starting the role, we can verify that in the “scripts” subfolder the following files are created:


The “ExternalTasks_err.log” is empty (0Kb in size), indicating that the execution was successful. We can open the “ExternalTasks.log” to verify that our tasks executed as expected. In this case, the tasks are simply showing some echoes:


Inside the “external” subfolder we can found all the downloaded .zip file, the unzipped contents and another log about the downloading and task processing steps:



What if I need to get a configuration setting value from an external task?

In the case you need to get a service configuration value from a external task, you can use the awesome power of combining Powershell with managed code. The following Powershell function allows you to get a configuration setting value from inside your external startup in a .ps1 file:

[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.WindowsAzure.ServiceRuntime")

function Get-ConfigurationSetting($key, $defaultValue = "")
    if ([Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::IsAvailable)
        return [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::GetConfigurationSettingValue($key)
    return $defaultValue

Once you have defined the function, you can use it with the following syntax. Note that the second parameter for the default value is optional.

$mySetting = Get-ConfigurationSetting "SettingName" "myDefaultValue"


Downloading and executing external startup tasks increase the versatility of the role startup tasks since you don’t need to repackage and upload your cloud services to change the behavior. By simply changing a setting they are automatically downloaded and executed previous starting the worker role.

You can download the example code from this Url: http://sdrv.ms/1dY86lt

Un saludo & Happy Coding!

[Evento] ¡Construye la mejor App y llévate un AR Drone 2.0!

LaGuerraDeLosDrones_Logo_WhiteAtención a la última frikada que estamos organizando a nivel nacional entre todas las comunidades técnicas de Microsoft. Se trata de un concurso de desarrollo de aplicaciones para Windows Phone y Windows RT con el objetivo de controlar remotamente drones AR Drone 2.0 de Parrot.

Partiendo del SDK que ofrece Parrot, de código open source disponible en GitHub y de todo el SDK de desarrollo para Visual Studio, los desarrolladores de las mejores 9 apps serán obsequiados con un AR Drone 2.0. En este enlace puedes encontrar las bases del concurso.


Durante las próximas semanas comenzarán en cada una de las ciudades una serie de formaciones técnicas GRATUITAS sobre cómo programar tu aplicación. De hecho, los drones ya están en las sedes de cada comunidad para que puedas realizar las pruebas oportunas. En la web del concurso puedes informarte acerca de todos los eventos transcurrirán próximamente.

Así que ya sabes: piensa en una idea, ven a las sesiones para aprender cómo desarrollarla, publícala y gana tu AR Drone 2.0.

¿Friki? Ya verás los videos que vamos a ir colgando…

…¿alguien dijo drones recibiendo señales desde un servidor en Windows Azure?

EvoqContentAgradecer a DNN Corp. por la instancia de Evoq Content in the Cloud, que permiten alojar la web actual del concurso.



Evento en TenerifeDev

Titulo: Desarrollando apps de control de AR.Drones en Windows Phone y Windows 8
Descripción: aprende a desarrollar aplicaciones para dispositivos móviles de plataforma Windows y compite con otros equipos a nivel nacional a ver quien construye la app más innovadora. En esta sesión se realizara una introducción al desarrollo de ambas plataformas, centrándonos finalmente en un ejemplo de app para el AR.Drone con el SDK. Veremos en directo como depurar línea a línea de código mientras el cuadricóptero revolotea por la sala. Anímate, forma un equipo, implementa tu idea, y hazte con uno de los 9 drones que hay de premio a las mejores apps.

LogoFecha: 8 de Noviembre de 2013
Hora: 17:00
Lugar: Sala de Grados de la ETSII, La Laguna
Inscripción gratuita pero por razones de aforo es necesario registrarse previamente
URL de registro al evento: http://bit.ly/TenerifeDevDrones
Organiza: TenerifeDev (http://www.tenerifedev.com) – Alberto Díaz, Jose Fortes, Santiago Porras, David Rodriguez

La dirección de la ETSII, recuerda a aquellos alumnos interesados en participar en este evento, que los estatutos de la Universidad de La Laguna (Art. 1.3, Art. 99),  establecen que la ULL "está al servicio del desarrollo integral de los pueblos, de la paz y de la defensa del medio ambiente" y que "en ningún caso se fomentará la investigación en aspectos específicamente bélicos o militaristas" por lo que la ETSII no apoyará proyectos fuera de estas directrices. Entendemos que las aplicaciones de los drones pueden ser útiles en muchos otros aspectos, por lo que animamos a los alumnos interesados a participar en proyectos ligados a las funciones que los estatutos establecen para la Universidad.

Welcome OS Family 4: Windows Server 2012 R2, IIS 8.5 and .NET Framework 4.5.1

logo-net-451This week has been an awesome one for those using Windows Azure to deploy their services. As soon as Microsoft announcing the general availability of Windows Server 2012 R2, the image was available on all Azure Datacenters worldwide to start creating new devices with the latest OS, not only for the Virtual Machines flavor (IaaS), also for Cloud Services (PaaS). This converts Microsoft’s Cloud in the first one allowing to deploy VMs with it.

The new features included in this OS version are really awesome, and if you are publishing a website on Azure via VMs or Cloud Services you will be really-really happy, because two new enhancements included: IIS 8.5 and .NET Framework 4.5.1.

And that isn’t all, seems that Windows Server 2012 deploys a 30% faster than other previous Windows Server OS images on Azure, so deployment operations like redeploying a hosted service, creating staging environments, etc. will be done faster!! Did I mention new price cuts for memory intensive instances?

Application performance

On this framework release, some “most requested features” have been included, like the x64 edit and continue feature, the ADO.NET connection resiliency (I will write a separate blog post only for this one), etc. You can find an overview of this improvements on this MSDN blog post, but I would like to highlight two features because directly affects the performance of DNN running on Windows Azure, a subject that as you may know, I have been working on for the past years. Microsoft has delighted us by running and documenting the performance improvements using DNN Platform, so let’s summarize the results.

ASP.NET App Suspend

Until now, when an application hosted on IIS was idle for some time (20mins by default), the site was terminated in order to preserve server resources. The problem was that with applications like DNN that takes some seconds to warm-up to serve the first web request (let’s call this “cold startup”), a site with low traffic would appear really slow because would spend more time warming the application pool than serving the contents. The workarounds were to increase the Idle Time-out property of the pool, or when not having access to the IIS configuration, to use external periodic webrequests to avoid the application being shutting down. But this techniques were in detriment of server’s resources and many hosters were banning this type of webrequests to not end up with the server shared resources.

This new feature allows applications hosted on IIS 8.5 to be suspended instead of being terminated, so when the site is shutdown because of the idle timeout, instead of completely killing the worker process, all the state is saved into disk. A new webrequest to the application pool causes to bring the worker process again back into memory, and for the case of DNN, this means around a 90% of improvement. This really rocks!!

ASP.NET App Suspend

Check this video to see the experiment done by Microsoft guys that led to the numbers above.


If you want to know more about this new feature, check this MSDN blog post from The .NET Team.

Multi-core JIT (MCJ) for ASP.net

The second great improvement in application performance with the .NET Framework 4.5.1 release is the Multi-core JIT support for applications using Assembly.LoadFrom and Appdomain.AssemblyResolve like DNN Platform, so if your are using a Medium sized or greater VM on Azure (VMs with more than one core), you will notice a good improvement on cold startups.


Enabling the awesome features

The Multi-core JIT feature is enabled by default if you use Windows Server 2012 R2 or just upgrade to .NET Framework 4.5.1, so you don’t need to do anything to turn it on. The ASP.net App Suspend feature can be enabled on IIS 8.5 in the application pool advanced settings:


New service package for cloud services

While using Virtual Machines (IaaS), this can be easily achieved by deploying the new Windows Server 2012 R2 server image. But to get these benefits on a Cloud Service (PaaS) when using the DNN Azure Accelerator you will need to use the latest accelerator’s service package because as fix was needed.



What fix? I tested today that while changing the OS to Windows Server 2012 R2 instance, the service was cycling on the startup tasks. The cause of this was that the ocsetup.exe used to install the remote management service -that is needed to setup WebDeploy- is no longer included on the system32 folder on WinSrv2012 R2.

The new way of enabling features is by using “dism”, so after doing the following changes on the startup task (check http://forums.iis.net/t/1171432.aspx for more info), all worked fine:

   1:  if "%EMULATED%" == "true" goto SKIP
   2:  if not "%ENABLED%" == "true" goto SKIP
   4:  dism /online /enable-feature /featurename:IIS-WebServerRole 
   5:  dism /online /enable-feature /featurename:IIS-WebServerManagementTools
   6:  dism /online /enable-feature /featurename:IIS-ManagementService
   7:  reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WebManagement\Server /v EnableRemoteManagement /t REG_DWORD /d 1 /f  
   8:  net start wmsvc >> SetupIISRemoteMgmt_log.txt 2>> SetupIISRemoteMgmt_err.txt
   9:  sc config wmsvc start=auto
  11:  :SKIP
  13:  EXIT /B 0

The new packages are available as an addon to the current DNN Azure Accelerator that you can download from CodePlex, called “DNN Azure Accelerator OS Family 4 packages”. Just download the .zip file and unzip it into the “/packages” folder in the accelerator. You will see those packages in the package selection step in the wizard.


After deploying an instance with one of this new packages, you will notice that the DNN site is running on top of IIS 8.5.


Hope this helps. If you have any question, just drop a comment on the post.


P.S. Have you seen the IIS 8.5 default page? Not yet? Here a screenshot Smile


¡Windows Azure MVP 2013!

Wow! Wow! Wow!!

MicrosoftMVPLogoVerticalHoy hay motivo de celebración. Cual ha sido mi satisfacción al ir a comprobar la bandeja de entrada y ver un correo con asunto “¡Enhorabuena MVP de Microsoft 2013!”, casi me da un patatús de alegría.

Para los que no sepan de qué va el tema –cosa harto difícil para aquellos que leen este blog- se trata de un nombramiento por parte de Microsoft en reconocimiento a la contribución realizada en las comunidades técnicas a lo largo del pasado año, en este caso en concreto en el área de Windows Azure.


En este enlace de MSDN se encuentra más información acerca de este anuncio, así como en el propio portal de Microsoft MVP.

Quiero agradecer a todos los que han puesto de un modo u otro su granito de arena para que haya sido posible. A la familia que cada vez me ve menos el pelo pero siguen demostrándome todo su apoyo; a los amigos que siguen estando ahí en todo momento; a los compañeros de trabajo que considero como parte de la familia; a los compañeros de TenerifeDev con los que tantos buenos ratos he pasado; a todos los que me han dado su apoyo leyendo este blog, dándome sus opiniones y convertirme en mejor profesional; y por supuesto a Microsoft, tanto por el reconocimiento como por su apoyo a la comunidad, algo que llega a convertirse en un estilo de vida.

Y en especial a ti Carmen, que has sido y eres la que me ha soportado durante tanto tiempo delante de la pantalla sin bajar la palanca de la luz. Te quiero.

¡Un saludo y Happy Coding!

David Rodriguez

Posted: 1/10/2013 20:35 por David Rodríguez | con no comments
Archivado en:
Más artículos Página siguiente >