Windows Azure Management Libraries - managing cloud infrastructure from .NET applications

Original author: Brady Gaster
  • Transfer
  • Tutorial
image

This article describes the recently released Windows Azure Management Libraries designed to manage the cloud infrastructure, services, and storage elements hosted on Windows Azure from .NET applications . Libraries are described using code samples from a WPF application.

What is Windows Azure Management Libraries?


With the release of the Windows Azure Management Libraries, a large portion of the Windows Azure cloud infrastructure can be accessed and automated from .NET applications. These libraries work on top of the functions of the open REST API platform and their release is intended to facilitate the development of the developer with the cloud infrastructure.

The library preview, available today, includes support for Cloud Services, virtual machines and networks, Web sites, Web sites, storage accounts, and infrastructure elements such as Affinity Groups.

We spent a lot of time designing the natural .NET Framework API, which transparently represents the underlying open REST API. It was very important for us to present these services using modern approaches familiar to developers used on the .NET platform:

  • Portable Class Library (PCL) support for .NET Framework 4.5, Windows Phone 8, Windows Store, and Silverlight;
  • distribution in the form of NuGet packages with a minimum of dependencies to facilitate versioning;
  • support for asynchrony and asynchronous operations based on elements of the async / await platform (with easy ability to implement synchronous overloaded methods);
  • common infrastructure for unified error handling, tracing, configuration, and HTTP pipeline management;
  • Designed for ease of testing and using mocking
  • built on the basis of popular libraries such as HttpClient and Json.NET.

These packages offer you the rich capabilities and ease of managing, automating, deploying, and testing WIndows Azure cloud infrastructure. Using them, you can manage virtual machines, cloud services, virtual networks, websites and key infrastructure components of the platform.

Beginning of work


As with any other SDK, in order to find out how we can work with it, it is best to learn a little code. No code should be written to solve a problem that does not actually exist, so let's first state what problem Windows Azure Management Libraries solve:
I have a process that I run on Windows Azure as a Worker Role. Everything works great, but this process, in fact, needs to be run only a few times a week. It would be great to be able to get a new service, put my code into it and then start its execution. It would be very good if, after executing the service, the code reported this back, so that we could delete it automatically. Sometimes, I forget to turn off this service manually, so that I may have an extra waste when it stays on after executing the code. It would be great to be able to automate the creation of the infrastructure I need, its launch and subsequent self-destruction.
Prior to the advent of the Windows Azure Management Libraries (WAML for short, though not officially), solving the described problem was not an easy task. True, there are already a number of excellent opensource libraries from the community that offer the .NET layer for managing Windows Azure services, however, none of them have the full implementation of the Windows Azure Management REST API functions or the full implementation of C # features. When creating your own layer for managing the power of the Windows Azure cloud, you will definitely have to write your own HTTP / XML code to exchange requests with the REST API. This is not the most interesting thing to do in life. A boring and boring job, especially after you implement your second dozen of hundreds of API methods.

Installing Management Libraries


I decided to implement the task in the form of a simple WPF application that will run on my desktop. Since I will have a cloud service with a working role running in the cloud, I have combined all three projects into a single solution, which you can see below: You probably noticed that I was preparing to add several NuGet packages to my application. This is because the Windows Azure Management Libraries are distributed as separate NuGet packages. I am going to select the Microsoft.WindowsAzure.Management.Libraries package and it will install all the libraries available in Management Libraries alone. If I want to manage only one aspect of Windows Azure, then instead of adding all the libraries, I can install only one specific package, for example,

a123

Microsoft.WindowsAzure.Management.WebSites , which offers functionality to manage only the Windows Azure Web Sites infrastructure. After adding a link to the package, I have everything I need to configure client authentication between my WPF application and the Windows Azure REST API.

a124



Client Authentication


The first implementation of user authentication that we wrote for WAML and Windows Azure was based on the X509 certificate mechanism. Recently, Windows Azure for .NET SDK 2.2, Visual Studio, and PowerShell have added built-in account-based authentication. We are currently working on its support in WAML. The WAML release available today supports authentication only on the basis of certificates, however, stay tuned, we are working to add support for authentication based on accounts to the library.

