Get Started with the Management Libraries for .NET

 

If you need to manage Cloud Services, Virtual Machines, Virtual Networks, Websites, or Storage Accounts using native .NET code, the Management Libraries for .NET make it possible for you by providing easy to use clients. This tutorial shows you how to use some of the available clients to create and delete a Virtual Machine. It also shows you how to authenticate the requests to the management service by using Azure Active Directory (Azure AD).

To complete this tutorial, you need an Azure account. You can activate your MSDN subscriber benefits or sign up for a free trial. You must also have Visual Studio installed.

Note

Azure has two different deployment models for creating and working with resources: Resource Manager and classic. This article covers using the classic deployment model. Microsoft recommends using Resource Manager for most new deployments instead of the classic deployment model.

It will take you about 30 minutes to do the following to create and delete a Virtual Machine:

  1. Add an application to Azure AD – All requests to the management service must be authenticated. This tutorial shows you how to do this using Azure AD.

  2. Create a Visual Studio project – For this tutorial, you use a console application.

  3. Install the libraries – The Management Libraries and the Active Directory Authentication Library are needed to complete the steps in this tutorial.

  4. Add the code to create the credentials – A JSON Web Token (JWT) is needed to create the credentials for authentication.

  5. Add the code to create the resources – After a cloud service is created, a Virtual Machine can be deployed to it. A storage account is used to store the disk that is created for the Virtual Machine.

  6. Add the code to delete the resources – Because you are charged for services running in Azure, it is always a good practice to delete resources that are not needed.

  7. Run the console application – You sign in to Azure AD and then the code that you added in the previous steps runs in a console application.

Add an application to Azure AD

To use Azure AD to authenticate requests to the management service, an application must be added to the Default Directory. Do the following to add an application:

  1. Sign in to the Azure Management Portal.

  2. Towards the bottom of the left menu, click Active Directory, and then click Default Directory.

  3. On the Default Directory page, under Integrate applications, click Add an application you’re developing.

    Add an Azure AD application

  4. Enter the name of the application, select WEB APPLICATION AND/OR WEB API, and then click the right arrow.

    Provide a name for the application

  5. Enter a URI for the application and then click the checkmark. The URI includes the name of the application that is preceded by https://localhost/.

    Enter the redirect URL

  6. After the application is created, you must add permission for the application to access the Service Management APIs. Go to the page for your application, and then click Configure.

  7. In the Permissions to other applications section at the bottom of the configuration page, click Select application, and then select Windows Azure Service Management API.

    Assign permissions to the application

  8. Click Delegated Permissions: 0, and then select Access Azure Service Management.

    Continue setting permissions

  9. Click Save on the bottom menu.

Create a Visual Studio project

In Visual Studio, do the following:

  1. Click File > New > Project.

    Create a new Visual Studio project

  2. In Templates > Visual C# > Windows, select Console Application, enter the name and location of the project, and then click OK.

    Enter settings for the new project

  3. You should now see the following in the Solution Explorer:

    Project in Solution Explorer

Install the libraries

NuGet packages are the easiest way to install the libraries that you need to finish this tutorial. For this tutorial, you need the Microsoft Azure Management Libraries and the Azure Active Directory Authentication Library. To get these libraries in Visual Studio, do the following:

  1. Right-click the project name in the Solution Explorer, and then click Manage NuGet Packages.

    Manage NuGet packages

  2. Type Management Libraries in the search box, click Install for the Microsoft Azure Management Libraries, and then follow the instructions to install the package.

    Install Management Libraries

  3. Type Active Directory in the search box, click Install for the Active Directory Authentication Library package, and then follow the instructions to install the package.

    Install Active Directory library

  4. When you expand the References node in Solution Explorer, you should see the following:

    Verify assembly references

You are now ready to start using the libraries to create your application.

Add the code to create the credentials

Now that the application is created and the authentication library has been installed, you can format the application information into credentials that can be used to authenticate requests to the management service. You create the credentials by using the AuthenticationResult, AuthenticationContext, and the TokenCloudCredentials classes and by providing values for a tenant identifier, client identifier, and redirection URI.

