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);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if (!string.IsNullOrEmpty(this.Location))
            {
                if (serviceExists)
                {
                    HostedServiceGetResponse existingSvc = null;
                    try
                    {
                        existingSvc = ComputeClient.HostedServices.Get(this.ServiceName);
                    }
                    catch
                    {
                        throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                    }

                    if (existingSvc == null ||
                        existingSvc.Properties == null ||
                        !this.Location.Equals(existingSvc.Properties.Location))
                    {
                        throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    HostedServiceGetResponse existingSvc = null;
                    try
                    {
                        existingSvc = ComputeClient.HostedServices.Get(this.ServiceName);
                    }
                    catch
                    {
                        throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                    }

                    if (existingSvc == null ||
                        existingSvc.Properties == null ||
                        !this.AffinityGroup.Equals(existingSvc.Properties.AffinityGroup))
                    {
                        throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.ReverseDnsFqdn))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsReverseDnsFqdnCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                try
                {
                    //Implicitly created hosted service2012-05-07 23:12 

                    // Create the Cloud Service when
                    // Location or Affinity Group is Specified
                    // or VNET is specified and the service doesn't exist
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup = this.AffinityGroup,
                        Location = this.Location,
                        ServiceName = this.ServiceName,
                        Description = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label = this.ServiceName,
                        ReverseDnsFqdn = this.ReverseDnsFqdn
                    };

                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + Resources.QuickVMCreateCloudService,
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
                catch (CloudException ex)
                {
                    WriteExceptionError(ex);
                    return;
                }
            }

            if (ParameterSetName.Equals(WindowsParamSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

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

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

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                                                         {
                                                             c.Thumbprint,
                                                             CertificateFile = CertUtilsNewSM.Create(c, this.NoExportPrivateKey.IsPresent)
                                                         };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionNewSM(
                            null,
                            operationDescription,
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                            (s, r) => ContextFactory<OperationStatusResponse, ManagementOperationContext>(r, s));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            try
            {
                if (CurrentDeploymentNewSM == null)
                {
                    // If the current deployment doesn't exist set it create it
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.ServiceName,
                        Label              = this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { vm },
                        ReservedIPName     = this.ReservedIPName,
                        DnsSettings        = this.DnsSettings == null ? null : new Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings
                                             {
                                                 DnsServers = (from dns in this.DnsSettings
                                                               select new Management.Compute.Models.DnsServer
                                                               {
                                                                   Name = dns.Name,
                                                                   Address = dns.Address
                                                               }).ToList()
                                             }
                    };

                    ExecuteClientActionNewSM(
                        parameters,
                        string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));
                }
                else
                {
                    if (!string.IsNullOrEmpty(VNetName) || DnsSettings != null)
                    {
                        WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                    }

                    // Only create the VM when a new VM was added and it was not created during the deployment phase.
                    ExecuteClientActionNewSM(
                        vm,
                        string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.Create(
                            this.ServiceName,
                            this.ServiceName,
                            new VirtualMachineCreateParameters
                            {
                                AvailabilitySetName         = vm.AvailabilitySetName,
                                OSVirtualHardDisk           = vm.OSVirtualHardDisk,
                                DataVirtualHardDisks        = vm.DataVirtualHardDisks,
                                RoleName                    = vm.RoleName,
                                RoleSize                    = vm.RoleSize,
                                VMImageName                 = vm.VMImageName,
                                MediaLocation               = vm.MediaLocation,
                                ProvisionGuestAgent         = vm.ProvisionGuestAgent,
                                ResourceExtensionReferences = vm.ResourceExtensionReferences,
                                ConfigurationSets           = vm.ConfigurationSets
                            }));
                }

                if (WaitForBoot.IsPresent)
                {
                    WaitForRoleToBoot(vm.RoleName);
                }
            }
            catch (CloudException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                }

                WriteExceptionError(ex);
            }
        }
        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);
                }
            }
        }
        protected PSArgument[] CreateVirtualMachineCreateDeploymentParameters()
        {
            string serviceName = string.Empty;
            VirtualMachineCreateDeploymentParameters parameters = new VirtualMachineCreateDeploymentParameters();

            return ConvertFromObjectsToArguments(new string[] { "ServiceName", "Parameters" }, new object[] { serviceName, parameters });
        }
 /// <summary>
 /// The Create Virtual Machine Deployment operation provisions a
 /// virtual machine based on the supplied configuration.  When you
 /// create a deployment of a virtual machine, you should make sure
 /// that the cloud service and the disk or image that you use are
 /// located in the same region. For example, if the cloud service was
 /// created in the West US region, the disk or image that you use
 /// should also be located in a stor4age account in the West US
 /// region.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.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='parameters'>
 /// Parameters supplied to the Create Virtual Machine Deployment
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<OperationResponse> BeginCreatingDeploymentAsync(this IVirtualMachineOperations operations, string serviceName, VirtualMachineCreateDeploymentParameters parameters)
 {
     return operations.BeginCreatingDeploymentAsync(serviceName, parameters, CancellationToken.None);
 }