I will not focus on discussing the use of certificate-based authentication. On the contrary, I intend to proceed as quickly as possible to a discussion of functional things in our article. I need information on just two elements to connect to the Windows Azure REST API:

  • Subscription ID
  • Management Certificate

I got these values ​​from one of my publish settings files. Below you can see the XML- contents of such a file: Using the key identifier and the subscription later in my code, I can invoke a method GetCredentials , which returns an instance of an abstract class SubscriptionCloudCredentials , which we use in the code library Management Library for the submission of data on the parameters of user access. With this approach, if I want to add account-based authentication in the future, then it will be much easier for me to replace the authentication mechanism. The code for the CertificateAuthenticationHelper class from my example is shown below:

a125



using Microsoft.WindowsAzure; 
using System; 
using System.Security.Cryptography.X509Certificates; 
namespaceMyCloudServiceManager 
{ 
     internalclassCertificateAuthenticationHelper 
     { 
         internalstatic SubscriptionCloudCredentials GetCredentials(string subscrtionId, 
             string base64EncodedCert) 
         { 
             returnnew CertificateCloudCredentials(subscrtionId, 
                 new X509Certificate2(Convert.FromBase64String(base64EncodedCert))); 
         } 
     } 
}

Now, I will write a controller class that will work on the interaction between the WPF application and Management Libraries. 

Control layer


In order to take into account all the possible parameters that will be used in my service, I created the ManagementControllerParameters class . This class contains all the data that I will need to create services and host my code in the cloud.

namespaceMyCloudServiceManager 
{ 
     internalclassManagementControllerParameters 
     { 
         internalstring Region { get; set; } 
         internalstring StorageAccountName { get; set; } 
         internalstring CloudServiceName { get; set; } 
         internalstring PackageFilePath { get; set; } 
         internalstring ConfigurationFilePath { get; set; } 
         publicstring SubscriptionId { get; set; } 
         publicstring Base64EncodedCertificate { get; set; } 
     } 
}

Then I created a class that contains convenient functionality for the interaction between the user interface and the Management Library layer. This class was created for cleaner code in the UX layer later on. Pay attention to the constructor code. Two clients are created in it. First, StorageManagementClient is for managing storage accounts. The second ComputeManagementClient offers the ability to work with the computing power of Windows Azure - cloud services and virtual machines, their locations and so on.

In order to separate the code between files into different functional parts, I created a partial ManagementController class , the code of which is available to you in the public Gistso that you can use it in your own projects.

using Microsoft.WindowsAzure; 
using Microsoft.WindowsAzure.Management.Compute; 
using Microsoft.WindowsAzure.Management.Storage; 
using System; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController : IDisposable 
     { 
         private StorageManagementClient _storageManagementClient; 
         private ManagementControllerParameters _parameters; 
         private ComputeManagementClient _computeManagementClient; 
         internalManagementController(ManagementControllerParameters parameters) 
         { 
             _parameters = parameters; 
             var credential = CertificateAuthenticationHelper.GetCredentials( 
                 parameters.SubscriptionId, 
                 parameters.Base64EncodedCertificate); 
             _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credential); 
             _computeManagementClient = CloudContext.Clients.CreateComputeManagementClient(credential); 
         } 
         publicvoidDispose() 
         { 
             if (_storageManagementClient != null) 
                 _storageManagementClient.Dispose(); 
             if (_computeManagementClient != null) 
                 _computeManagementClient.Dispose(); 
         } 
     } 
}

Now, let's create some cloud management clients and do some work.

Create a new vault account


The first thing we need to implement the strategy of our service is a storage account. The service will use the .cspkg package file created in Visual Studio based on the cloud service project. It must be placed as a blob in the Windows Azure storage. Before I can do this, I need to create an account in the repository of which the package file can be downloaded. The code below is intended to create a vault account in the specified region:

