/// <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
        /// <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;
            }
        }
Esempio n. 3
0
        private void GenerateVM(string serviceName, VMConfigModel vmConfig, string virtualMachineName, 
			int rdpPort, VMUserModel user, bool firstVMInDeployment)
        {
            var windowsConfigurationSet = new ConfigurationSet
            {
                //TODO: depends on the OS type??
                ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
                AdminPassword = user.Password,
                AdminUserName = user.Username,
                ComputerName = virtualMachineName,
                HostName = string.Format("{0}.cloudapp.net", serviceName),

            };

            var endpoints = new ConfigurationSet
            {
                ConfigurationSetType = "NetworkConfiguration",
                InputEndpoints = new List<InputEndpoint>
                {
                    new InputEndpoint
                    {
                        Name = "RDP",
                        Port = rdpPort,
                        Protocol = "TCP",
                        LocalPort = InternalRdpPort
                    }
                }
            };

            string newVhdName = string.Format("{0}.vhd", virtualMachineName);

            Uri mediaUri = new Uri(GetVHDStorageUrl(vmConfig.Region) + newVhdName);

            var vhd = new OSVirtualHardDisk
            {
                SourceImageName = vmConfig.ImageName,
                HostCaching = VirtualHardDiskHostCaching.ReadWrite,
                MediaLink = mediaUri,

            };

            OperationStatusResponse deploymentResult;

            if (firstVMInDeployment)
            {
                deploymentResult = CreateDeployment(serviceName, virtualMachineName, windowsConfigurationSet, endpoints, vhd, vmConfig);

            }
            else
            {
                deploymentResult = AddVm(serviceName, virtualMachineName, windowsConfigurationSet, endpoints, vhd, vmConfig);
            }
            //TODO: handle the deploymentResult
        }
Esempio n. 4
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. 5
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;
        }
Esempio n. 6
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. 7
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();


        }
Esempio n. 8
0
        public async static Task<string> CreateVirtualMachine(
  SubscriptionCloudCredentials credentials)
        {
            using (var storageClient = new StorageManagementClient(credentials))
            {
                try
                {
                    storageClient.StorageAccounts.Create(new StorageAccountCreateParameters
                    {
                        AccountType = "Standard_LRS",
                        // GeoReplicationEnabled = false,
                        Label = "Sample Storage Account",
                        Location = "East US",
                        Name = "mbjastorage"
                    });
                }
                catch (Exception e)
                { }
            }
            using (var computeClient = new ComputeManagementClient(credentials))
            {
                try
                {
                    var operatingSystemImageListResult =
         await computeClient.VirtualMachineOSImages.ListAsync();
                    var imageName =
                      operatingSystemImageListResult.Images.FirstOrDefault(
                        x => x.Label.Contains(
                          "Windows Server 2012 R2 Datacenter, March 2014")).Name;

                    var windowsConfigSet = new ConfigurationSet
                    {
                        ConfigurationSetType =
        ConfigurationSetTypes.WindowsProvisioningConfiguration,
                        AdminPassword =
        "******",
                        AdminUserName = "******",
                        ComputerName = "libraryvm01",
                        HostName = string.Format("{0}.cloudapp.net",
        "libraryvm01")
                    };
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return "Successfully created Virtual Machine";
        }