/// <summary>
 /// The Add Role operation adds a virtual machine to an existing
 /// deployment.  You can refer to the OSDisk in the Add Role operation
 /// in the following ways.  Platform/User Image – Set the
 /// SourceImageName to a platform or user image. You can optionally
 /// specify the DiskName and MediaLink values as part the operation to
 /// control the name and location of target disk.  When DiskName and
 /// MediaLink are specified in this mode, they must not already exist
 /// in the system, otherwise a conflict fault is returned.  UserDisk –
 /// Set DiskName to a user supplied image in image repository.
 /// SourceImageName must be set to NULL. All other properties are
 /// ignored.  Blob in a Storage Account – Set MediaLink to a blob
 /// containing the image. SourceImageName and DiskName are set to
 /// NULL.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOperations.
 /// </param>
 /// <param name='serviceName'>
 /// The name of your service.
 /// </param>
 /// <param name='deploymentName'>
 /// The name of your deployment.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create Virtual Machine operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginCreating(this IVirtualMachineOperations operations, string serviceName, string deploymentName, VirtualMachineCreateParameters parameters)
 {
     try
     {
         return operations.BeginCreatingAsync(serviceName, deploymentName, parameters).Result;
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
        public void NewAzureVMProcess()
        {
            AzureSubscription currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount(Profile);
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }

            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
            {
                var parameter = new HostedServiceCreateParameters
                {
                    AffinityGroup = this.AffinityGroup,
                    Location = this.Location,
                    ServiceName = this.ServiceName,
                    Description = this.ServiceDescription ?? String.Format(
                                      "Implicitly created hosted service{0}",
                                      DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                    Label = this.ServiceLabel ?? this.ServiceName,
                    ReverseDnsFqdn = this.ReverseDnsFqdn
                };

                try
                {
                    this.ComputeClient.HostedServices.Create(parameter);
                }
                catch (CloudException ex)
                {
                    if (string.Equals(ex.Error.Code, "ConflictError"))
                    {
                        HostedServiceGetResponse existingService = this.ComputeClient.HostedServices.Get(this.ServiceName);

                        if (existingService == null || existingService.Properties == null)
                        {
                            // The same service name is already used by another subscription.
                            WriteExceptionError(ex);
                            return;
                        }
                        else if ((string.IsNullOrEmpty(existingService.Properties.Location) &&
                            string.Compare(existingService.Properties.AffinityGroup, this.AffinityGroup, StringComparison.InvariantCultureIgnoreCase) == 0)
                            || (string.IsNullOrEmpty(existingService.Properties.AffinityGroup) &&
                            string.Compare(existingService.Properties.Location, this.Location, StringComparison.InvariantCultureIgnoreCase) == 0))
                        {
                            // The same service name is already created under the same subscription,
                            // and its affinity group or location is matched with the given parameter.
                            this.WriteWarning(ex.Error.Message);
                        }
                        else
                        {
                            // The same service name is already created under the same subscription,
                            // but its affinity group or location is not matched with the given parameter.
                            this.WriteWarning("Location or AffinityGroup name is not matched with the existing service");
                            WriteExceptionError(ex);
                            return;
                        }
                    }
                    else
                    {
                        WriteExceptionError(ex);
                        return;
                    }
                }
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType<Model.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if(!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters = CertUtilsNewSM.Create(vm.WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory<OperationStatusResponse, ManagementOperationContext>(r, s));

                }

                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                    select new
                           {
                               c.Thumbprint,
                               CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                           };

                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory<OperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select((vm, index) => CreatePersistentVMRole(VMTuples[index], currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot = DeploymentSlot.Production,
                        Name = this.DeploymentName ?? this.ServiceName,
                        Label = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles = { persistentVMs[0] },
                        ReservedIPName = ReservedIPName
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(
                                new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer
                                {
                                    Name = dns.Name,
                                    Address = dns.Address
                                });
                        }
                    }

                    if (this.InternalLoadBalancerConfig != null)
                    {
                        parameters.LoadBalancers = new LoadBalancer[1]
                        {
                            new LoadBalancer
                            {
                                Name = this.InternalLoadBalancerConfig.InternalLoadBalancerName,
                                FrontendIPConfiguration = new FrontendIPConfiguration
                                {
                                    Type = FrontendIPConfigurationType.Private,
                                    SubnetName = this.InternalLoadBalancerConfig.SubnetName,
                                    StaticVirtualNetworkIPAddress = this.InternalLoadBalancerConfig.IPAddress
                                }
                            }
                        };
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if(this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        WriteExceptionError(ex);
                    }

                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

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

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);
                
                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk = VMTuples[i].Item3 ? null : persistentVMs[i].OSVirtualHardDisk,
                    RoleName = persistentVMs[i].RoleName,
                    RoleSize = persistentVMs[i].RoleSize,
                    ProvisionGuestAgent = persistentVMs[i].ProvisionGuestAgent,
                    ResourceExtensionReferences = persistentVMs[i].ProvisionGuestAgent != null && persistentVMs[i].ProvisionGuestAgent.Value ? persistentVMs[i].ResourceExtensionReferences : null,
                    VMImageName = VMTuples[i].Item3 ? persistentVMs[i].VMImageName : null,
                    MediaLocation = VMTuples[i].Item3 ? persistentVMs[i].MediaLocation : null
                };

                if (parameter.OSVirtualHardDisk != null)
                {
                    parameter.OSVirtualHardDisk.IOType = null;
                }

                if (persistentVMs[i].DataVirtualHardDisks != null && persistentVMs[i].DataVirtualHardDisks.Any())
                {
                    persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                    parameter.DataVirtualHardDisks.ForEach(d => d.IOType = null);
                }

                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if(this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
 /// <summary>
 /// The Add Role operation adds a virtual machine to an existing
 /// deployment.  You can refer to the OSDisk in the Add Role operation
 /// in the following ways.  Platform/User Image – Set the
 /// SourceImageName to a platform or user image. You can optionally
 /// specify the DiskName and MediaLink values as part the operation to
 /// control the name and location of target disk.  When DiskName and
 /// MediaLink are specified in this mode, they must not already exist
 /// in the system, otherwise a conflict fault is returned.  UserDisk –
 /// Set DiskName to a user supplied image in image repository.
 /// SourceImageName must be set to NULL. All other properties are
 /// ignored.  Blob in a Storage Account – Set MediaLink to a blob
 /// containing the image. SourceImageName and DiskName are set to
 /// NULL.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOperations.
 /// </param>
 /// <param name='serviceName'>
 /// The name of your service.
 /// </param>
 /// <param name='deploymentName'>
 /// The name of your deployment.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create Virtual Machine operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<OperationResponse> BeginCreatingAsync(this IVirtualMachineOperations operations, string serviceName, string deploymentName, VirtualMachineCreateParameters parameters)
 {
     return operations.BeginCreatingAsync(serviceName, deploymentName, parameters, CancellationToken.None);
 }
 /// <summary>
 /// The Begin Creating Role operation adds a virtual machine to an
 /// existing deployment. You can refer to the OSDisk in the Add Role
 /// operation in the following ways: Platform/User Image - Set the
 /// SourceImageName to a platform or user image. You can optionally
 /// specify the DiskName and MediaLink values as part the operation to
 /// control the name and location of target disk. When DiskName and
 /// MediaLink are specified in this mode, they must not already exist
 /// in the system, otherwise a conflict fault is returned; UserDisk -
 /// Set DiskName to a user supplied image in image repository.
 /// SourceImageName must be set to NULL. All other properties are
 /// ignored; or Blob in a Storage Account - Set MediaLink to a blob
 /// containing the image. SourceImageName and DiskName are set to
 /// NULL.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.Compute.IVirtualMachineOperations.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The name of your service.
 /// </param>
 /// <param name='deploymentName'>
 /// Required. The name of your deployment.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Begin Creating Virtual Machine
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginCreating(this IVirtualMachineOperations operations, string serviceName, string deploymentName, VirtualMachineCreateParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IVirtualMachineOperations)s).BeginCreatingAsync(serviceName, deploymentName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        /// <author>Bart</author>
        /// <summary>
        /// Deze methode is om een nieuwe Virtual Machine aan te maken op Azure, wanneer er al een deployment is gemaakt.
        /// </summary>
        /// <param name="virtualMachine">Is het model van de Virtual Machine</param>
        /// <returns>Een true of false respectiefelijk aan of de actie geslaagt is of niet.</returns>
        private Boolean WithoutDeployment(VirtualMachine virtualMachine)
        {
            try {
                ComputeManagementClient client = new ComputeManagementClient(cloudCredentials);

                //Stap 1 : Het klaarzetten van de meeste data uit het VirtualMachine model.

                string vmName = virtualMachine.Naam;
                string uName = virtualMachine.VMuser;
                string uPassword = virtualMachine.VMpass;
                string cloudServiceName = virtualMachine.IP;
                int port = virtualMachine.PoortNr;

                string imageName = null;
                switch (virtualMachine.Type)
                {
                    case VirtualMachineTypes.Sharepoint:
                        imageName = sc.GetValue("sharepointImg");
                        break;
                    case VirtualMachineTypes.SQLServer:
                        imageName = sc.GetValue("sqlImg");
                        break;
                }

                //Stap 2 : Het maken van de configuratie van de VM.

                ResourceExtensionReference resourceExtensionReference = new ResourceExtensionReference()
                {
                    ReferenceName = "VMAccessAgent",
                    Name = "VMAccessAgent",
                    Publisher = "Microsoft.Compute",
                    Version = "2.0"
                };

                ConfigurationSet configSet = new ConfigurationSet()
                {
                    ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                    EnableAutomaticUpdates = false,
                    ComputerName = vmName,
                    AdminUserName = uName,
                    AdminPassword = uPassword,
                };

                ConfigurationSet networkConfigSet = new ConfigurationSet()
                {
                    ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                    InputEndpoints = new List<InputEndpoint>
                    {
                        new InputEndpoint()
                        {
                            LocalPort = int.Parse(sc.GetValue("rdpPort")),
                            Name = "Remote Desktop",
                            Port = port,
                            Protocol = InputEndpointTransportProtocol.Tcp,
                            EnableDirectServerReturn = false
                        }
                    }
                };

                //Stap 3 : Het zetten van alle gegevens in één CreateParameters object.

                VirtualMachineCreateParameters virtualMachineParams = new VirtualMachineCreateParameters
                {
                    RoleName = vmName,
                    RoleSize = VirtualMachineRoleSize.Small,
                    ProvisionGuestAgent = true,
                    ConfigurationSets = new List<ConfigurationSet>(),
                    ResourceExtensionReferences = new List<ResourceExtensionReference>(),
                    OSVirtualHardDisk = new OSVirtualHardDisk()
                    {
                        MediaLink = GetVhdUri(string.Format("{0}.blob.core.windows.net/vhds", relatedStorageAccountName)),
                        SourceImageName = GetSourceImageNameByFamilyName(imageName)
                    }
                };

                virtualMachineParams.ResourceExtensionReferences.Add(resourceExtensionReference);
                virtualMachineParams.ConfigurationSets.Add(configSet);
                virtualMachineParams.ConfigurationSets.Add(networkConfigSet);

                //Stap 4 : Het werkelijke creëren van de VM.

                client.VirtualMachines.Create(cloudServiceName, "VMs", virtualMachineParams);
                System.Diagnostics.Debug.Write("Create VM Succes");
                return true;
            }
            catch (CloudException e)
            {
                throw e;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #6
0
        private OperationStatusResponse AddVm(string serviceName, string virtualMachineName, ConfigurationSet windowsConfigurationSet, ConfigurationSet endpoints, OSVirtualHardDisk vhd, VMConfigModel vmConfig)
        {
            OperationStatusResponse deploymentResult;
            var createVMParameters = new VirtualMachineCreateParameters
            {

                RoleName = virtualMachineName,
                RoleSize = MapToAzureVmSize(vmConfig.VmSize),
                OSVirtualHardDisk = vhd,
                ProvisionGuestAgent = true,
                ConfigurationSets = new List<ConfigurationSet>
                    {
                        windowsConfigurationSet,
                        endpoints,
                    },
            };

            if (vmConfig.InsertCaptureScript)
            {
                createVMParameters.ResourceExtensionReferences =
                    CreateCaptureScript(vmConfig.CaptureKey, vmConfig.ChocoPackageList);
            }

            deploymentResult = _compute.VirtualMachines.Create(serviceName, serviceName, createVMParameters);
            return deploymentResult;
        }
Example #7
0
        private void AddRole(string cloudServiceName, string deploymentName, Role role, DeploymentSlot slot = DeploymentSlot.Production)
        {
            try
            {
                using (var computeClient = new ComputeManagementClient(_credentials))
                {

                    VirtualMachineCreateParameters createParams = new VirtualMachineCreateParameters
                    {
                        RoleName = role.RoleName,
                        RoleSize = role.RoleSize,
                        OSVirtualHardDisk = role.OSVirtualHardDisk,
                        ConfigurationSets = role.ConfigurationSets,
                        AvailabilitySetName = role.AvailabilitySetName,
                        DataVirtualHardDisks = role.DataVirtualHardDisks,
                        ProvisionGuestAgent = role.ProvisionGuestAgent

                    };
                    computeClient.VirtualMachines.Create(cloudServiceName, deploymentName, createParams);
                }
            }
            catch (CloudException e)
            {
                throw e;
            }

        }
        protected PSArgument[] CreateVirtualMachineCreateParameters()
        {
            string serviceName = string.Empty;
            string deploymentName = string.Empty;
            VirtualMachineCreateParameters parameters = new VirtualMachineCreateParameters();

            return ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentName", "Parameters" }, new object[] { serviceName, deploymentName, parameters });
        }
Example #9
0
        /// <summary>
        /// Creates deployment and virtual machines in destination subscription.
        /// </summary>
        /// <param name="deploymentDetails">Deployment details</param>
        /// <param name="serviceName">Cloud service name</param>        
        private void CreateDeployment(Deployment deploymentDetails, string serviceName)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Logger.Info(methodName, ProgressResources.ExecutionStarted, ResourceType.Deployment.ToString(), deploymentDetails.Name);
            Stopwatch swTotalDeploymentWithVMs = new Stopwatch();
            swTotalDeploymentWithVMs.Start();
            if (!deploymentDetails.IsImported)
            {
                //List<Uri> disks = null;
                string containerName;
                using (var client = new ComputeManagementClient(importParameters.SourceSubscriptionSettings.Credentials,
                    importParameters.SourceSubscriptionSettings.ServiceUrl))
                {
                    try
                    {
                        using (var computeClient = new ComputeManagementClient(importParameters.DestinationSubscriptionSettings.Credentials))
                        {
                            for (int virtualMachineNumber = 0; virtualMachineNumber < deploymentDetails.VirtualMachines.Count(); virtualMachineNumber++)
                            {
                                VirtualMachine virtualMachine = deploymentDetails.VirtualMachines[virtualMachineNumber];
                                // Check if virtual machine is already imported, if not create new virtual machine
                                if (!virtualMachine.IsImported)
                                {
                                    string sourceStorageAccountName = virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.MediaLink.Host.Substring(
                                        0, virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.MediaLink.Host.IndexOf('.'));
                                    string accountName = GetDestinationResourceName(ResourceType.StorageAccount, sourceStorageAccountName);
                                    Stopwatch swDeployment = new Stopwatch();
                                    swDeployment.Start();
                                    containerName = virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.MediaLink.Segments[1].Substring(0,
                                        virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.MediaLink.Segments[1].IndexOf('/')); ;

                                    // Set up the Virtual Hard Disk with the OS Disk
                                    var vhd = new OSVirtualHardDisk
                                    {
                                        HostCaching = virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.HostCaching,
                                        //IOType is implicitly determined from the MediaLink. This should not be explicitly specified in the request.
                                        Label = virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.Label,
                                        MediaLink = new Uri(string.Format(CultureInfo.InvariantCulture,
                                            Constants.StorageAccountMediaLink,
                                            accountName, containerName,
                                            virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.MediaLink.Segments.Last()), UriKind.Absolute),
                                        Name = string.Format("{0}{1}", importParameters.DestinationPrefixName,
                                        GetDestinationResourceName(ResourceType.OSDisk, virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.Name,
                                            ResourceType.CloudService, serviceName)),
                                        OperatingSystem = virtualMachine.VirtualMachineDetails.OSVirtualHardDisk.OperatingSystem,
                                        //SourceImageName should be set only when creating the virtual machine from an image. Here we create it from a disk.
                                    };

                                    // Set up the Data Disk
                                    List<DataVirtualHardDisk> dataDisks = new List<DataVirtualHardDisk>();
                                    foreach (var disk in virtualMachine.VirtualMachineDetails.DataVirtualHardDisks)
                                    {
                                        dataDisks.Add(new DataVirtualHardDisk
                                        {
                                            HostCaching = disk.HostCaching,
                                            //IOType is implicitly determined from the MediaLink. This should not be explicitly specified in the request.
                                            Label = disk.Label,
                                            LogicalDiskSizeInGB = disk.LogicalDiskSizeInGB,
                                            LogicalUnitNumber = disk.LogicalUnitNumber,
                                            MediaLink = new Uri(string.Format(CultureInfo.InvariantCulture,
                                                Constants.StorageAccountMediaLink, accountName, containerName,
                                                disk.MediaLink.Segments.Last()), UriKind.Absolute),
                                            Name = string.Format("{0}{1}", importParameters.DestinationPrefixName,
                                                GetDestinationResourceName(ResourceType.HardDisk, disk.Name, ResourceType.CloudService, serviceName)),
                                            SourceMediaLink = new Uri(string.Format(CultureInfo.InvariantCulture,
                                                Constants.StorageAccountMediaLink, accountName, containerName,
                                                disk.MediaLink.Segments.Last()), UriKind.Absolute)
                                        });
                                    };

                                    // Deploy the Virtual Machine
                                    Logger.Info(methodName, string.Format(ProgressResources.ImportVirtualMachineStarted,
                                                      virtualMachine.VirtualMachineDetails.RoleName, deploymentDetails.Name),
                                                      ResourceType.VirtualMachine.ToString(), virtualMachine.VirtualMachineDetails.RoleName);

                                    // For first virtual machine create new deployment
                                    if (virtualMachineNumber == 0)
                                    {
                                        List<Role> roles = new List<Role>();
                                        roles.Add(new Role
                                        {
                                            AvailabilitySetName = virtualMachine.VirtualMachineDetails.AvailabilitySetName,
                                            ConfigurationSets = virtualMachine.VirtualMachineDetails.ConfigurationSets,
                                            DataVirtualHardDisks = dataDisks,
                                            DefaultWinRmCertificateThumbprint = virtualMachine.VirtualMachineDetails.DefaultWinRmCertificateThumbprint,
                                            Label = null, // Label is set automatically.
                                            MediaLocation = virtualMachine.VirtualMachineDetails.MediaLocation,
                                            OSVersion = virtualMachine.VirtualMachineDetails.OSVersion,
                                            OSVirtualHardDisk = vhd,
                                            ProvisionGuestAgent = true,
                                            ResourceExtensionReferences = virtualMachine.VirtualMachineDetails.ResourceExtensionReferences,
                                            RoleName = virtualMachine.VirtualMachineDetails.RoleName,
                                            RoleSize = virtualMachine.VirtualMachineDetails.RoleSize,
                                            RoleType = virtualMachine.VirtualMachineDetails.RoleType,
                                            VMImageName = virtualMachine.VirtualMachineDetails.VMImageName
                                        });

                                        // Create the deployment parameters
                                        var createDeploymentParameters = new VirtualMachineCreateDeploymentParameters
                                        {
                                            DeploymentSlot = DeploymentSlot.Production,
                                            DnsSettings = deploymentDetails.DnsSettings,
                                            Label = deploymentDetails.Name, // Set it to new name instead of old deployment label.
                                            LoadBalancers = deploymentDetails.LoadBalancers,
                                            Name = deploymentDetails.Name,
                                            ReservedIPName = deploymentDetails.ReservedIPName,
                                            Roles = roles,
                                            VirtualNetworkName = deploymentDetails.VirtualNetworkName
                                        };
                                        var deploymentResult = Retry.RetryOperation(() => computeClient.VirtualMachines.CreateDeployment(
                                            serviceName, createDeploymentParameters), (BaseParameters)importParameters, ResourceType.VirtualMachine,
                                            virtualMachine.VirtualMachineDetails.RoleName);

                                        UpdateMedatadaFile(ResourceType.VirtualMachine, virtualMachine.VirtualMachineDetails.RoleName,
                                            parentResourceName: serviceName);

                                    }
                                    // Add virtual machine in existing deployment
                                    else
                                    {
                                        VirtualMachineCreateParameters parameters = new VirtualMachineCreateParameters
                                        {
                                            AvailabilitySetName = virtualMachine.VirtualMachineDetails.AvailabilitySetName,
                                            ConfigurationSets = virtualMachine.VirtualMachineDetails.ConfigurationSets,
                                            DataVirtualHardDisks = dataDisks,
                                            MediaLocation = virtualMachine.VirtualMachineDetails.MediaLocation,
                                            OSVirtualHardDisk = vhd,
                                            ProvisionGuestAgent = true,
                                            ResourceExtensionReferences = virtualMachine.VirtualMachineDetails.ResourceExtensionReferences,
                                            RoleName = virtualMachine.VirtualMachineDetails.RoleName,
                                            RoleSize = virtualMachine.VirtualMachineDetails.RoleSize,
                                            VMImageName = virtualMachine.VirtualMachineDetails.VMImageName
                                        };

                                        Retry.RetryOperation(() => computeClient.VirtualMachines.Create(serviceName, deploymentDetails.Name, parameters),
                                           (BaseParameters)importParameters, ResourceType.VirtualMachine, virtualMachine.VirtualMachineDetails.RoleName,
                                            () => DeleteVirtualMachineIfTaskCancelled(ResourceType.VirtualMachine, serviceName, deploymentDetails.Name, virtualMachine.VirtualMachineDetails.RoleName));

                                        UpdateMedatadaFile(ResourceType.VirtualMachine, virtualMachine.VirtualMachineDetails.RoleName, parentResourceName: serviceName);
                                    }
                                    swDeployment.Stop();
                                    Logger.Info(methodName, string.Format(ProgressResources.ImportVirtualMachineCompleted,
                                                    virtualMachine.VirtualMachineDetails.RoleName, deploymentDetails.Name, swDeployment.Elapsed.Days, swDeployment.Elapsed.Hours,
                                                    swDeployment.Elapsed.Minutes, swDeployment.Elapsed.Seconds),
                                                    ResourceType.VirtualMachine.ToString(), virtualMachine.VirtualMachineDetails.RoleName);

                                    // ShutDown created virtual machine.
                                    computeClient.VirtualMachines.Shutdown(serviceName, deploymentDetails.Name,
                                        virtualMachine.VirtualMachineDetails.RoleName,
                                        new VirtualMachineShutdownParameters { PostShutdownAction = PostShutdownAction.StoppedDeallocated });
                                }
                            }
                            UpdateMedatadaFile(ResourceType.Deployment, deploymentDetails.Name, parentResourceName: serviceName);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(methodName, ex, ResourceType.Deployment.ToString(), deploymentDetails.Name);
                        throw;
                    }
                }
            }
            swTotalDeploymentWithVMs.Stop();
            Logger.Info(methodName, string.Format(ProgressResources.ExecutionCompletedWithTime, swTotalDeploymentWithVMs.Elapsed.Days, swTotalDeploymentWithVMs.Elapsed.Hours,
                swTotalDeploymentWithVMs.Elapsed.Minutes, swTotalDeploymentWithVMs.Elapsed.Seconds), ResourceType.Deployment.ToString(), deploymentDetails.Name);
        }