Un paseo por las nubes

Un blog acerca de Cloud Computing...
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?

Keyboard_Low_Res

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?

Solution

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:

image

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>

image

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.

FileNameTooLong

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

-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

PowerShellIseResult

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.

Conclusion

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:

MicrosoftAzure

Microsoft Azure

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

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.

UniversalApps

Universal Apps para dominarlos a todos

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

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.

image

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.

image

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

image

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:

AttachedDisks

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:

SourceImageName

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

DifferentVMSourceImagenames

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

GetAzureVMImageName

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

Conclusion

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.

HF-and-Diabetes-Glycosylation-150.small_

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.

Tweet

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:

GET-WebAPI

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

StockStatus

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.

MobileService

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!!).

ScheduledTask

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") {
                        sendNotifications(result.InventoryStatusResponse);        
                    } else {
                        console.warn(result.InventoryStatusResponse.inventoryStatus);    
                    }
                });
        });            
    }
    catch(e) {
        console.error(e);
    }
}

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

function sendNotifications(inventoryStatusResponse) {
    sendSMS(inventoryStatusResponse);
    sendEMail(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
    httpRequest.post({
        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); }
        console.log(body);
    });    
}

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);       
    sendgrid.send({
        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) {
            console.error(message);
        }
        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:

EmailNofitication

Phone

Conclusion

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.
    NewRelicSignup2
  3. Click next to review the purchase of the free service, and click Finish to start provisioning.
    NewRelicSignup3
  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.
    NewRelicProvisioned

    NewRelicConnectionInfo
    NewRelicPortal

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"
    Break
}
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")
}
$newRelicConfig.Save($path)

# 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 2.18.25.0, 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.

CSCFGFile0

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:

 CSCFGFile1

CSCFGFile2

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:

NewRelicApp

Conclusion

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:

http://dnnazureaccelerator.codeplex.com/

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

Fixes

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

ARDroneDraw

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.

Agradecimientos

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.

Slides

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.

DSC_0044

DSC_0029

DSC_0017

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.

ServiceDefinition.csdef

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

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

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;

ServiceConfiguration.cscfg

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

Settings

WorkerRole.cs

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;
                        return;
                }
            }
        }

scripts/SetupExternalTasks.cmd

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
if "%EXTERNALTASKURL%"=="" 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

:SKIP
EXIT /B 0

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.

scripts/SetupExternalTasks.ps1

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 "") {
    exit
 }

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
$webclient.DownloadFile($tasksUrl,$file)

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:

FilesCreated

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:

TasksLog

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:

ExternalTasks

SetupTasksLog

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"

Conclusion

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.

drone

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.

http://www.laguerradelosdrones.com/

 

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.

IISPerformance

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.

MultiCoreJIT

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:

IdleTimeoutAction

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.

OSFamily4

OSFamily4_b

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
   3:   
   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
  10:   
  11:  :SKIP
  12:   
  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.

OSFamily4_c

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.

DNN_PaaS_4.5.1

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

Thanks.

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

localhost

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

Recognition

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:
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 http://www.windowsazure.com/en-us/downloads/#cmd-line-tools

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.

AzureSubscriptions

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("http://checkip.dyndns.com") -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.

RuleThemAll

Hope this helps,

David Rodriguez

Posted: 25/9/2013 11:40 por David Rodríguez | con no comments
Archivado en:
DNN Azure Accelerator 2013 Q3 Released

DNNPoweredByAzureHi, today I have released a new version of the DNN Azure Accelerator, the tool to deploy DNN Platform instances on Windows Azure by using cloud services (PaaS model).

You can download the latest version from CodePlex:

New features