Example #5
0
        public static VirtualMachineCreateDeploymentParameters CreateVMParameters(VirtualMachineOSImageGetResponse image, string deploymentName, string storageAccount, string deploymentLabel, string blobUri)
        {
            var blobUrl = GetUriForVMVhd(deploymentName, storageAccount, blobUri);
            string roleName = AZT.TestUtilities.GenerateName("role");
            VirtualMachineCreateDeploymentParameters parameters = new VirtualMachineCreateDeploymentParameters
            {
                DeploymentSlot = DeploymentSlot.Production,
                Label = deploymentLabel,
                Name = deploymentName
            };
            parameters.Roles.Add(new Role
            {
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    HostCaching = VirtualHardDiskHostCaching.ReadWrite,
                    MediaLink = blobUrl,
                    SourceImageName = image.Name
                },
                ProvisionGuestAgent = true,
                RoleName = roleName,
                RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleSize = VirtualMachineRoleSize.Large.ToString(),
            });

            return parameters;
        }
 /// <summary>
 /// The Begin Creating Virtual Machine Deployment operation provisions
 /// a virtual machine based on the supplied configuration. When you
 /// create a deployment of a virtual machine, you should make sure
 /// that the cloud service and the disk or image that you use are
 /// located in the same region. For example, if the cloud service was
 /// created in the West US region, the disk or image that you use
 /// should also be located in a storage account in the West US region.
 /// (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.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='parameters'>
 /// Required. Parameters supplied to the Begin Creating Virtual Machine
 /// Deployment operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginCreatingDeployment(this IVirtualMachineOperations operations, string serviceName, VirtualMachineCreateDeploymentParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IVirtualMachineOperations)s).BeginCreatingDeploymentAsync(serviceName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// The Create Virtual Machine Deployment operation provisions a
 /// virtual machine based on the supplied configuration.  When you
 /// create a deployment of a virtual machine, you should make sure
 /// that the cloud service and the disk or image that you use are
 /// located in the same region. For example, if the cloud service was
 /// created in the West US region, the disk or image that you use
 /// should also be located in a stor4age account in the West US
 /// region.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.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='parameters'>
 /// Parameters supplied to the Create Virtual Machine Deployment
 /// operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static OperationResponse BeginCreatingDeployment(this IVirtualMachineOperations operations, string serviceName, VirtualMachineCreateDeploymentParameters parameters)
 {
     try
     {
         return operations.BeginCreatingDeploymentAsync(serviceName, parameters).Result;
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }
        /// <author>Bart</author>
        /// <summary>
        /// Deze methode is om een nieuwe Virtual Machine aan te maken op Azure.
        /// </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 WithDeployment(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.

                var vmRole = new Role()
                {
                    RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                    RoleName = vmName,
                    Label = 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)
                    }
                };

                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
                        }
                    }
                };

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

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

                List<Role> roleList = new List<Role>() { vmRole };
                VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters()
                {
                    Name = "VMs",
                    Label = vmName,
                    Roles = roleList,
                    DeploymentSlot = DeploymentSlot.Production
                };

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

                client.VirtualMachines.CreateDeployment(cloudServiceName, createDeploymentParams);
                System.Diagnostics.Debug.Write("Create VM Succes");
                return true;
            }
            catch (CloudException e)
            {
                throw e;
                //return false;
            }
            catch (Exception ex)
            {
                throw ex;
                //return false;
            }
        }