using Microsoft.WindowsAzure.Management.Storage; 
using Microsoft.WindowsAzure.Management.Storage.Models; 
using System.Threading.Tasks; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController 
     { 
         internalasync Task CreateStorageAccount() 
         { 
             await _storageManagementClient.StorageAccounts.CreateAsync( 
                 new StorageAccountCreateParameters 
                 { 
                     Location = _parameters.Region, 
                     ServiceName = _parameters.StorageAccountName 
                 }); 
         } 
     } 
}

After the vault account is created, I can use it. I need a connection string to connect my application (and my "soon-to-be-created" cloud service) to the repository. I wrote a method that is responsible for retrieving Windows Azure storage connection keys through the REST API. Then, I form the connection string and return it to the calling code.

using Microsoft.WindowsAzure.Management.Storage; 
using System.Globalization; 
using System.Threading.Tasks; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController 
     { 
         privateasync Task<string> GetStorageAccountConnectionString() 
         { 
             var keys = await _storageManagementClient.StorageAccounts.GetKeysAsync(_parameters.StorageAccountName); 
             string connectionString = string.Format( 
                 CultureInfo.InvariantCulture, 
                 "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", 
                 _parameters.StorageAccountName, keys.SecondaryKey); 
             return connectionString; 
         } 
     } 
}

Now, after creating the storage account, I can create a cloud service and publish my package on Windows Azure.

Create and host a new cloud service


The code required for the cloud service is surprisingly simple. All we need is to indicate the name of the service and the region in which it should be created.

using Microsoft.WindowsAzure.Management.Compute; 
using Microsoft.WindowsAzure.Management.Compute.Models; 
using System.Threading.Tasks; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController 
     { 
         internalasync Task CreateCloudService() 
         { 
             await _computeManagementClient.HostedServices.CreateAsync(new HostedServiceCreateParameters 
             { 
                 Location = _parameters.Region, 
                 ServiceName = _parameters.CloudServiceName 
             }); 
         } 
     } 
}

Finally, all that remains for me to host the cloud service is to upload the service package file created in Visual Studio to the blob, and then call the REST API. This call will consist of the address of the blob in which the package is located and the XML data received from the configuration file of the cloud project. This code uses the Windows Azure Storage SDK , which is available as a NuGet package.

using Microsoft.WindowsAzure.Management.Compute; 
using Microsoft.WindowsAzure.Management.Compute.Models; 
using Microsoft.WindowsAzure.Storage; 
using Microsoft.WindowsAzure.Storage.Blob; 
using System.IO; 
using System.Threading.Tasks; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController 
     { 
         internalasync Task DeployCloudService() 
         { 
             var storageConnectionString = await GetStorageAccountConnectionString(); 
             var account = CloudStorageAccount.Parse(storageConnectionString); 
             var blobs = account.CreateCloudBlobClient(); 
             var container = blobs.GetContainerReference("deployments"); 
             await container.CreateIfNotExistsAsync(); 
             await container.SetPermissionsAsync( 
                 new BlobContainerPermissions() 
                 { 
                     PublicAccess = BlobContainerPublicAccessType.Container 
                 }); 
             var blob = container.GetBlockBlobReference( 
                 Path.GetFileName(_parameters.PackageFilePath)); 
             await blob.UploadFromFileAsync(_parameters.PackageFilePath, FileMode.Open); 
             await _computeManagementClient.Deployments.CreateAsync(_parameters.CloudServiceName, 
                     DeploymentSlot.Production, 
                     new DeploymentCreateParameters 
                     { 
                         Label = _parameters.CloudServiceName, 
                         Name = _parameters.CloudServiceName + "Prod", 
                         PackageUri = blob.Uri, 
                         Configuration = File.ReadAllText(_parameters.ConfigurationFilePath), 
                         StartDeployment = true 
                     }); 
         } 
     } 
}

All the code necessary to create the application in Windows Azure has been created. Finally, it remains to write some code to destroy the application in the cloud.

Removing items in the Windows Azure cloud


Removing items in Windows Azure using the Windows Azure Management Libraries is as easy as creating them. The code below cleans up the created storage, then it simultaneously deletes the hosted code and the cloud service itself.