Add the configuration settings

  1. In Solution Explorer, open the App.config file, and then add the following appSettings section:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <startup> 
        <supportedRuntime version="v4.0" 
           sku=".NETFramework,Version=v4.5" />
      </startup>
      <appSettings>
        <add key="login" value="https://login.windows.net/{0}" />
        <add key="tenantId" value="<id-of-tenant>" /> 
        <add key="apiEndpoint" value="https://management.core.windows.net/" />
        <add key="clientId" value="<id-of-client>" />
        <add key="redirectUri" value="<uri-of-application>" />
        <add key="subscriptionId" value="<id-of-subscription>"/>
        <add key="serviceName" value="<name-of-service>"/>
        <add key="storageName" value="<name-of-storage>"/> 
        <add key="deployName" value="<name-of-deployment>"/>
        <add key="vmName" value="<name-of-virtual-machine>"/>
        <add key="adminName" value="<name-of-admin-account>"/>
        <add key="adminPassword" value="<password-of-account>"/>
        <add key="imageFilter" value="Windows Server 2012 R2 Datacenter, March 2014"/>
      </appSettings>
    </configuration>
    
  2. To find the identifier of the Azure AD tenant, go to the Default Directory page in the Active Directory section of the Management Portal, select the application that you previously created, and then click View Endpoints.

    View endpoints

  3. Copy the GUID of the application and use it to replace <id-of-tenant>.

    Copy the application endpoint

  4. On the Configuration page of the application in the Management Portal, copy the client identifier and use it to replace <id-of-client>.

    Copy AD client ID

  5. On the Configuration page, copy the redirect URI and use it to replace <uri-of-application>.

    Copy the application redirect URI

  6. On the bottom of the left menu of the Management Portal, click Settings.

  7. On the Settings page, copy the subscription ID and use it to replace <id-of-subscription>.

  8. Replace <name-of-service> with the name that you want to use for the new cloud service. To see if the cloud service name is available to use, you could use CheckNameAvailabilityAsync.

  9. To create the Virtual Machine, you need to replace the following:

    • <name-of-storage> with the name that you want to use for the new storage account. When you create a Virtual Machine, a virtual hard disk (VHD) is created and is used by the machine. This VHD must be stored in an Azure storage account. For more information about storage accounts, see What is a storage account? To see if the storage account name is available to use, you could use CheckNameAvailabilityAsync.

    • <name-of-deployment> with the name that you want to use for the deployment.

    • <name-of-virtual-machine> with the name that you want to use for the Virtual Machine.

    • <name-of-admin-account> with the name that you want to use for the administrator account on the Virtual Machine.

    • <password-of-account> with the password that you want to use for the administrator account.

    Note

    For this tutorial, the Windows Server 2012 R2 Datacenter, March 2014 is being used, but you could change it to any image that is available in the gallery.

  10. Save the App.config file.

Get the token

  1. To access the configuration settings that you added to the App.config file, you must include the following using statement in the Program.cs file:

    using System.Configuration;
    

    And you must reference the System.Configuration assembly:

    Add System.Configuration assembly reference

  2. You have already added a reference to the Microsoft.IdentityModel.Clients.ActiveDirectory assembly, but to use it you need to add a using statement for it:

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    

    And to create the credentials, you need to add a using statement for the Microsoft.WindowsAzure namespace:

    using Microsoft.WindowsAzure;
    
  3. The code that you are creating uses asynchronous operations to complete the tasks. To set this up, you need to add using statements for the System.Threading namespace:

    using System.Threading;
    using System.Threading.Tasks;
    
  4. Add the following method to the Program class to get the token that is needed to create the credentials:

    private static string GetAuthorizationHeader()
    {
      AuthenticationResult result = null;
    
      var context = new AuthenticationContext(string.Format(
        ConfigurationManager.AppSettings["login"],
        ConfigurationManager.AppSettings["tenantId"]));
    
      var thread = new Thread(() =>
      {
        result = context.AcquireToken(
          ConfigurationManager.AppSettings["apiEndpoint"],
          ConfigurationManager.AppSettings["clientId"],
          new Uri(ConfigurationManager.AppSettings["redirectUri"]));
      });
    
      thread.SetApartmentState(ApartmentState.STA);
      thread.Name = "AquireTokenThread";
      thread.Start();
      thread.Join();
    
      if (result == null)
      {
        throw new InvalidOperationException("Failed to obtain the JWT token");
      }
    
      string token = result.AccessToken;
            return token;
    }
    
  5. Add the following code to the Main method in the Program.cs file to create the credentials:

    var token = GetAuthorizationHeader();
    var credential = new TokenCloudCredentials(
      ConfigurationManager.AppSettings["subscriptionId"], token);
    
  6. Save the Program.cs file.

