之前发的blog简单的介绍了如何使用Management Class Libraries 来控制Azure platform。

但由于官方并没有提供文档,所以我们只能够通过自己研究来摸索使用该类库的方法。

在使用过程中我发现可以再抽象出一层中间层,从而让该类库的使用更趋近于Management REST API。

下面以创建一个Virtual Machine 为例让我们来了解如何使用该类库来操作Virtual Machine

首先我们要知道,在Azure Platform中,任何一个VM Instance都要运行在一个HostedService 里面的Deployment下面的。

所以在使用过程中我们需要首先创建一个Hosted Service。

我们可以通过以下两个方法来进行创建:

  public static void createCloudServiceByLocation(string cloudServiceName, string location)
{
ComputeManagementClient client = new ComputeManagementClient(getCredentials());
HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
{
ServiceName = cloudServiceName,
Location = location,
Label = EncodeToBase64(cloudServiceName),
};
try
{
client.HostedServices.Create(hostedServiceCreateParams);
}
catch (CloudException e)
{
throw e;
} }
public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName)
{
ComputeManagementClient client = new ComputeManagementClient(getCredentials());
HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
{
ServiceName = cloudServiceName,
AffinityGroup = affinityGroupName,
Label = EncodeToBase64(cloudServiceName),
};
try
{
client.HostedServices.Create(hostedServiceCreateParams);
}
catch (CloudException e)
{
throw e;
} }

在有了HostedService之后,我们可以通过两种方式来创建VM。

第一种:首先创建一个Deployment,然后再通过添加角色来向这个Deployment中添加Virtual Machine,这样需要与Azure平台交互两次。

第二种:直接调用创建虚拟机部署,这样将在一个Request中创建一个虚拟机的Deployment并且将添加1或多个Virtual Machine到该Deployment下面。

我们可以通过创建自己的Extension Class Library来使得操作更趋向于REST API,一下是我抽象层的代码:

public static class MyVirtualMachineExtension
{
/// <summary>
/// Instantiation a new VM Role
/// </summary>
public static Role CreateVMRole(this IVirtualMachineOperations client, string cloudServiceName, string roleName, VirtualMachineRoleSize roleSize, string userName, string password, OSVirtualHardDisk osVHD)
{
Role vmRole = new Role
{
RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
RoleName = roleName,
Label = roleName,
RoleSize = roleSize,
ConfigurationSets = new List<ConfigurationSet>(),
OSVirtualHardDisk = osVHD
};
ConfigurationSet configSet = new ConfigurationSet
{
ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
EnableAutomaticUpdates = true,
ResetPasswordOnFirstLogon = false,
ComputerName = roleName,
AdminUserName = userName,
AdminPassword = password,
InputEndpoints = new BindingList<InputEndpoint>
{
new InputEndpoint { LocalPort = , Name = "RDP", Protocol = "tcp" },
                    new InputEndpoint { LocalPort = , Port = , Name = "web", Protocol = "tcp" }
}
};
vmRole.ConfigurationSets.Add(configSet);
return vmRole;
} public static OSVirtualHardDisk CreateOSVHD(this IVirtualMachineImageOperations operation, string cloudserviceName, string vmName, string storageAccount, string imageFamiliyName)
{
try
{
var osVHD = new OSVirtualHardDisk
{
MediaLink = GetVhdUri(string.Format("{0}.blob.core.windows.net/vhds", storageAccount), cloudserviceName, vmName),
SourceImageName = GetSourceImageNameByFamliyName(operation, imageFamiliyName)
};
return osVHD;
}
catch (CloudException e)
{ throw e;
} } private static string GetSourceImageNameByFamliyName(this IVirtualMachineImageOperations operation, string imageFamliyName)
{
var disk = operation.List().Where(o => o.ImageFamily == imageFamliyName).FirstOrDefault();
if (disk != null)
{
return disk.Name;
}
else
{
throw new CloudException(string.Format("Can't find {0} OS image in current subscription"));
}
} private static Uri GetVhdUri(string blobcontainerAddress, string cloudServiceName, string vmName, bool cacheDisk = false, bool https = false)
{
var now = DateTime.UtcNow;
string dateString = now.Year + "-" + now.Month + "-" + now.Day; var address = string.Format("http{0}://{1}/{2}-{3}-{4}-{5}-650.vhd", https ? "s" : string.Empty, blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : string.Empty, dateString);
return new Uri(address);
} public static void CreateVMDeployment(this IVirtualMachineOperations operations, string cloudServiceName, string deploymentName, List<Role> roleList, DeploymentSlot slot = DeploymentSlot.Production)
{ try
{
VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters
{ Name = deploymentName,
Label = cloudServiceName,
Roles = roleList,
DeploymentSlot = slot
};
operations.CreateDeployment(cloudServiceName, createDeploymentParams);
}
catch (CloudException e)
{
throw e;
}
} public static void AddRole(this IVirtualMachineOperations operations, string cloudServiceName, string deploymentName, Role role, DeploymentSlot slot = DeploymentSlot.Production)
{
try
{
VirtualMachineCreateParameters createParams = new VirtualMachineCreateParameters
{
RoleName = role.Label,
RoleSize = role.RoleSize,
OSVirtualHardDisk = role.OSVirtualHardDisk,
ConfigurationSets = role.ConfigurationSets,
AvailabilitySetName = role.AvailabilitySetName,
DataVirtualHardDisks = role.DataVirtualHardDisks
}; operations.Create(cloudServiceName, deploymentName, createParams);
}
catch (CloudException e)
{
throw e;
} }
}