Example #9
0
        /// <summary>
        /// Create the Virtual Machine
        /// </summary>
        /// <param name="imageName">The OS image name to use</param>
        /// <returns></returns>
        internal async Task CreateVirtualMachine(string imageName)
        {
            // Get the details of the selected OS image
            var image = await _computeManagementClient.VirtualMachineOSImages.GetAsync(imageName);

            // The Deployment where the Virtual Machine will be hosted
            var parameters = new VirtualMachineCreateDeploymentParameters
            {
                DeploymentSlot = DeploymentSlot.Production,
                Name = _parameters.CloudServiceName,
                Label = String.Format("CloudService{0}", _parameters.CloudServiceName),
            };

            // The Role defines the details of the VM parameters
            parameters.Roles.Add(new Role
            {
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    HostCaching = VirtualHardDiskHostCaching.ReadWrite,
                    MediaLink = new Uri(string.Format("https://{0}.blob.core.windows.net/vhds/{1}",
                        _parameters.StorageAccountName, _parameters.VMName)),
                    SourceImageName = image.Name
                },
                // You could use DataVirtualHardDisks here to add additional persistent data disks
                RoleName = _parameters.VMName,
                RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleSize = VirtualMachineRoleSize.Small,
                ProvisionGuestAgent = true
            });

            // Add a ConfigurationSet for the Windows specific configuration
            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                ComputerName = _parameters.VMName, // TODO: HostName for Linux
                AdminUserName = _parameters.AdminUsername,
                AdminPassword = _parameters.AdminPassword,
                EnableAutomaticUpdates = false,
                TimeZone = "Pacific Standard Time"
            });

            // Add a ConfigurationSet describing the ports to open to the outside
            parameters.Roles[0].ConfigurationSets.Add(new ConfigurationSet
            {
                ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
                InputEndpoints = new List<InputEndpoint>()
                {
                    // Open the RDP port using a non-standard external port 
                    new InputEndpoint()
                    {
                        Name = "RDP",
                        Protocol = InputEndpointTransportProtocol.Tcp,
                        LocalPort = 3389,
                        Port = _parameters.RDPPort
                    }
                }
            });

            // Create the Virtual Machine
            var response = await _computeManagementClient.VirtualMachines.CreateDeploymentAsync(_parameters.CloudServiceName, parameters);
        }
Example #10
0
        private OperationStatusResponse CreateDeployment(string serviceName, string virtualMachineName, ConfigurationSet windowsConfigurationSet, ConfigurationSet endpoints, OSVirtualHardDisk vhd, VMConfigModel vmConfig)
        {
            OperationStatusResponse deploymentResult;
            var role = new Role
            {
                RoleName = virtualMachineName,
                RoleSize = MapToAzureVmSize(vmConfig.VmSize),
                RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                OSVirtualHardDisk = vhd,
                ProvisionGuestAgent = true,
                ConfigurationSets = new List<ConfigurationSet>
                {
                    windowsConfigurationSet,
                    endpoints,
                }
            };

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

            var createDeploymentParameters = new VirtualMachineCreateDeploymentParameters
            {
                Name = serviceName,
                Label = serviceName,
                DeploymentSlot = DeploymentSlot.Production,
                Roles = new List<Role> { role },

            };

            deploymentResult = _compute.VirtualMachines.CreateDeployment(
                serviceName,
                createDeploymentParameters);
            return deploymentResult;
        }
Example #11
0
        public async Task<string> CreateVirtualMachine(string virtualMachineName, string cloudServiceName, string storageAccountName, string username, string password, string imageFilter, string virtualMachineSize, int rdpPort, bool isCloudServiceAlreadyCreated)
        {
            using (var computeClient = new ComputeManagementClient(_credentials))
            {
                // get the list of images from the api
                var operatingSystemImageListResult =
                    await computeClient.VirtualMachineOSImages.ListAsync();

                // find the one i want
                var virtualMachineOsImage = operatingSystemImageListResult
                    .Images
                    .FirstOrDefault(x =>
                        x.Name.Contains(imageFilter));


                if (virtualMachineOsImage == null)
                {
                    throw new Exception("OS Image Name Not Foud");
                }
                var imageName =
                    virtualMachineOsImage.Name;


                // set up the configuration set for the windows image
                var windowsConfigSet = new ConfigurationSet
                {
                    ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                    AdminPassword = password,
                    AdminUserName = username,
                    ComputerName = virtualMachineName,
                    HostName = string.Format("{0}.cloudapp.net", cloudServiceName)
                  
                };

                // make sure i enable powershell & rdp access
                var endpoints = new ConfigurationSet
                {
                    ConfigurationSetType = "NetworkConfiguration",
                    InputEndpoints = new List<InputEndpoint>
                    {
                        //new InputEndpoint
                        //{
                        //    Name = "PowerShell", LocalPort = 5986, Protocol = "tcp", Port = 5986,
                        //},
                        new InputEndpoint
                        {
                            Name = "Remote Desktop",
                            LocalPort = 3389,
                            Protocol = "tcp",
                            Port = rdpPort,
                        }
                    }
                };

                // set up the hard disk with the os
                var vhd = SetOsVirtualHardDisk(virtualMachineName, storageAccountName, imageName);
                // create the role for the vm in the cloud service
                var role = new Role
                {
                    RoleName = virtualMachineName,
                    RoleSize = virtualMachineSize,
                    RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                    OSVirtualHardDisk = vhd,
                    ProvisionGuestAgent = true,

                    ConfigurationSets = new List<ConfigurationSet>
                    {
                        windowsConfigSet,
                        endpoints
                    }
                };
                var isDeploymentCreated = false;
                if (isCloudServiceAlreadyCreated)
                {
                    var vm = await computeClient.HostedServices.GetDetailedAsync(cloudServiceName);
                    isDeploymentCreated = vm.Deployments.ToList().Any(x => x.Name == cloudServiceName);
                }

                if (isDeploymentCreated)
                {
                    AddRole(cloudServiceName, cloudServiceName, role, DeploymentSlot.Production);
                }
                else
                {
                    // create the deployment parameters
                    var createDeploymentParameters = new VirtualMachineCreateDeploymentParameters
                    {
                        Name = cloudServiceName,
                        Label = cloudServiceName,
                        DeploymentSlot = DeploymentSlot.Production,
                        Roles = new List<Role> {role}
                    };


                    // deploy the virtual machine
                    var deploymentResult = await computeClient.VirtualMachines.CreateDeploymentAsync(
                        cloudServiceName,
                        createDeploymentParameters);
                }

                // return the name of the virtual machine
                return virtualMachineName;
            }
        }
 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;
     }
 }