Add the code to create the resources

The resources that you create using this tutorial include a storage account, a cloud service, and a Virtual Machine.

Create a storage account

You create a storage account by using the StorageManagementClient and StorageAccountCreateParameters classes.

  1. Add a new class file to the project named StorageAccountCreator.

  2. Add the following using statements to the top of the file:

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Management.Models;
    using Microsoft.WindowsAzure.Management.Storage;
    using Microsoft.WindowsAzure.Management.Storage.Models;
    using Microsoft.WindowsAzure.Management.Compute;
    using Microsoft.WindowsAzure.Management.Compute.Models;
    using System.Configuration;
    
  3. Change the class signature to the following:

    public static class StorageAccountCreator
    {
    }
    
  4. Add the following method to the class to create the storage account:

    public async static Task<string> CreateStorageAccount(
      SubscriptionCloudCredentials credentials)
    {
      using (var storageClient = new StorageManagementClient(credentials))
      {
        await storageClient.StorageAccounts.CreateAsync(
          new StorageAccountCreateParameters
          {
            GeoReplicationEnabled = false,
            Label = "Sample Storage Account",
            Location = LocationNames.WestUS,
            Name = ConfigurationManager.AppSettings["storageName"]
          });
      }
      return "Successfully created account.";
    }
    

    Note

    This example shows the use of the WestUS location. You can get a list of all available locations by using ListAsync.

  5. Save the StorageAccountCreator.cs file.

  6. Add the following method to the Program.cs file:

    public async static void CreateResources(
      TokenCloudCredentials credential)
    {
      Console.WriteLine(
        "Creating the storage account. This may take a few minutes...");
      var stResult = 
        await StorageAccountCreator.CreateStorageAccount(credential);
      Console.WriteLine(stResult);
    }
    
  7. Add the following lines to the Main method:

    CreateResources(credential);
    Console.ReadLine();
    

Create a cloud service

You create a storage account by using the ComputeManagementClient and the HostedServiceCreateParameters classes.

  1. Add a new class file to the project named CloudServiceCreator.

  2. Add the following using statements to the top of the file:

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Management.Compute;
    using Microsoft.WindowsAzure.Management.Compute.Models;
    using Microsoft.WindowsAzure.Management.Models;
    using System.Configuration;
    
  3. Change the class signature to the following:

    public static class CloudServiceCreator
    {
    }
    
  4. Add the following method to the class to create the cloud service:

    public async static Task<string> CreateCloudService(
      SubscriptionCloudCredentials credentials)
    {
      using (var computeClient = new ComputeManagementClient(credentials))
      {
        await computeClient.HostedServices.CreateAsync(
          new HostedServiceCreateParameters
          {
            Label = "NewCloudService",
            Location = LocationNames.WestUS,
            ServiceName = ConfigurationManager.AppSettings["serviceName"]
          });
      }
      return "Successfully created service.";
    }
    

    Note

    The cloud service is being created in the same location as the storage account. You could select a different location, but the storage account and the cloud service should be in the same location.

  5. Save the CloudServiceCreator.cs file.

  6. Add the following code to the CreateResources method that you added to the Program.cs file:

    Console.WriteLine("Creating the cloud service...");
    var csResult = 
      await CloudServiceCreator.CreateCloudService(credential);
    Console.WriteLine(csResult);
    
  7. Save the Program.cs file.

Deploy a Virtual Machine

A virtual machine is deployed by using the following classes:

Adding input endpoints is optional, but you can’t access the Virtual Machine without one.

  1. Add a new class file to the project named VirtualMachineCreator.

  2. Add the following using statements to the top of the file:

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Management.Compute;
    using Microsoft.WindowsAzure.Management.Compute.Models;
    using Microsoft.WindowsAzure.Management.Models;
    using System.Configuration;
    
  3. Change the class signature to the following:

    public static class VirtualMachineCreator
    {
    }
    
  4. Add the following method to the class:

    public async static Task<string> CreateVirtualMachine(
      SubscriptionCloudCredentials credentials)
    {
      using (var computeClient = new ComputeManagementClient(credentials))
      {
      }
      return "Successfully created Virtual Machine";
    }
    
  5. To get the name of the VHD file for the image that you defined in the application configuration file, add the following code inside of the using block that you just added:

    var operatingSystemImageListResult = 
      await computeClient.VirtualMachineOSImages.ListAsync();
    var imageName = 
      operatingSystemImageListResult.Images.FirstOrDefault(
        x => x.Label.Contains(
          ConfigurationManager.AppSettings["imageFilter"])).Name;
    
  6. To set the configuration of the Virtual Machine, add the following code to the same using block:

    var windowsConfigSet = new ConfigurationSet
    {
      ConfigurationSetType =
        ConfigurationSetTypes.WindowsProvisioningConfiguration,
      AdminPassword =
        ConfigurationManager.AppSettings["adminPassword"],
      AdminUserName = ConfigurationManager.AppSettings["adminName"],
      ComputerName = ConfigurationManager.AppSettings["vmName"],
      HostName = string.Format("{0}.cloudapp.net", 
        ConfigurationManager.AppSettings["serviceName"])
    };
    
  7. To log in to the Virtual Machine or to use Remote PowerShell on the Virtual Machine, endpoints must be added. Add the following code to the using block to create the endpoints:

    var networkConfigSet = new ConfigurationSet
    {
      ConfigurationSetType = "NetworkConfiguration",
      InputEndpoints = new List<InputEndpoint>
      {
        new InputEndpoint
        {
          Name = "PowerShell",
          LocalPort = 5986,
          Protocol = "tcp", 
          Port = 5986,
        },
        new InputEndpoint
        {
          Name = "Remote Desktop", 
          LocalPort = 3389, 
          Protocol = "tcp", 
          Port = 3389,
        }
      }
    };
    
  8. Add the following code to the using block to create the operating system disk for the Virtual Machine:

    var vhd = new OSVirtualHardDisk
    {
      SourceImageName = imageName,
      HostCaching = VirtualHardDiskHostCaching.ReadWrite,
      MediaLink = new Uri(string.Format(
        "https://{0}.blob.core.windows.net/vhds/{1}.vhd",
          ConfigurationManager.AppSettings["storageName"], imageName))
    };
    

    Note

    For more information, see Manage Disks and Images.

  9. Add the following code to the using block to set attributes for the deployment, such as the name and size of the machine:

    var deploymentAttributes = new Role
    {
      RoleName = ConfigurationManager.AppSettings["vmName"],
      RoleSize = VirtualMachineRoleSize.Small,
      RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
      OSVirtualHardDisk = vhd,
      ConfigurationSets = new List<ConfigurationSet>
      {
        windowsConfigSet,
        networkConfigSet
      },
      ProvisionGuestAgent = true
    };
    

    Note

    This tutorial creates a Small sized Virtual Machine. Larger sizes are available. For more information, see Virtual Machine and Cloud Service Sizes for Azure.

  10. And finally, add the following code to the using block to deploy the Virtual Machine:

    var createDeploymentParameters = 
      new VirtualMachineCreateDeploymentParameters
      {
        Name = ConfigurationManager.AppSettings["deployName"],
        Label = ConfigurationManager.AppSettings["deployName"],
        DeploymentSlot = DeploymentSlot.Production,
        Roles = new List<Role> { deploymentAttributes }
      };
    var deploymentResult = 
      await computeClient.VirtualMachines.CreateDeploymentAsync(
        ConfigurationManager.AppSettings["serviceName"],
        createDeploymentParameters);
    
  11. Save the VirtualMachineCreator.cs file.

  12. Add the following code to the CreateResources method that you added to the Program.cs file:

    Console.WriteLine(
      "Deploying the Virtual Machine. This may take a few minutes...");
    var vmResult = 
      await VirtualMachineCreator.CreateVirtualMachine(credential);
    Console.WriteLine(vmResult);
    Console.WriteLine("Press Enter to remove the resources.");
    
  13. Save the Program.cs file

Add the code to delete the resources

Because you are charged for resources used in Azure, it is always a good practice to delete resources that are no longer needed.

Delete the deployment

Delete the deployment by using the GetBySlotAsync and DeleteByNameAsync classes.

  1. To cleanly delete the Virtual Machine, you need to make sure that is it in a Running state. Add the following method to the VirtualMachineCreator class to make sure that the machine is deleted only after it is successfully running:

    public async static Task<string> DeleteVirtualMachine(
      SubscriptionCloudCredentials credentials)
    {
      using (var computeClient = new ComputeManagementClient(credentials))
      {
        string vmStatus = "Created";
        while (!vmStatus.Equals("Running"))
        {
          var vmStatusResponse =
            await computeClient.Deployments.GetBySlotAsync(
              ConfigurationManager.AppSettings["serviceName"],
              DeploymentSlot.Production);
          vmStatus = vmStatusResponse.Status.ToString();
        }
    
        var deleteDeploymentResult =
          await computeClient.Deployments.DeleteByNameAsync(
            ConfigurationManager.AppSettings["serviceName"],
            ConfigurationManager.AppSettings["deployName"],
            true);
      }
      return "Successfully deleted Virtual Machine.";
    }
    
  2. Save the VirtualMachineCreator.cs file.

  3. Add the following method to the Program.cs file:

    public async static void DeleteResources(
      TokenCloudCredentials credential)
    {
      Console.WriteLine(
        "Deleting the Virtual Machine. This may take a few minutes...");
      var vmResult = 
        await VirtualMachineCreator.DeleteVirtualMachine(credential);
      Console.WriteLine(vmResult);
    }
    
  4. Add the following code to the Main method:

    DeleteResources(credential);
    Console.ReadLine();
    
  5. Save the Program.cs file.

Delete the storage account

  1. The storage account can only be deleted when it doesn’t contain anything. Since it takes a bit of time for the Virtual Machine and its disk to be deleted, add the following method to the StorageAccountCreator class to wait for the storage account to be empty and then delete the account:

    public async static Task<string>
      DeleteStorageAccount(SubscriptionCloudCredentials credentials)
    {
      using (var computeClient = new ComputeManagementClient(credentials))
      {
        var diskCount = 1;
        while (diskCount > 0)
        {
          var diskListResult = 
            await computeClient.VirtualMachineDisks.ListDisksAsync();
          diskCount = diskListResult.Disks.Count;
        }
      }
    
      using (var storageClient = new StorageManagementClient(credentials))
      {
        await storageClient.StorageAccounts.DeleteAsync(
          ConfigurationManager.AppSettings["storageName"]);
      }
    
      return "Successfully deleted account.";
    }
    

Delete the cloud service

Delete the cloud service by using the DeleteAsync class.

  1. Add the following method to the CloudServiceCreator class to delete the cloud service:

    public async static Task<string> DeleteCloudService(
      this SubscriptionCloudCredentials credentials)
    {
      using (var computeClient = new ComputeManagementClient(credentials))
      {
        await computeClient.HostedServices.DeleteAsync(
          ConfigurationManager.AppSettings["serviceName"]);
      }
      return "Successfully deleted service.";
    }
    
  2. Save the CloudServiceCreator.cs file.

  3. Add the following code to the DeleteResources method that you added to the Program.cs file:

    Console.WriteLine("Deleting the service...");
    var csResult = 
      await CloudServiceCreator.DeleteCloudService(credential);
    Console.WriteLine(csResult);
    
  4. Save the Program.cs file.

Run the console application

To run the console application, click Start in Visual Studio, and then sign in to Azure AD using the same username and password that you use with your subscription:

Sign in to Azure AD

It should take about 5 minutes for this console application to run completely from start to finish. Before you press Enter to start deleting resources, you could take a few minutes to verify the creation of the resources in the Management Portal before you delete them.

After running completely through the application, you should see something similar to the following in the console window:

Results of creating and deleting a Virtual Machine