2 out of 6 rated this helpful - Rate this topic

Code Quick Start: Create a console application that lists your Windows Azure hosted services

Updated: November 14, 2011

The following steps describe how to create a console application that uses the Windows Azure Service Management REST API. Specifically this sample will use the List Hosted Services operation. Other Service Management REST operations could be called in a similar manner.

This sample does not get deployed to the Windows Azure cloud; rather, it shows you how to interact with the Windows Azure service management features through a stand-alone application.

  1. If you haven’t already done so, add a management certificate for your subscription within the Windows Azure management portal. For information about management certificates and their use in authenticating calls to the Service Management REST API, see Manage Certificates in Windows Azure and Authenticating Service Management Requests. Note that the management certificate must contain a key length of at least 2048 bits. There are multiple techniques for creating a certificate. For purposes of this topic, we’ll use the following makecert command, which can be run from a Visual Studio command prompt:

    makecert -r -pe -a sha1 -n "CN=My Azure Management Certificate" -ss My -len 2048 -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" -sy 24 myazuremanagementcert.cer
    

    This makecert command creates a user certificate that is stored in the My (Personal) store. The certificate contains a key that is 2048 bits in length, and the certificate is also saved to the file named myazuremanagementcert.cer. To associate this certificate with your subscription, log in to http://manage.windowsazure.com, navigate to Hosted Services, Storage Accounts, and CDN, click Management Certificates, and then click the Add Certificate icon. Using the Add New Management Certificate dialog, choose a subscription, and then select the certificate that you created using makecert (myazuremanagementcert.cer).

  2. Launch Microsoft Visual Studio 2010.

  3. On the File menu, click New, and then click Project.

  4. Within the New Project dialog, navigate to Installed Templates, Visual C#, and click Windows.

  5. Click Console Application. Choose .NET Framework 4 from the drop down list. If needed, modify the Location: field, which indicates where your solution will be stored. For purposes of this sample, use ServiceManagementSample as the name of the project. Click OK to close the New Project dialog.

  6. From the Project menu, click Add Reference…. Within the .NET tab of the Add Reference dialog, select System.Security and click OK.

  7. Open the Add Reference dialog again and add a reference to System.Net.

  8. Modify Program.cs to contain the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net;  // For HttpWebRequest and HttpWebResponse classes.
    using System.Security.Cryptography.X509Certificates;  // For certificate-related classes.
    using System.IO;  // For Stream classes.
    
    namespace ServiceManagementSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    // X.509 certificate variables.
                    X509Store certStore = null;
                    X509Certificate2Collection certCollection = null;
                    X509Certificate2 certificate = null;
    
                    // Request and response variables.
                    HttpWebRequest httpWebRequest = null;
                    HttpWebResponse httpWebResponse = null;
    
                    // Stream variables.
                    Stream responseStream = null;
                    StreamReader reader = null;
    
                    // URI variable.
                    Uri requestUri = null;
    
                    // Specify operation to use for the service management call.
                    // This sample will use the operation for listing the hosted services.
                    string operation = "hostedservices";
    
                    // The ID for the Windows Azure subscription.
                    string subscriptionId = "your_subscription_id";
    
                    // The thumbprint for the certificate. This certificate would have been
                    // previously added as a management certificate within the Windows Azure management portal.
                    string thumbPrint = "your_certificate_thumbprint";
    
                    // Open the certificate store for the current user.
                    certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    certStore.Open(OpenFlags.ReadOnly);
    
                    // Find the certificate with the specified thumbprint.
                    certCollection = certStore.Certificates.Find(
                                         X509FindType.FindByThumbprint,
                                         thumbPrint,
                                         false);
    
                    // Close the certificate store.
                    certStore.Close();
    
                    // Check to see if a matching certificate was found.
                    if (0 == certCollection.Count)
                    {
                        throw new Exception("No certificate found containing thumbprint " + thumbPrint);
                    }
    
                    // A matching certificate was found.
                    certificate = certCollection[0];
                    Console.WriteLine("Using certificate with thumbprint: " + thumbPrint);
    
                    // Create the request.
                    requestUri = new Uri("https://management.core.windows.net/"
                                         + subscriptionId 
                                         + "/services/" 
                                         + operation);
    
                    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUri);
                    
                    // Add the certificate to the request.
                    httpWebRequest.ClientCertificates.Add(certificate);
                    
                    // Specify the version information in the header.
                    httpWebRequest.Headers.Add("x-ms-version", "2011-10-01");
    
                    // Make the call using the web request.
                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    
                    // Display the web response status code.
                    Console.WriteLine("Response status code: " + httpWebResponse.StatusCode);
    
                    // Display the request ID returned by Windows Azure.
                     if (null != httpWebResponse.Headers)
                     {
                         Console.WriteLine("x-ms-request-id: "
                         + httpWebResponse.Headers["x-ms-request-id"]);
                     }
    
                    // Parse the web response.
                    responseStream = httpWebResponse.GetResponseStream();
                    reader = new StreamReader(responseStream);
                    // Display the raw response.
                    Console.WriteLine("Response output:");
                    Console.WriteLine(reader.ReadToEnd());
    
                    // Close the resources no longer needed.
                    httpWebResponse.Close(); 
                    responseStream.Close(); 
                    reader.Close();
                }
                catch (Exception e)
                {
                 
                    Console.WriteLine("Error encountered: " + e.Message);
                    
                    // Exit the application with exit code 1.
                    System.Environment.Exit(1);
                    
                }
                finally
                {
                    // Exit the application.
                    System.Environment.Exit(0);
                }
    
            }
        }
    }
    
    
  9. Modify the values assigned to subscriptionId and thumbPrint to use your Windows Azure subscription ID and your certificate thumbprint, respectively. You can use the Windows Azure management portal, http://manage.windowsazure.com, to determine both of those values. Specifically, within http://manage.windowsazure.com, you can navigate to Hosted Services, Storage Accounts, and CDN, and then click Management Certificates. Click your subscription, and the subscription ID will be displayed in the Properties pane; right-click the subscription ID, click Copy, and then paste it into your code as the value assigned to subscriptionId. Similarly, retrieve your certificate thumbprint from http://manage.windowsazure.com: click the certificate to bring up the Properties pane, right-click the thumbprint, click Copy, and then paste it into your code as the value assigned to thumbPrint.

  10. Save Program.cs.

  11. On the Debug menu, click Start Without Debugging to run your program.