Example #13
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);
        }
Example #14
0
        static void Main(string[] args)
        {
            //var token = GetAuthorizationHeader();
            //var credential = new TokenCloudCredentials(
            //  "ed0caab7-c6d4-45e9-9289-c7e5997c9241", token);

            //   CreateVM(credential);
            #region
            var x509Certificate2 = new X509Certificate2(@"D:/aktest.cer");
            CertificateCloudCredentials cer = new CertificateCloudCredentials("ed0caab7-c6d4-45e9-9289-c7e5997c9241", x509Certificate2);
            // CreateResources(credential);
            //var storageClient=CloudContext.Clients.CreateStorageManagementClient(cer);
            //storageClient.StorageAccounts.Create(new StorageAccountCreateParameters
            //{
            //    AccountType= "Standard_LRS",
            //    // GeoReplicationEnabled = false,
            //    Label = "Sample Storage Account",
            //    Location = "East US",
            //    Name = "mbjastorage"
            //});


            var windowsConfigSet = new ConfigurationSet
            {
                ConfigurationSetType =
     ConfigurationSetTypes.WindowsProvisioningConfiguration,
                AdminPassword =
     "******",
                AdminUserName = "******",
                ComputerName = "libraryvm01",
                HostName = string.Format("{0}.cloudapp.net",
     "libraryvm01")
            };
    
            var vmClient = CloudContext.Clients.CreateComputeManagementClient(cer);
            var operatingSystemImageListResult = vmClient.VirtualMachineOSImages.List();
            var imageName =
                    operatingSystemImageListResult.Images.FirstOrDefault(
                      x => x.Label.Contains(
                        "SQL Server 2014 RTM Standard on Windows Server 2012 R2")).Name;

            var networkConfigSet = new ConfigurationSet
            {
                ConfigurationSetType = "NetworkConfiguration",
                InputEndpoints = new List<InputEndpoint>
  {
    new InputEndpoint
    {
      Name = "PowerShell",
      LocalPort = 5986,
      Protocol = "tcp",
      Port = 5986,
    },
    new InputEndpoint
    {
      Name = "Remote Desktop",
      LocalPort = 3389,
      Protocol = "tcp",
      Port = 3389,
    }
  }
            };
            var vhd = new OSVirtualHardDisk
            {
                SourceImageName = imageName,
                HostCaching = VirtualHardDiskHostCaching.ReadWrite,
                MediaLink = new Uri(string.Format(
    "https://{0}.blob.core.windows.net/vhds/{1}.vhd",
      "willshao", imageName))
            };
            var deploymentAttributes = new Role
            {
                RoleName = "libraryvm01",
                RoleSize = VirtualMachineRoleSize.Small,
                RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                OSVirtualHardDisk = vhd,
                ConfigurationSets = new List<ConfigurationSet>
  {
    windowsConfigSet,
    networkConfigSet
  },
                ProvisionGuestAgent = true
            };
            var createDeploymentParameters =
   new VirtualMachineCreateDeploymentParameters
   {
       Name = "libraryvm01",
       Label = "libraryvm01",
       DeploymentSlot = DeploymentSlot.Production,
       Roles = new List<Role> { deploymentAttributes }
   };

            try
            {

            var mymachine=    vmClient.VirtualMachines.Get("javmtest", "javmtest", "javmtest");
       vmClient.VirtualMachines.CreateDeploymentAsync(
       "libraryvm01",
        createDeploymentParameters);
            }
            catch (Exception e)
            { }
            #endregion
            Console.ReadLine();


        }