The new features included in this release need deeper details:

  • Packages and solution upgraded to Azure SDK 2.1: all the packages has been rebuilt by using the latest Azure SDK version available, that comes with more features and support for the latest cloud services features. Check the Azure SDK 2.1 release notes for more information. Note that the previous Accelerator packages were built using the SDK 1.8;
  • Changed the use of a mapped network drive for a symbolic link: to avoid remapping issues executing “net.exe use” and “net.exe delete” commands, the new method for mapping the network location has been introduced by using a symbolic link to the network share. As a consequence, you will no longer see the X: mapped network drive. To access the drive contents:
    • From the webrole that mounted the drive, you can access the drive contents by browsing F: drive (or B: if it’s the first mount)
    • From any webrole, included the one that mounted the drive, you can access the drive contents by browsing “C:\Resources\Directory\<RoleDeploymentId>.DNNAzure.SitesRoot\root”. Note that the alias “C:\Resources\Directory\sites\root” is also available, and it’s the one being used by IIS
  • Support for Web Platform Installer custom feeds: now you can specify a custom feed Url for Web Platform Installer, so you can automate the installation of custom addons using this way. To build your own custom feeds, check this blog post.

Another important thing that changed on this release, is that Azure Connect is no longer supported in favor of Virtual Network, so the Connect step in the Wizard has been removed. The new step to setup Virtual Network through the wizard has not been included in this release, but you can get it working by including your virtual network settings directly on the .cscfg files before starting to create the cloud service. For more information about how this can be achieved, check the Windows Azure Virtual Network Configuration Schema documenation.

Release notes

New Features

  • Packages and solution upgraded to Azure SDK 2.1
  • Changed the use of a mapped network drive for a symbolic link to avoid remapping issues (you will not see the mapped X: drive anymore)
  • Support for Web Platform Installer custom feeds
  • Rebranding changes

Fixes

  • Fix for the CA2 certificate thumbprint that was being ignored
  • Fix for WebDeploy and FTP services while working on HA mode
  • Fixes around the drive unmount/mount logic when a failure is detected
  • Fix to include the databaseOwner and objectQualifier settings while creating the portal aliases for the Offline site
  • Fix to shorten the symbolic link path length (see http://geeks.ms/blogs/davidjrh/archive/2013/06/18/path-too-long-when-using-local-storage-in-an-azure-cloud-service.aspx for more info)
  • Implemented the RoleEnvironment.StatusCheck to programatically change the instance status from Busy to Ready after successfully setting up the IIS
  • Fix on the Compete for the lease process, causing a "Value cannot be null" exception after a deployment upgrade
  • Fix to modify the default connection limit to a higher value to avoid inrole caching connection timeouts
  • Fix to avoid 404 errors while calling the automatic installation process
  • Fix to add support for East US and West US in the accelerator Wizard

Deprecated

  • Azure Connect has been deprecated in favor of Virtual Networks. All Azure Connect support has been removed

 

Un saludo y happy coding!

[Event] CloudBurst 2013: the Sweden Windows Azure Group Developer Conference

CloudBurst2013CloudBurst is a Windows Azure developer conference run by the Sweden Windows Azure Group (SWAG). The event features two days of sessions from Windows Azure community and industry leaders and provides real-world content for Windows Azure developers and those wanting to explore the platform. The focus will be on developing Windows Azure applications and real-world cloud-based solutions.

The event will run for two days on September 19 - 20, 2013 at the headquarters of Microsoft in Stockholm, where the "top" Azure MVPs will share sessions around the Windows Azure platform. Organizers for SWAG are the two Swedish Windows Azure MVPs Alan Smith and Magnus Mårtensson.

The event is free to attend and if can’t go to Stockholm for the date don’t worry, the event will be streamed via Microsoft World Wide Events. You have all the information on the CloudBurst 2013 website:

CloudBurst 2013 event information

And don’t loose the “DNN Cloud Services – Under the Hood” session!

ReadySetGoIt is my pleasure to participate as a speaker in a session to discuss how we implemented DNN Cloud Services on the Windows Azure platform. For an hour I will be showing some details of the most interesting subsystems as the DNN Verification Extension Service created using Azure cloud services and messaging queues; how we have deployed about 20,000 instances of product trials with Windows Azure Pack for Windows Server on Virtual Machines and all fully automated; or how we have built a backend system using a CQRS pattern and able to deploy DNN instances on any infrastructure, from web Sites to Cloud Services.

See you in Stockholm!

Un saludo y “Happy Kodning”!!

PS: Did I tell you that you can still get an Aston Martin? Smile

Más artículos Página siguiente >