The sample creates an instance of the HttpWebRequest class using the httpWebRequest variable, which represents the web request to use for the Service Management REST API call. The web request contains a certificate that corresponds to one of the management certificates that you have previously added to your Windows Azure subscription. The sample finds the local certificate through the System.Security.Cryptography.X509Certificates.Find method, performing the search using the certificate thumbprint. As shown in the image earlier in this topic, the Windows Azure management portal displays the thumbprint for your management certificates, making it convenient for you to use the thumbprint in your code. You could use a different technique to assign the proper certificate to the request (for example, performing the certificate search based on subject name or displaying a user interface dialog that allows the user to select a certificate); the important aspect is the certificate must have previously been uploaded to the Windows Azure management portal for your subscription in order for the call to successful. Additionally, the line of code:

certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

is a constructor for the System.Security.Cryptography.X509Certificates.X509Store class, and it instructs the application to open the My store for the current user. Recall that the makecert command above specified the My store (via –ss My) as the certificate store when creating the certificate on behalf of the user. If however you wanted to use a certificate from a different store, you can modify the StoreName setting used by the X509Store constructor. Similarly, if you want to use a local machine certificate instead of the current user certificate, modify the StoreLocation setting in the X509Store constructor (specifically, to be StoreLocation.LocalMachine).

The requestUri variable is assigned the values needed for a “list hosted services” operation, as documented at List Hosted Services. The requestUri variable is used for the creation of the httpWebRequest variable. The certificate is added to the web request variable.

The x-ms-version value of 2011-10-01 is added to the header; this represents the version of the Windows Azure Service Management REST API to use for the operation. For information about the values to use for x-ms-version, see Service Management Versioning. The remaining code submits the request and displays the response. For more information about the format of the response header and body for this particular sample, see List Hosted Services.

A variety of other operations are available in the Service Management REST API. For example, you can create a deployment by using the Create Deployment operation, or list storage accounts by using the List Storage Accounts operation. The List Hosted Services operation uses the GET method, which is the default method for the web request, so specifying GET within the code is not required. Other operations, however, may require specifying the method. For example, the Create Deployment operation uses the POST method, in which case the code would contain the following line:

httpWebRequest.Method = "POST";

As another example of using a method other than GET, the Delete Certificate operation uses the DELETE method. Consult the documentation for each operation to determine the method that is required for the web request, as well as to learn details about the request and response formats. For more information about the available operations, see Windows Azure Service Management REST API Reference.

For information about error codes that could be returned by the Service Management API, see Service Management Status and Error Codes.

See Also

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.
facebook page visit twitter rss feed newsletter