Microsoft.WindowsAzure.Management.ServiceManagement.IaaS.PersistentVMs.NewAzureVMCommand.NewAzureVMProcess C# (CSharp) Method

NewAzureVMProcess() public method

public NewAzureVMProcess ( ) : void
return void
        public void NewAzureVMProcess()
        {
            List<PersistentVMRole> persistentVMs = new List<PersistentVMRole>();
            SubscriptionData currentSubscription = this.GetCurrentSubscription();

            foreach (PersistentVM pVM in this.VMs)
            {
                if (pVM.OSVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(pVM.OSVirtualHardDisk.DiskName))
                {
                    CloudStorageAccount currentStorage = null;
                    try
                    {
                        currentStorage = CloudStorageAccountFactory.GetCurrentCloudStorageAccount(Channel, currentSubscription);
                    }
                    catch (ServiceManagementClientException) // couldn't access
                    {
                        throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
                    }
                    if (currentStorage == null) // not set
                    {
                        throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storage account to set it.");
                    }

                    DateTime dateTimeCreated = DateTime.Now;
                    string diskPartName = pVM.RoleName;

                    if (pVM.OSVirtualHardDisk.DiskLabel != null)
                    {
                        diskPartName += "-" + pVM.OSVirtualHardDisk.DiskLabel;
                    }

                    string vhdname = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, diskPartName, dateTimeCreated.Year, dateTimeCreated.Month, dateTimeCreated.Day, dateTimeCreated.Millisecond);
                    string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                    if (blobEndpoint.EndsWith("/") == false)
                    {
                        blobEndpoint += "/";
                    }

                    pVM.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
                }

                foreach (DataVirtualHardDisk datadisk in pVM.DataVirtualHardDisks)
                {
                    if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName))
                    {
                        CloudStorageAccount currentStorage = CloudStorageAccountFactory.GetCurrentCloudStorageAccount(Channel, currentSubscription);
                        if (currentStorage == null)
                        {
                            throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
                        }

                        DateTime dateTimeCreated = DateTime.Now;
                        string diskPartName = pVM.RoleName;

                        if (datadisk.DiskLabel != null)
                        {
                            diskPartName += "-" + datadisk.DiskLabel;
                        }

                        string vhdname = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, diskPartName, dateTimeCreated.Year, dateTimeCreated.Month, dateTimeCreated.Day, dateTimeCreated.Millisecond);
                        string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;

                        if (blobEndpoint.EndsWith("/") == false)
                        {
                            blobEndpoint += "/";
                        }

                        datadisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
                    }

                    if (pVM.DataVirtualHardDisks.Count() > 1)
                    {
                        // To avoid duplicate disk names
                        System.Threading.Thread.Sleep(1);
                    }
                }

                var vmRole = new PersistentVMRole
                {
                    AvailabilitySetName = pVM.AvailabilitySetName,
                    ConfigurationSets = pVM.ConfigurationSets,
                    DataVirtualHardDisks = pVM.DataVirtualHardDisks,
                    OSVirtualHardDisk = pVM.OSVirtualHardDisk,
                    RoleName = pVM.RoleName,
                    RoleSize = pVM.RoleSize,
                    RoleType = pVM.RoleType,
                    Label = pVM.Label
                };

                persistentVMs.Add(vmRole);
            }

            Operation lastOperation = null;

            using (new OperationContextScope(Channel.ToContextChannel()))
            {
                try
                {
                    if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase) == true)
                    {
                        CreateHostedServiceInput chsi = new CreateHostedServiceInput();
                        chsi.AffinityGroup = this.AffinityGroup;
                        chsi.Location = this.Location;
                        chsi.ServiceName = this.ServiceName;

                        if (this.ServiceDescription == null)
                        {
                            DateTime dtUTC = DateTime.Now.ToUniversalTime();
                            //Implicitly created hosted service2012-05-07 23:12
                            string serviceDesc = String.Format("Implicitly created hosted service{0}", dtUTC.ToString("yyyy-MM-dd HH:mm"));
                            chsi.Description = serviceDesc;
                        }
                        else
                        {
                            chsi.Description = this.ServiceDescription;
                        }

                        if (this.ServiceLabel == null)
                        {
                            chsi.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                        }
                        else
                        {
                            chsi.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceLabel);
                        }

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi), WaitForOperation);
                    }
                }
                catch (ServiceManagementClientException ex)
                {
                    this.WriteErrorDetails(ex);
                    return;
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return;
            }

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        if (string.IsNullOrEmpty(this.DeploymentName))
                        {
                            this.DeploymentName = this.ServiceName;
                        }

                        if (string.IsNullOrEmpty(this.DeploymentLabel))
                        {
                            this.DeploymentLabel = this.ServiceName;
                        }

                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.DeploymentName,
                            Label = this.DeploymentLabel,
                            RoleList = new RoleList(new List<Role> { persistentVMs[0] }),
                            VirtualNetworkName = this.VNetName
                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings();
                            deployment.Dns.DnsServers = new DnsServerList();
                            foreach (DnsServer dns in this.DnsSettings)
                            {
                                deployment.Dns.DnsServers.Add(dns);
                            }
                        }

                        ExecuteClientAction(deployment, CommandRuntime.ToString() + " - Create Deployment with VM " + persistentVMs[0].RoleName, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment), WaitForOperation);
                    }
                    catch (ServiceManagementClientException ex)
                    {
                        if (ex.HttpStatus == HttpStatusCode.NotFound)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -AffinityGroup to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    this.createdDeployment = true;
                }
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning("VNetName, DnsSettings, DeploymentLabel or DeploymentName Name can only be specified on new deployments.");
                }
            }

            if (this.createdDeployment == false && CurrentDeployment != null)
            {
                this.DeploymentName = CurrentDeployment.Name;
            }

            int startingVM = (this.createdDeployment == true) ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return;
                }

                ExecuteClientActionInOCS(persistentVMs[i],
                    CommandRuntime.ToString() + " - Create VM " + persistentVMs[i].RoleName,
                    s => this.Channel.AddRole(s, this.ServiceName, this.DeploymentName, persistentVMs[i]),
                    WaitForOperation);
            }
        }