之前发的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. C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别

    转自:http://www.cnblogs.com/leolis/p/3968943.html 在编程过程中,数据转换是经常要用到的,C#中数据转换的方法很多,拿将目标对象转换为 整型(int)来讲, ...

  2. CNUOJ 0486 800401反质数

    难度级别:A: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 将正整数 x 的约数个数表示为 g(x).例如,g(1)=1,g(4)=3, g ...

  3. Google Gson 使用简介

    http://www.cnblogs.com/haippy/archive/2012/05/20/2509329.html

  4. Git系列教程三 配置与基本命令

    一.安装Git 网上有很多安装教程,可以参考.这里使用的是Windows版本的Git,点击这里下载. 二.基本设置 安装完成后,通过点击鼠标右键就可以看到新添加了俩个Git命令:Git GUI Her ...

  5. JDBC的使用(二):PreparedStatement接口;ResultSet接口(获取结果集);例题:SQL注入

    ResultSet接口:类似于一个临时表,用来暂时存放数据库查询操作所获得的结果集. getInt(), getFloat(), getDate(), getBoolean(), getString( ...

  6. Oracle中日期时间的操作比较和加减-入门基础(转)

    Oracle关于时间/日期的操作     1.日期时间间隔操作 当前时间减去7分钟的时间 select sysdate,sysdate - interval '7' MINUTE from dual ...

  7. SQL TOP 子句、SQL LIKE 操作符、SQL 通配符

    TOP 子句 TOP 子句用于规定要返回的记录的数目. 对于拥有数千条记录的大型表来说,TOP 子句是非常有用的. 注释:并非所有的数据库系统都支持 TOP 子句. SQL Server 的语法: S ...

  8. Centos下ACL(访问控制列表)介绍(转)

    我们知道,在Linux操作系统中,传统的权限管理分是以三种身份(属主.属組以及其它人)搭配三种权限(可读.可写以及可执行),并且搭配三种特殊权限(SUID,SGID,SBIT),来实现对系统的安全保护 ...

  9. java中一些定时器的使用

    一:简单说明 ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便. ...

  10. 解决UIScrollView把uitableviewcell的点击事件屏蔽

    cell中 [self.contentView addSubview:self.scrollView]; self.scrollView.userInteractionEnabled = NO; [s ...