/// <summary>
        /// Instantiate a new VM Role
        /// </summary>
        public static Role CreateVMRole(this IVirtualMachineOperations client, string cloudServiceName, string roleName, string image, string size, string userName, string password, OSVirtualHardDisk osVHD)
        {
            Role vmRole = new Role
            {
                RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
                RoleName = roleName,
                Label = roleName,
                RoleSize = size,
                ConfigurationSets = new List<ConfigurationSet>(),
                //OSVirtualHardDisk = osVHD, 
                ProvisionGuestAgent = true,
                ResourceExtensionReferences = null,
                VMImageName = image,
               //OSVersion = "Windows Server 2012 R2 Datacenter"                
            };
            ConfigurationSet configSet = new ConfigurationSet
            {
                ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                EnableAutomaticUpdates = true,
                ResetPasswordOnFirstLogon = false,
                ComputerName = roleName,
                AdminUserName = userName,
                AdminPassword = password,
                InputEndpoints = new BindingList<InputEndpoint>
               {
                   new InputEndpoint { LocalPort = 3389, Name = "RDP", Protocol = "tcp" },
                   new InputEndpoint { LocalPort = 80, Port = 80, Name = "web", Protocol = "tcp" }
               }
            };

            vmRole.ConfigurationSets.Add(configSet);
            return vmRole;
        }
Esempio n. 2
0
        public static string GetPublicIPName(Microsoft.WindowsAzure.Management.Compute.Models.Role vmRole)
        {
            string name = null;

            if (vmRole != null && vmRole.ConfigurationSets != null && vmRole.ConfigurationSets.Any())
            {
                var networkCfg = vmRole.ConfigurationSets
                                 .Where(c => string.Equals(c.ConfigurationSetType, ConfigurationSetTypes.NetworkConfiguration, StringComparison.OrdinalIgnoreCase))
                                 .SingleOrDefault();

                if (networkCfg != null)
                {
                    var publicIp = networkCfg.PublicIPs.FirstOrDefault();
                    name = publicIp == null ? null : publicIp.Name;
                }
            }

            return(name);
        }
        /// <summary>
        ///     Create virtual machine
        /// </summary>
        /// <param name="hostedServiceName"></param>
        /// <param name="osVirtualHardDisk"></param>
        /// <param name="configurationSets"></param>
        /// <param name="dataVirtualHardDisks"></param>
        /// <param name="virtualMachineName"></param>
        /// <param name="deploymentName"></param>
        /// <returns></returns>
        public string CreateVirtualMachine(
            string hostedServiceName,
            OSVirtualHardDisk osVirtualHardDisk,
            IList<ConfigurationSet> configurationSets,
            IList<DataVirtualHardDisk> dataVirtualHardDisks = null,
            string virtualMachineName = "",
            string deploymentName = "")
        {
            if (string.IsNullOrEmpty(deploymentName))
            {
                deploymentName = Dependencies.TestResourcesCollector.GetUniqueDeploymentName();
            }

            if (string.IsNullOrEmpty(virtualMachineName))
            {
                virtualMachineName = Dependencies.TestResourcesCollector.GetUniqueVirtualMachineName();
            }

            var csm = new AzureCloudServiceManager();
            csm.CreateOrUpdateDeployment(hostedServiceName, new DeploymentCreateParameters { Name = deploymentName });

            var vmDeployment = csm.CreateOrUpdateDeployment(hostedServiceName, new DeploymentCreateParameters { 
                Name = deploymentName, 
                Label = Base64EncodingHelper.EncodeToBase64String(AzureServiceConstants.DefaultLabel)
            });
                
            var vmRole = new Role
            {
                RoleName = virtualMachineName,
                RoleType = "PersistentVMRole",
                OSVirtualHardDisk = osVirtualHardDisk,
                ConfigurationSets = configurationSets,
                DataVirtualHardDisks = dataVirtualHardDisks
            };

            vmDeployment.Roles.Add(vmRole);

            return CreateVirtualMachine(hostedServiceName, vmDeployment, virtualMachineName);
        }
Esempio n. 4
0
 public static VirtualMachineUpdateParameters GetVMUpdateParameters(Role roleToUpdate, string storageAccount,
     IEnumerable<ConfigurationSet> configSets, bool preserveOriginalConfigSets)
 {
     VirtualMachineUpdateParameters updateParameters = new VirtualMachineUpdateParameters
     {
         Label = roleToUpdate.Label,
         RoleName = roleToUpdate.RoleName,
         AvailabilitySetName = roleToUpdate.AvailabilitySetName,
         ConfigurationSets = preserveOriginalConfigSets ? roleToUpdate.ConfigurationSets : new List<ConfigurationSet>(),
         DataVirtualHardDisks = new List<DataVirtualHardDisk>(),
         OSVirtualHardDisk = new OSVirtualHardDisk(),
         ProvisionGuestAgent = roleToUpdate.ProvisionGuestAgent,
         ResourceExtensionReferences = roleToUpdate.ResourceExtensionReferences,
         RoleSize = roleToUpdate.RoleSize
     };
     if (updateParameters.ConfigurationSets == null)
     {
         updateParameters.ConfigurationSets = configSets.ToList();
     }
     else
     {
         foreach (var configurationSet in configSets)
         {
             updateParameters.ConfigurationSets.Add(configurationSet);
         }
     }
     return updateParameters;
 }
Esempio n. 5
0
        /// <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;
            }
        }
Esempio n. 6
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;
        }
Esempio n. 7
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;
            }
        }
Esempio n. 8
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;
            }

        }
 private static VirtualMachineCreateParameters ConvertRoleToVirtualMachineCreateParameters(Role role)
 {
     return new VirtualMachineCreateParameters
     {
         AvailabilitySetName = role.AvailabilitySetName,
         ConfigurationSets = role.ConfigurationSets,
         DataVirtualHardDisks = role.DataVirtualHardDisks,
         OSVirtualHardDisk = role.OSVirtualHardDisk,
         ProvisionGuestAgent = role.ProvisionGuestAgent,
         ResourceExtensionReferences = role.ResourceExtensionReferences,
         RoleName = role.RoleName,
         RoleSize = role.RoleSize,
         VMImageName = role.VMImageName,
     };
 }
Esempio n. 10
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();


        }