第一个Azure应用

https://www.azure.cn/zh-cn/

学习Azure,首先看的是官网Azure介绍,因为用到了虚拟机及存储等因此,着重看这两块。

本文Demo是通过API发送消息,当收到消息后新建虚拟机并启动虚拟机。

详细步骤:

1.新建Azure Cloud应用程序,添加WebRole以及WorkerRole,WebRole对应的是WebAPI

2.具体代码

WebRole中实现发送消息

public class AzureMessageController : ApiController
    {
        // POST api/AzureMessage
        [HttpGet]
        [Route ("api/AzureMessage")]
        public Dictionary<string, string> Get([FromBody]string value)
        {
            Dictionary<string, string> item = new Dictionary<string, string>();
            item.Add("name", "Jerry");
            QueueClient client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
            BrokeredMessage msg = new BrokeredMessage(item);
            try
            {
                client.Send(msg);
            }
            catch
            {
                throw;
            }
            finally
            {
                client.Close();
            }
            return item;
        }
    }

WorkerRole中在WorkerRole.cs中实现接收消息并新建虚拟机,开启虚拟机,及Stop动作

 private static QueueClient client;
 private IComputeManagementClient csClient;
 private INetworkManagementClient netClient;

a. OnStart()中开启消息队列客户端

public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.
    
            client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
            Trace.TraceInformation("MyWorkerRole has been started");
            
            return base.OnStart();
        }

b. OnStop()中关闭消息队列客户端

public override void OnStop()
        {
            Trace.TraceInformation("MyWorkerRole is stopping");

            //this.cancellationTokenSource.Cancel();
            //this.runCompleteEvent.WaitOne();
            client.Close();
            base.OnStop();

            Trace.TraceInformation("MyWorkerRole has stopped");
        }