整体programe代码如下:

 class Program
{ public const string base64EncodedCertificate = "";
public const string subscriptionId = ""; public static string vmName = "Azure111";
public static string location = "East Asia";
public static string storageAccountName = "superdino";
public static string userName = "Dino";
public static string password = "PassWord1!"; public static string imageFamiliyName = "Windows Server 2012 Datacenter"; static void Main(string[] args)
{
ComputeManagementClient client = new ComputeManagementClient(getCredentials());
//You need a hosted service host VM.
try
{
client.HostedServices.Get(vmName);
}
catch (CloudException e)
{
createCloudServiceByLocation(vmName, location);
} var OSVHD = client.VirtualMachineImages.CreateOSVHD(vmName, vmName, storageAccountName, imageFamiliyName);
var VMROle = client.VirtualMachines.CreateVMRole(vmName, vmName, VirtualMachineRoleSize.Small, userName, password, OSVHD);
List<Role> roleList = new List<Role>{
VMROle
};
client.VirtualMachines.CreateVMDeployment(vmName, vmName, roleList);
Console.WriteLine("Create VM success");
client.VirtualMachines.AddRole("CloudServiceName", "ExsitDeploymentName", VMROle); Console.ReadLine();
} public static void createCloudServiceByLocation(string cloudServiceName, string location)
{
ComputeManagementClient client = new ComputeManagementClient(getCredentials());
HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
{
ServiceName = cloudServiceName,
Location = location,
Label = EncodeToBase64(cloudServiceName),
};
try
{
client.HostedServices.Create(hostedServiceCreateParams);
}
catch (CloudException e)
{
throw e;
} }
public static void createCloudServiceByAffinityGroup(string cloudServiceName, string affinityGroupName)
{
ComputeManagementClient client = new ComputeManagementClient(getCredentials());
HostedServiceCreateParameters hostedServiceCreateParams = new HostedServiceCreateParameters
{
ServiceName = cloudServiceName,
AffinityGroup = affinityGroupName,
Label = EncodeToBase64(cloudServiceName),
};
try
{
client.HostedServices.Create(hostedServiceCreateParams);
}
catch (CloudException e)
{
throw e;
} }
public static string EncodeToBase64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
} public static SubscriptionCloudCredentials getCredentials()
{
return new CertificateCloudCredentials(subscriptionId, new X509Certificate2(Convert.FromBase64String(base64EncodedCertificate)));
} }