using Microsoft.WindowsAzure.Management.Storage; 
using Microsoft.WindowsAzure.Management.Compute; 
using Microsoft.WindowsAzure.Management.Compute.Models; 
namespaceMyCloudServiceManager 
{ 
     internalpartialclassManagementController 
     { 
         internalvoidCleanup() 
         { 
             _computeManagementClient.Deployments.DeleteBySlot(_parameters.CloudServiceName, DeploymentSlot.Production); 
             _computeManagementClient.HostedServices.Delete(_parameters.CloudServiceName); 
             _storageManagementClient.StorageAccounts.Delete(_parameters.StorageAccountName); 
         } 
     } 
}

Given all the convenience of writing the previous code, the code for the user interface should be relatively simple.

User interface


The user interface for our application is relatively simplified. I just placed a couple of buttons on the WPF form. The first allows you to create the necessary elements in Windows Azure and place code. The second removes items from the cloud. The following is the XAML code:

<Windowx:Class="MyCloudServiceManager.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Deploy Service"Height="166"Width="308"><Grid><Grid.ColumnDefinitions><ColumnDefinitionWidth="112*"/><ColumnDefinitionWidth="125*"/></Grid.ColumnDefinitions><Buttonx:Name="_createButton"Content="Create"HorizontalAlignment="Left"VerticalAlignment="Top"Width="75"Margin="73,80,0,0"Grid.Column="1"Click="_createButton_Click"/><Buttonx:Name="_deleteButton"Content="Delete"HorizontalAlignment="Left"VerticalAlignment="Top"Width="75"Margin="73,105,0,0"Grid.Column="1"Click="_deleteButton_Click"/></Grid></Window>

The control code is also very simple. In the Create button click event handler, I create an instance of ManagementController , passing all the necessary parameters to it to create application components in Windows Azure. Then I call the controller methods to create the elements in the cloud.

I also handle the event of pressing the Delete button , deleting and clearing all the elements created earlier in the cloud.

using Microsoft.WindowsAzure.Management.Models; 
using System.IO; 
using System.Windows; 
namespaceMyCloudServiceManager 
{ 
     publicpartialclassMainWindow : Window 
     { 
         private ManagementController _controller; 
         publicMainWindow() 
         { 
             InitializeComponent(); 
         } 
         privateasyncvoid _createButton_Click(object sender, RoutedEventArgs e) 
         { 
             if (_controller == null) 
             { 
                 _controller = new ManagementController( 
                     new ManagementControllerParameters 
                     { 
                         Base64EncodedCertificate = "MIIKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 
                         SubscriptionId = "66c15fe5-XXXX-XXXX-XXXX-XXXXXXXXXX", 
                         CloudServiceName = "ManagementLibraryDemoSvc01", 
                         ConfigurationFilePath = "ServiceConfiguration.Cloud.cscfg", 
                         PackageFilePath = "MyCloudService.cspkg", 
                         Region = LocationNames.WestUS, 
                         StorageAccountName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) 
                     }); 
             } 
             await _controller.CreateStorageAccount(); 
             await _controller.CreateCloudService(); 
             await _controller.DeployCloudService(); 
         } 
         privatevoid _deleteButton_Click(object sender, RoutedEventArgs e) 
         { 
             _controller.Cleanup(); 
         } 
     } 
}

You can modify this code to use the capabilities of the Windows Storage SDK to monitor on the client side the message queue in the cloud storage. After the cloud service completes its work, it will send a message to the queue in the cloud. The message will be received by the client, who will call the Cleanup method and remove all application components from the cloud.

Endless automation options


Windows Azure Management Libraries offer the perfect automation layer between your code and Windows Azure. You can use these libraries to automate the full range of processes for creating and removing Windows Azure components. In the current version, we offer libraries for managing computing power and cloud storage, as well as components of Windows Azure Web Sites. Over time, we will add more functions to the libraries. Our goal is to give you the ability to automate the execution of any task in Windows Azure.

We look forward to your feedback on working with libraries. Please try, experiment with Management Libraries and let us know to facilitate what tasks you use them. We are open to any of your ideas or questions. The library code is open, as well as the code of many other libraries for Windows Azure, you can find it in our repository on GitHub .

Also popular now: