Wed, 16 Nov 2011

Calling the Windows Azure Service Management API with the New .publishsettings File

This week, we added a new way to get a management certificate set up to interact with the Windows Azure Service Management API. There’s a new page in the Windows Azure portal (https://windows.azure.com/download/publishprofile.aspx). Browsing there does two things:

  1. It generates a management certificate and adds it to all the subscriptions you have.
  2. It offers you a download of a .publishsettings file, which contains that certificate and the list of subscription IDs.

With the new November release of the Windows Azure tools for Visual Studio, you can simply import this file and then start publishing to Windows Azure.

You can also use this file from your own code, since it contains the subscription ID(s) and management certificate you need to have to make calls to the Service Management API. The format of the file is quite simple. It contains a base64-encoded .pfx file (the certificate) and a list of subscription IDs, all in XML. The following code consumes a .publishsettings file and uses it to print out a list of all your Windows Azure applications:

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;

namespace ListServices
{
    class Program
    {
        static void Main(string[] args)
        {
            var profile = XDocument.Load(args[0]);
            var req = (HttpWebRequest)WebRequest.Create(
                string.Format("https://management.core.windows.net/{0}/services/hostedservices",
                profile.Descendants("Subscription").First().Attribute("Id").Value));
            req.Headers["x-ms-version"] = "2011-10-01";
            req.ClientCertificates.Add(new X509Certificate2(Convert.FromBase64String(
                profile.Descendants("PublishProfile").Single()
                .Attribute("ManagementCertificate").Value)));
            XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";
            Console.WriteLine(string.Join("\n",
                XDocument.Load(req.GetResponse().GetResponseStream())
                .Descendants(xmlns + "ServiceName").Select(n => n.Value).ToArray()));
        }
    }
}

As you can see, it’s pretty easy to use this file. I plan to update a lot of my own tools to consume .publishsettings files. It’s a much easier flow than generating a certificate locally and uploading it via the portal. (But you can still do that if you want.)

[UPDATE 1:55pm] Want more? Wade Wegner wrote a great related post: “Programmatically Installing and Using Your Management Certificate with the New .publishsettings File