Azure Virtual Machine 之 如何利用Management Class Libraries 创建VM的更多相关文章

  1. Windows Azure Virtual Machine (29) 修改Azure VM 数据磁盘容量

    <Windows Azure Platform 系列文章目录> 当我们使用Windows Azure管理界面,创建Azure虚拟机的时候,默认挂载的磁盘是固定大小的 1.比如我创建1个Wi ...

  2. [New Portal]Windows Azure Virtual Machine (23) 使用Storage Space,提高Virtual Machine磁盘的IOPS

    <Windows Azure Platform 系列文章目录> 注意:如果使用Azure Virtual Machine,虚拟机所在的存储账号建议使用Local Redundant.不建议 ...

  3. [New Portal]Windows Azure Virtual Machine (12) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (2)

    <Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...

  4. [New Portal]Windows Azure Virtual Machine (13) 在本地使用Hyper-V制作虚拟机模板,并上传至Azure (3)

    <Windows Azure Platform 系列文章目录> 本章介绍的内容是将本地Hyper-V的VHD,上传到Azure数据中心,作为自定义的虚拟机模板. 注意:因为在制作VHD的最 ...

  5. [New Portal]Windows Azure Virtual Machine (15) 在本地制作数据文件VHD并上传至Azure(2)

    <Windows Azure Platform 系列文章目录> 在上一章内容里,我们已经将包含有OFFICE2013 ISO安装文件的VHD上传至Azure Blob Storage中了. ...

  6. [New Portal]Windows Azure Virtual Machine (16) 使用Azure PowerShell创建Azure Virtual Machine

    <Windows Azure Platform 系列文章目录> 注:本章内容和之前的[New Portal]Windows Azure Virtual Machine (12) 在本地制作 ...

  7. [New Portal]Windows Azure Virtual Machine (18) Azure Virtual Machine内部IP和外部IP

    <Windows Azure Platform 系列文章目录> 在开始本章内容之前,请读者熟悉以下2篇博文:       [New Portal]Windows Azure Virtual ...

  8. [New Portal]Windows Azure Virtual Machine (19) 关闭Azure Virtual Machine与VIP Address,Internal IP Address的关系(1)

    <Windows Azure Platform 系列文章目录> 默认情况下,通过Azure Management Portal创建的Public IP和Private IP都是随机分配的. ...

  9. [New Portal]Windows Azure Virtual Machine (20) 关闭Azure Virtual Machine与VIP Address,Internal IP Address的关系(2)

    <Windows Azure Platform 系列文章目录> 默认情况下,通过Azure Management Portal创建的Public IP和Private IP都是随机分配的. ...

随机推荐

  1. 复制文件的问题:使用FileInputStream和FileOutputStream实现文件复制

    public class Test{ public static void main(String [] args) { Test t=new Test(); t.upload(); } public ...

  2. 字符串转数字_atoi_stringstream

    一.#include <cstdlib> 字符串转换到整型数,函数原型:int atoi(const char *nptr) 注意事项:有符号整型,能转换的最大字符串是:"214 ...

  3. 实战Java虚拟机之四:提升性能,禁用System.gc() ?

    今天开始实战Java虚拟机之四:"禁用System.gc()". 总计有5个系列 实战Java虚拟机之一“堆溢出处理” 实战Java虚拟机之二“虚拟机的工作模式” 实战Java虚拟 ...

  4. 「iOS造轮子」之UIButton 用Block响应事件

    俗语说 一个不懒的程序员不是好程序员 造轮子,也只是为了以后更好的coding. coding,简易明了的代码更是所有程序员都希望看到的 无论是看自己的代码,还是接手别人的代码 都希望一看都知道这代码 ...

  5. [bzoj1087][scoi2005]互不侵犯king

    题目大意 在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上 左下右上右下八个方向上附近的各一个格子,共8个格子. 思路 首先,搜索可以放弃,因为这是一 ...

  6. java线程同步 以及wait 和notify用法

    package test; public class ThreadTest2 extends Thread { private int threadNo; private String lock; p ...

  7. 配置opencv时计算机显示丢失opencv_world300d.dll如何解决

    在自己安装路径里找到opencv_world300d.dll文件: 然后把opencv_world300d.dll文件复制到C://Windows/System32里:

  8. python 的var_dump

    from __future__ import print_function from types import NoneType __author__ = "Shamim Hasnath&q ...

  9. iOS 面试题(三):为什么 weakSelf 需要配合 strong self 使用 --转自唐巧

    问题 继续回答昨天的问题第二问. 我们知道,在使用 block 的时候,为了避免产生循环引用,通常需要使用 weakSelf 与 strongSelf,写下面这样的代码: __weak typeof( ...

  10. 如何理解C#委托

    一:从下面的例子开始,理解委托变量本质 如上图,Condition是我定义的委托变量.这个委托变量的本质就是地址变量(即C语言当中的指针变量),它保存的是方法的入口地址. 当函数的调用者传递实参给这个 ...