Syntax Highlighter

martes, 31 de diciembre de 2013

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*(?[^\=\s]+)\=\s*(?[^\;]+)(\;|$)", @("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:
$ = $(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", "")

# 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!!!

domingo, 22 de diciembre de 2013

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!

sábado, 21 de diciembre de 2013

¡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.

jueves, 28 de noviembre de 2013

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.




viernes, 1 de noviembre de 2013

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:

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

// 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\"
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\"
Expand-ZIPFile -file "$localFolder\" -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 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:

Un saludo & Happy Coding!

lunes, 28 de octubre de 2013

[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:
Organiza: TenerifeDev ( – 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.

domingo, 20 de octubre de 2013

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

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 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 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


martes, 1 de octubre de 2013

¡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

miércoles, 25 de septiembre de 2013

Windows Azure PowerShell: One script to rule them all

Are you in mobility and you have lots of SQL Azure DB Servers to manage? Does your public IP address change often and you’re sick of having to manually change the SQL Azure firewall rules?

Good news, I’m going to show you a PowerShell script to automatically add a firewall rule to ALL your SQL Azure servers in ALL your subscriptions for your current public Internet IP Address.

PowerShellDownloadBefore start, just be sure that you have installed the latest Windows Azure PowerShell package, that you can download from

Setup your WA PowerShell subscriptions

The first part after downloading the Windows Azure PowerShell package is to setup the subscriptions you have access to. You will need to do this process only once, since the configuration settings will be stored in your profile, but perhaps you would like to revisit it later to add more subscriptions.

Configuring subscriptions by importing a .publishsettings file

The fastest way to setup the subscriptions is by importing a .publishsettings file containing an encoded management certificate data and subscription Ids:

1) Download your publish settings file:

PS C:\> Get-AzurePublishSettingsFile

This will open a browser that, after introducing your LiveId, will automatically download your .publishsettings file. This file contains credentials to administer your subscriptions and services, so be sure to store it in a secure location or delete after use.

2) Import your .publishsettings file:

PS C:\> Import-AzurePublishSettingsFile MyAzureCredentials.publishsettings

These settings will be stored inside “C:\Users\<UserName>\AppData\Roaming\Windows Azure PowerShell” folder.

Configuring subscriptions by using self-signed management certificate

Another way to setup your subscriptions would be to use your own self-signed management certificates, to avoid the automatic creation of management certificates in all your subscriptions and giving you more control on which subscriptions you are going to manage via PowerShell.

1) Create and Upload a Management Certificate for Windows Azure. Follow the instructions described in this MSDN article.

2) Run the following PowerShell script to access your subscription from PowerShell:

$subscriptionId = '<type your subscriptionId here>'
$subscriptionName = '<type a subscription name here>'
$thumbprint = '<paste your management certificate thumbprint here>'
$mgmtCert = Get-Item cert:\\CurrentUser\My\$thumbprint
Set-AzureSubscription -SubscriptionName $subscriptionName -SubscriptionId $subscriptionId -Certificate $mgmtCert

You can repeat this operation for each subscription you want to manage from PowerShell.

Finally, with both ways of configuring your Azure Subscriptions, you can verify which subscriptions you have setup by running “Get-AzureSubscription” Cmdlet.


One script to rule them all

Now that we have setup the subscriptions, the intention is to create a firewall rule in ALL the SQL Azure servers under ALL my subscriptions for my current public IP address, in order to manage them by using SQL Server Management Studio or whatever other tool.

Based on Alexander Zeitler’s blog post on the matter, I have added some modifications to build the following script that you can save in .ps1 file (I have called it RuleThemAll.ps1 Smile).

# Set a RuleName
$ruleName = "David Laptop"
# Get your public Internet IP Address
$externalIP = (New-Object net.webclient).downloadstring("") -replace "[^\d\.]"
# Loop all your subscriptions
Get-AzureSubscription | ForEach-Object { 
    Select-AzureSubscription $_.SubscriptionName
    # Loop all your SQL DB servers
    Get-AzureSqlDatabaseServer | ForEach-Object {
        $rule = Get-AzureSqlDatabaseServerFirewallRule -ServerName $_.ServerName -RuleName $ruleName
        if (!$rule) {
            New-AzureSqlDatabaseServerFirewallRule $_.ServerName -RuleName $ruleName -StartIpAddress $externalIP -EndIpAddress $externalIP 
        else {
            Set-AzureSqlDatabaseServerFirewallRule $_.ServerName -RuleName $ruleName -StartIpAddress $externalIP -EndIpAddress $externalIP 

After a while, you will have the rule enabled in all your servers in all your subscriptions.


Hope this helps,

David Rodriguez

Related Posts Plugin for WordPress, Blogger...