c. Run()接收消息后,对虚拟机操作

 public override  void Run()
        {
            Trace.TraceInformation("MyWorkerRole is running");
            //while (true)
            //{
                BrokeredMessage msg = client.Receive(TimeSpan.FromSeconds(5));
                if (msg != null)
                {
                    Dictionary<string, string> item = msg.GetBody<Dictionary<string,string>>();
                    Trace.TraceInformation("Messages received name: "+item["name"]);
                    //Create VM
                    #region 1. create certificattion to client
                    X509Certificate2 certificate = null;
                    string thumbprint = "这里是证书所需要的thumbprint";
                    certificate = new X509Certificate2(Convert.FromBase64String(thumbprint));
                    Microsoft.Azure.SubscriptionCloudCredentials CloudCredential = new Microsoft.Azure.CertificateCloudCredentials("这里是云服务证书序列", certificate);
                    csClient = new ComputeManagementClient(CloudCredential);
                #endregion
                    #region 2. create cloudservice---serviceName
                var list = csClient.HostedServices.List();
                    csClient.HostedServices.BeginDeletingAll("serviceName");
                    var hostServicesPar = new Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceCreateParameters("serviceName", "label")
                    {
                        Location = "West US"
                    };

                    csClient.HostedServices.Create(hostServicesPar);

                    #endregion
                    #region 3. osVHD
                    OSVirtualHardDisk osVHD = null;
                    //osVHD = csClient.VirtualMachineOSImages.CreateOSVHD(_parameters.CloudServiceName, _parameters.NodeName, _parameters.Image);
                    var res = csClient.VirtualMachineOSImages.Get("imageName");  //提前定制好的Image
                    Uri ur = res.MediaLinkUri;
                    string UrlPath = ur.AbsoluteUri;
                    string Result = UrlPath.Substring(0, UrlPath.LastIndexOf('/'));
                   
                    osVHD = new OSVirtualHardDisk
                    {
                        MediaLink = VMClass.GetVhdUri(Result,"serviceName", "vmName"),
                        SourceImageName = "imageName",
                    };
                #endregion
                    #region 4. vnet
                netClient = new NetworkManagementClient(CloudCredential);
                var netlist = netClient.Networks.List();
                ConfigurationSet conset = new ConfigurationSet
                    {
                        ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                        SubnetNames = new List<string> { "Subnet-1" }
                    };

                        #endregion
                    #region 5. Role

                        List <ConfigurationSet> Configurations = new List<ConfigurationSet>();
                    Configurations.Add(conset);

                    Configurations.Add(new ConfigurationSet
                    {
                        AdminUserName = "userName",
                        AdminPassword = "userPWD",
                        ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                        EnableAutomaticUpdates = true,
                        ResetPasswordOnFirstLogon = false,
                        ComputerName = "MyComputerName",

                    });
                    //}
                    Microsoft.WindowsAzure.Management.Compute.Models.Role vmRole = new Microsoft.WindowsAzure.Management.Compute.Models.Role
                    {
                        RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                        RoleName = "MyRoleName",
                        Label = "label",
                        RoleSize = "Standard_DS1_v2",
                        //  VMImageName = imageName,
                        OSVirtualHardDisk = osVHD,
                        ProvisionGuestAgent = true,
                        ConfigurationSets = Configurations
                    };
                    #endregion
                    #region 6. check demployment
                    //check demployment
                    DeploymentGetResponse demployment = null;
                    try
                    {
                        demployment = csClient.Deployments.GetBySlot("serviceName", DeploymentSlot.Production);
                    }
                    catch { }

                    if (demployment != null)
                    {
                        //csClient.VirtualMachines.CreateVM(_parameters.HostSvcName, _parameters.HostSvcName, vmRole);
                        VirtualMachineCreateParameters parameters = new VirtualMachineCreateParameters()
                        {
                            ConfigurationSets = vmRole.ConfigurationSets,
                            ProvisionGuestAgent = true,
                            RoleName = vmRole.RoleName,
                            RoleSize = vmRole.RoleSize,
                            OSVirtualHardDisk = vmRole.OSVirtualHardDisk,
                            //VMImageName = vmRole.VMImageName,
                            ResourceExtensionReferences = vmRole.ResourceExtensionReferences,

                        };
                        if (parameters.OSVirtualHardDisk == null)
                        {
                            parameters.VMImageName = vmRole.VMImageName;
                        };
                        csClient.VirtualMachines.Create("serviceName", "deploymentName", parameters);
                    }
                    else
                    {
                        //csClient.VirtualMachines.CreateVMDeployment(_parameters.HostSvcName, _parameters.HostSvcName, _parameters.VirtualNetworkName, new List<Role>() { vmRole });
                        VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters
                        {
                            Name = "deploymentName",
                            Label = "serviceName",
                            Roles = new List<Microsoft.WindowsAzure.Management.Compute.Models.Role>() { vmRole },
                            DeploymentSlot = DeploymentSlot.Production,
                            VirtualNetworkName = "WDSOQASubCVnet01"
                        };
                    Trace.TraceInformation("Begin creating VM: " + item["name"]);
                    csClient.VirtualMachines.CreateDeployment("serviceName", createDeploymentParams);
                    Trace.TraceInformation("End : " + item["name"]);
                    Trace.TraceInformation("VM information : " );
                    Trace.TraceInformation("VM information Cloudservice: xx");
                    Trace.TraceInformation("VM information Name: xx");
                    Trace.TraceInformation("VM information VNet: WDSOQASubCVnet01");
                    Trace.TraceInformation("VM information Size: Standard_DS1_v2");
                }
                    #endregion
                }           
        }

用到的自定义的类

public static class VMClass
{
    public 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;
            string timeString = now.Hour + "-" + now.Second;
            var address = string.Format("{0}/{1}-{2}-{3}-{4}-650.vhd", blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : timeString, dateString);
            return new Uri(address);
        }
}
原文地址:https://www.cnblogs.com/Betty-IT/p/9274340.html