protected void EnsureClientsInitialized(bool useSPN = false)
 {
     if (!m_initialized)
     {
         lock (m_lock)
         {
             if (!m_initialized)
             {
                 var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
                 if (useSPN)
                 {
                     m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClientWithSpn(handler);
                     m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClientWithSpn(handler);
                     m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClientSpn(handler);
                     m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClientSpn(handler);
                 }
                 else
                 {
                     m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(handler);
                     m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(handler);
                     m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(handler);
                     m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClient(handler);
                 }
                 m_subId = m_CrpClient.Credentials.SubscriptionId;
                 m_location = ComputeManagementTestUtilities.DefaultLocation;
             }
         }
     }
 }
Exemple #2
0
        public void ListVMs()
        {
            using (var computeManagementClient = new ComputeManagementClient(azureLogin.Credentials))
            {
                computeManagementClient.SubscriptionId = azureLogin.SubscriptionId;

                var result = HandleResult("List VMs in " + demo.Group,
                    () => computeManagementClient.VirtualMachines.List(demo.Group),
                    t => "Count: " + t.Count());

                if (result == null)
                    return;

                var azureVirtualMachines = new List<VirtualMachine>(result);
                while (result.NextPageLink != null)
                {
                    result = HandleResult("List Next VMs",
                        () => computeManagementClient.VirtualMachines.ListNext(result.NextPageLink),
                        t => "Count: " + t.Count());

                    if (result == null)
                        break;

                    azureVirtualMachines.AddRange(result);
                }

                var virtualMachines = azureVirtualMachines.Select(v => v.Name).ToList();
                Parallel.For(0, virtualMachines.Count, i =>
                {
                    var vmName = virtualMachines[i];
                    var vmInstance = HandleResult("Get VM instance " + vmName,
                        () => computeManagementClient.VirtualMachines.Get(demo.Group, vmName, "InstanceView"),
                        t => t.ProvisioningState);

                    if (vmInstance == null)
                        return;

                    var stat = vmInstance.InstanceView.Statuses.FirstOrDefault(s => s.Code.StartsWith("PowerState"));
                    Log.Info(string.Format("{0}: Size: {1}, State: {2}, Provisioning: {3}", 
                        vmName,
                        vmInstance.HardwareProfile.VmSize, 
                        stat == null ? "Unknown" : stat.DisplayStatus,
                        vmInstance.ProvisioningState));
                });
            }
        }
        internal static bool CheckImageType(ComputeManagementClient computeClient, string imageName, ImageType imageType)
        {
            try
            {
                if (computeClient == null)
                {
                    return false;
                }
                else if (imageType == ImageType.OSImage)
                {
                    return string.Equals(
                        computeClient.VirtualMachineOSImages.Get(imageName).Name,
                        imageName,
                        StringComparison.OrdinalIgnoreCase);
                }
                else if (imageType == ImageType.VMImage)
                {
                    return computeClient.VirtualMachineVMImages.List().VMImages.Any(
                        e => string.Equals(
                            e.Name,
                            imageName,
                            StringComparison.OrdinalIgnoreCase));
                }
            }
            catch (CloudException e)
            {
                if (e.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }

            return false;
        }
        public async Task<IEnumerable<VirtualMachine>> ListVirtualMachinesAsync(string accessToken, string subscriptionId)
        {
            var credentials = new TokenCredentials(subscriptionId, accessToken);
            using (var client = new ComputeManagementClient(credentials))
            {
                var virtualMachinesResult = await client.VirtualMachines.ListAllAsync(null).ConfigureAwait(false);
                var all = virtualMachinesResult.VirtualMachines.Select(async (vm) =>
                {
                    var resourceGroupName = GetResourceGroup(vm.Id);
                    var response = await client.VirtualMachines.GetWithInstanceViewAsync(resourceGroupName, vm.Name);
                    var vmStatus = response.VirtualMachine.InstanceView.Statuses.Where(p => p.Code.ToLower().StartsWith("powerstate/")).FirstOrDefault();
                    return new VirtualMachine
                    {
                        SubscriptionId = subscriptionId,
                        ResourceGroup = resourceGroupName,
                        Name = vm.Name,
                        PowerState = GetVirtualMachinePowerState(vmStatus?.Code.ToLower() ?? VirtualMachinePowerState.Unknown.ToString())
                    };
                });

                return await Task.WhenAll(all.ToList());
            }
        }
Exemple #5
0
        public async Task <IHttpActionResult> Get()
        {
            // Will throw if more than one record exists with 'Selected = 1' (reason: by design)
            var mancert = await _sql.QueryAsync <ManagementCertificate>("SELECT * FROM ManagementCertificates WHERE Selected = 1").ContinueWith(a => a.Result.SingleOrDefault());

            if (mancert == null)
            {
                // TODO: Inform user no certs exist
                return(Ok(new
                {
                    Nodes = new List <Node>(),
                    NodeDeployments = new List <NodeDeployment>(),
                    NodeInstances = new List <NodeInstance>()
                }));
            }

            var certbytes = Convert.FromBase64String(mancert.Certificate);
            var cert      = new X509Certificate2(certbytes);

            var creds = new CertificateCloudCredentials(mancert.SubscriptionId, cert);
            var cmc   = new ComputeManagementClient(creds);

            // ----

            var nodes           = new List <Node>();
            var nodeDeployments = new List <NodeDeployment>();
            var nodeInstances   = new List <NodeInstance>();

            var slots = Enum.GetValues(typeof(DeploymentSlot)).Cast <DeploymentSlot>().ToArray(); //.OrderByDescending(x => x).ToList();

            var hostedServices = await cmc.HostedServices.ListAsync();

            foreach (var hostedService in hostedServices.Where(a => a.ServiceName.ToLower().Contains("blazedsp-node")))
            {
                nodes.Add(new Node
                {
                    Id              = hostedService.ServiceName,
                    Label           = hostedService.Properties.Label,
                    Location        = hostedService.Properties.Location,
                    Status          = hostedService.Properties.Status,
                    NodeDeployments = new List <string>()
                });

                DeploymentGetResponse deployment = null;

                foreach (var slot in slots)
                {
                    try
                    {
                        deployment = await cmc.Deployments.GetBySlotAsync(hostedService.ServiceName, slot);
                    }
                    catch (CloudException ce)
                    {
                        if (!ce.Message.Contains("No deployments were found"))
                        {
                            throw new NotImplementedException(ce.Message, ce);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new NotImplementedException(ex.Message, ex);
                    }

                    if (deployment == null)
                    {
                        var guid = Guid.NewGuid().ToString();

                        nodeDeployments.Add(new NodeDeployment
                        {
                            Id             = guid,
                            DeploymentSlot = slot
                        });

                        nodes.Single(a => a.Id == hostedService.ServiceName).NodeDeployments.Add(guid);

                        continue;
                    }

                    var guids = new List <string>();
                    foreach (var instance in deployment.RoleInstances)
                    {
                        var guid = Guid.NewGuid().ToString();
                        guids.Add(guid);
                        nodeInstances.Add(new NodeInstance
                        {
                            Id           = guid,
                            Name         = instance.InstanceName,
                            Size         = instance.InstanceSize,
                            StateDetails = instance.InstanceStateDetails,
                            Status       = instance.InstanceStatus,
                            PowerState   = instance.PowerState,
                            RoleName     = instance.RoleName
                        });
                    }

                    nodeDeployments.Add(new NodeDeployment
                    {
                        Id               = deployment.PrivateId,
                        Name             = deployment.Name,
                        Label            = deployment.Label,
                        DeploymentSlot   = deployment.DeploymentSlot,
                        SdkVersion       = deployment.SdkVersion,
                        Status           = deployment.Status,
                        CreatedTime      = deployment.CreatedTime,
                        LastModifiedTime = deployment.LastModifiedTime,
                        NodeInstances    = guids
                    });

                    nodes.Single(a => a.Id == hostedService.ServiceName).NodeDeployments.Add(deployment.PrivateId);
                }
            }

            return(Ok(new
            {
                nodes,
                nodeDeployments,
                nodeInstances
            }));
        }
 public async Task<bool> DeallocateVirtualMachineAsync(string accessToken, string subscriptionId, string resourceGroupName, string virtualMachineName)
 {
     var credentials = new TokenCredentials(subscriptionId, accessToken);
     using (var client = new ComputeManagementClient(credentials))
     {
         var status = await client.VirtualMachines.DeallocateAsync(resourceGroupName, virtualMachineName).ConfigureAwait(false);
         return status.Status != Microsoft.Azure.Management.Compute.Models.ComputeOperationStatus.Failed;
     }
 }
Exemple #7
0
        public void TestExtImgListVersionsFilters()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                ComputeManagementClient _pirClient =
                    ComputeManagementTestUtilities.GetComputeManagementClient(context,
                                                                              new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                // Filter: startswith - Positive Test
                parameters.FilterExpression = null;
                var extImages = _pirClient.VirtualMachineExtensionImages.ListVersions(
                    parameters.Location,
                    parameters.PublisherName,
                    parameters.Type);
                Assert.True(extImages.Count > 0);

                string ver   = extImages.First().Name;
                var    query = new Microsoft.Rest.Azure.OData.ODataQuery <Microsoft.Azure.Management.Compute.Models.VirtualMachineExtensionImage>();

                query.SetFilter(f => f.Name.StartsWith(ver));
                parameters.FilterExpression = "$filter=startswith(name,'" + ver + "')";
                var vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions(
                    parameters.Location,
                    parameters.PublisherName,
                    parameters.Type,
                    query);
                Assert.True(vmextimg.Count > 0);
                Assert.True(vmextimg.Count(vmi => vmi.Name == "2.0") != 0);

                // Filter: startswith - Negative Test
                query.SetFilter(f => f.Name.StartsWith("1.0"));
                parameters.FilterExpression = "$filter=startswith(name,'1.0')";
                vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions(
                    parameters.Location,
                    parameters.PublisherName,
                    parameters.Type,
                    query);
                Assert.True(vmextimg.Count == 0);
                Assert.True(vmextimg.Count(vmi => vmi.Name == "2.0") == 0);

                // Filter: top - Positive Test
                query.Filter = null;
                query.Top    = 1;
                parameters.FilterExpression = "$top=1";
                vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions(
                    parameters.Location,
                    parameters.PublisherName,
                    parameters.Type,
                    query);
                Assert.True(vmextimg.Count == 1);
                Assert.True(vmextimg.Count(vmi => vmi.Name == "2.0") != 0);

                // Filter: top - Negative Test
                query.Top = 0;
                parameters.FilterExpression = "$top=0";
                vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions(
                    parameters.Location,
                    parameters.PublisherName,
                    parameters.Type,
                    query);
                Assert.True(vmextimg.Count == 0);
            }
        }
Exemple #8
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroupName,
            string location,
            string vmName)
        {
            var computeClient          = new ComputeManagementClient(subscriptionId, new DefaultAzureCredential());
            var networkClient          = new NetworkManagementClient(subscriptionId, new DefaultAzureCredential());
            var virtualNetworksClient  = networkClient.VirtualNetworks;
            var networkInterfaceClient = networkClient.NetworkInterfaces;
            var publicIpAddressClient  = networkClient.PublicIPAddresses;
            var availabilitySetsClient = computeClient.AvailabilitySets;
            var virtualMachinesClient  = computeClient.VirtualMachines;

            // Create AvailabilitySet
            Console.WriteLine("--------Start create AvailabilitySet--------");
            var availabilitySet = new AvailabilitySet(location)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount  = 2,
                Sku = new Azure.ResourceManager.Compute.Models.Sku()
                {
                    Name = "Aligned"
                }
            };

            availabilitySet = await availabilitySetsClient.CreateOrUpdateAsync(resourceGroupName, vmName + "_aSet", availabilitySet);

            // Create IP Address
            Console.WriteLine("--------Start create IP Address--------");
            var ipAddress = new PublicIPAddress()
            {
                PublicIPAddressVersion   = Azure.ResourceManager.Network.Models.IPVersion.IPv4,
                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                Location = location,
            };

            ipAddress = await publicIpAddressClient.StartCreateOrUpdate(resourceGroupName, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            Console.WriteLine("--------Start create VNet--------");
            var vnet = new VirtualNetwork()
            {
                Location     = location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = "mySubnet",
                        AddressPrefix = "10.0.0.0/24",
                    }
                },
            };

            vnet = await virtualNetworksClient
                   .StartCreateOrUpdate(resourceGroupName, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network Interface
            Console.WriteLine("--------Start create Network Interface--------");
            var nic = new NetworkInterface()
            {
                Location         = location,
                IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name    = "Primary",
                        Primary = true,
                        Subnet  = new Subnet()
                        {
                            Id = vnet.Subnets.First().Id
                        },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        PublicIPAddress           = new PublicIPAddress()
                        {
                            Id = ipAddress.Id
                        }
                    }
                }
            };

            nic = await networkInterfaceClient
                  .StartCreateOrUpdate(resourceGroupName, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            // Create VM
            Console.WriteLine("--------Start create VM--------");
            var vm = new VirtualMachine(location)
            {
                NetworkProfile = new Azure.ResourceManager.Compute.Models.NetworkProfile {
                    NetworkInterfaces = new[] { new NetworkInterfaceReference()
                                                {
                                                    Id = nic.Id
                                                } }
                },
                OsProfile = new OSProfile
                {
                    ComputerName       = vmName,
                    AdminUsername      = Program.AdminUsername,
                    AdminPassword      = Program.AdminPassword,
                    LinuxConfiguration = new LinuxConfiguration {
                        DisablePasswordAuthentication = false, ProvisionVMAgent = true
                    }
                },
                StorageProfile = new StorageProfile()
                {
                    ImageReference = new ImageReference()
                    {
                        Offer     = "UbuntuServer",
                        Publisher = "Canonical",
                        Sku       = "18.04-LTS",
                        Version   = "latest"
                    },
                    DataDisks = new List <DataDisk>()
                },
                HardwareProfile = new HardwareProfile()
                {
                    VmSize = VirtualMachineSizeTypes.StandardB1Ms
                },
                AvailabilitySet = new Azure.ResourceManager.Compute.Models.SubResource()
                {
                    Id = availabilitySet.Id
                }
            };

            var operation = await virtualMachinesClient.StartCreateOrUpdateAsync(resourceGroupName, vmName, vm);

            var result = (await operation.WaitForCompletionAsync()).Value;

            Console.WriteLine("VM ID: " + result.Id);
            Console.WriteLine("--------Done create VM--------");
        }
Exemple #9
0
        public void CreateVirtualMachine(string virtualMachineName, AzureVmSize size, string ipName, bool startVm = true)
        {
            azureLogin.Authenticate();
            using (var computeManagementClient = new ComputeManagementClient(azureLogin.Credentials))
            {
                var osdiskName = virtualMachineName + "_osdisk";

                var vm = new VirtualMachine()
                {
                    Name = virtualMachineName,
                    Location = demo.Location,
                    OSProfile = new OSProfile()
                    {
                        AdminUsername = demo.VmAdminUserName,
                        AdminPassword = demo.VmAdminPassword,
                        ComputerName = virtualMachineName,
                        WindowsConfiguration = new WindowsConfiguration()
                        {
                            EnableAutomaticUpdates = true,
                            ProvisionVMAgent = true,
                        },
                    },
                    HardwareProfile = new HardwareProfile()
                    {
                        VirtualMachineSize = size
                    },
                    NetworkProfile = new NetworkProfile()
                    {
                        NetworkInterfaces = new List<NetworkInterfaceReference>()
                        {
                            new NetworkInterfaceReference
                            {
                                ReferenceUri = GetNicId(ipName).Id,
                            },
                        },
                    },
                    StorageProfile = new StorageProfile()
                    {
                        ImageReference = new ImageReference()
                        {
                            Publisher = "MicrosoftWindowsServer",
                            Offer = "WindowsServer",
                            Sku = "2012-R2-Datacenter",
                            Version = "latest",
                        },
                        OSDisk = new OSDisk
                        {
                            Name = osdiskName,
                            CreateOption = "FromImage",
                            Caching = "ReadWrite",
                            VirtualHardDisk = new VirtualHardDisk()
                            {
                                Uri = string.Format("http://{0}.blob.core.windows.net/vhds/{1}.vhd", demo.Storage, osdiskName),
                            },
                        },
                    },
                };

                HandleResult("Create VM", () => computeManagementClient.VirtualMachines.CreateOrUpdate(demo.Group, vm));

                var vmInstance = HandleResult("Get VM instance " + virtualMachineName,
                    () => computeManagementClient.VirtualMachines.GetWithInstanceView(demo.Group, virtualMachineName),
                    t => t.VirtualMachine.ProvisioningState);
                var stat = vmInstance.VirtualMachine.InstanceView.Statuses.FirstOrDefault(s => s.Code.StartsWith("PowerState"));
                bool vmStarted = stat != null && stat.DisplayStatus == "VM running";

                if (startVm && !vmStarted)
                {
                    StartVirtualMachine(virtualMachineName);
                }
            }
        }
Exemple #10
0
        public void Instantiate(string className)
        {
            try
            {
                using (UndoContext context = UndoContext.Current)
                {
                    context.Start(className, "FixtureSetup");

                    this.managementClient  = this.GetManagementClient();
                    this.computeMgmtClient = this.GetComputeManagementClient();
                    this.storageMgmtClient = this.GetStorageManagementClient();

                    NewStorageAccountName  = TestUtilities.GenerateName();
                    NewServiceName         = TestUtilities.GenerateName();
                    DeploymentNameTemplate = TestUtilities.GenerateName();
                    this.DefaultLocation   = managementClient.GetDefaultLocation("Compute", "Storage");
                    // create a storage account
                    var storageAccountResult = storageMgmtClient.StorageAccounts.Create(
                        new StorageAccountCreateParameters
                    {
                        Location    = this.DefaultLocation,
                        Name        = NewStorageAccountName,
                        AccountType = "Standard_LRS"
                    });

                    // get the storage account
                    var keyResult = storageMgmtClient.StorageAccounts.GetKeys(NewStorageAccountName);

                    // build the connection string
                    _storageAccountConnectionString = string.Format(_storageConnectionStringTemplate,
                                                                    NewStorageAccountName, keyResult.PrimaryKey);

                    _blobUri = StorageTestUtilities.UploadFileToBlobStorage(NewStorageAccountName,
                                                                            _testDeploymentsBlobStorageContainerName, @"SampleService\SMNetTestAppProject.cspkg");
                    // upload the compute service package file
                    // persist the XML of the configuration file to a variable
                    var configXml = File.ReadAllText(@"SampleService\ServiceConfiguration.Cloud.cscfg");

                    // create a hosted service for the tests to use
                    var result = computeMgmtClient.HostedServices.Create(new HostedServiceCreateParameters
                    {
                        Location    = this.DefaultLocation,
                        Label       = NewServiceName,
                        ServiceName = NewServiceName
                    });

                    // assert that the call worked
                    Assert.Equal(result.StatusCode, HttpStatusCode.Created);

                    // Get an extension for our deployment
                    computeMgmtClient.HostedServices.AddExtension(
                        NewServiceName,
                        new HostedServiceAddExtensionParameters
                    {
                        Id   = "RDPExtensionTest",
                        Type = "RDP",
                        ProviderNamespace   = "Microsoft.Windows.Azure.Extensions",
                        PublicConfiguration =
                            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><PublicConfig><UserName>WilliamGatesIII</UserName><Expiration>2020-11-20</Expiration></PublicConfig>",
                        PrivateConfiguration =
                            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><PrivateConfig><Password>WindowsAzure1277!</Password></PrivateConfig>",
                        Version = "*"
                    });
                    ExtensionConfiguration extensionConfig = new ExtensionConfiguration();
                    extensionConfig.AllRoles.Add(new ExtensionConfiguration.Extension()
                    {
                        Id = "RDPExtensionTest"
                    });
                    _serviceDeploymentName = string.Format(DeploymentNameTemplate, NewServiceName);

                    // create the hosted service deployment
                    var deploymentResult = computeMgmtClient.Deployments.Create(NewServiceName,
                                                                                DeploymentSlot.Production,
                                                                                new DeploymentCreateParameters
                    {
                        Configuration          = configXml,
                        Name                   = _serviceDeploymentName,
                        Label                  = _serviceDeploymentName,
                        StartDeployment        = true,
                        ExtensionConfiguration = extensionConfig,
                        PackageUri             = _blobUri
                    });

                    // assert that nothing went wrong
                    var error = deploymentResult.Error;
                    Assert.True(error == null, "Unexpected error: " + (error == null ? "" : error.Message));
                }
            }
            catch (Exception)
            {
                Cleanup();
                throw;
            }
            finally
            {
                TestUtilities.EndTest();
            }
        }
        public VirtualMachine CreateVirtualMachine(TokenCredentials credential, string groupName, string subscriptionId, string location, string nicName, string avsetName, string storageName, string adminName, string adminPassword, string vmName)
        {
            var networkManagementClient = new NetworkManagementClient(credential)
            {
                SubscriptionId = subscriptionId
            };
            var nic = networkManagementClient.NetworkInterfaces.Get(groupName, nicName);

            var computeManagementClient = new ComputeManagementClient(credential);

            computeManagementClient.SubscriptionId = subscriptionId;
            var avSet = computeManagementClient.AvailabilitySets.Get(groupName, avsetName);

            Console.WriteLine("Creating the virtual machine...");
            return(computeManagementClient.VirtualMachines.CreateOrUpdate(
                       groupName,
                       vmName,
                       new VirtualMachine
            {
                Location = location,
                AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource
                {
                    Id = avSet.Id
                },
                HardwareProfile = new HardwareProfile
                {
                    VmSize = "Standard_A0"
                },
                OsProfile = new OSProfile
                {
                    AdminUsername = adminName,
                    AdminPassword = adminPassword,
                    ComputerName = vmName,
                    WindowsConfiguration = new WindowsConfiguration
                    {
                        ProvisionVMAgent = true
                    }
                },
                NetworkProfile = new NetworkProfile
                {
                    NetworkInterfaces = new List <NetworkInterfaceReference>
                    {
                        new NetworkInterfaceReference {
                            Id = nic.Id
                        }
                    }
                },
                StorageProfile = new StorageProfile
                {
                    ImageReference = new ImageReference
                    {
                        Publisher = "MicrosoftWindowsServer",
                        Offer = "WindowsServer",
                        Sku = "2012-R2-Datacenter",
                        Version = "latest"
                    },
                    OsDisk = new OSDisk
                    {
                        Name = "mytestod1",
                        CreateOption = DiskCreateOptionTypes.FromImage,
                        Vhd = new VirtualHardDisk
                        {
                            Uri = "http://" + storageName + ".blob.core.windows.net/vhds/mytestod1.vhd"
                        }
                    }
                }
            }
                       ));
        }
        public override void Execute()
        {
            // Note that we need to create 3 clients from this scenario; customer must know which client contains which resource
            var rmClient      = new ResourcesManagementClient(Context.SubscriptionId, Context.Credential);
            var computeClient = new ComputeManagementClient(Context.SubscriptionId, Context.Credential);
            var networkClient = new NetworkManagementClient(Context.SubscriptionId, Context.Credential);

            // Create Resource Group
            Console.WriteLine($"--------Start create group {Context.RgName}--------");

            // note that some resources use the StartCreate and some use Create - this can make it a bit difficult to handle resource creation generically
            var resourceGroup = rmClient.ResourceGroups.CreateOrUpdate(Context.RgName, new ResourceGroup(Context.Loc)).Value;

            CleanUp.Add(resourceGroup.Id);

            // Create AvailabilitySet
            Console.WriteLine("--------Start create AvailabilitySet--------");
            var aset = new AvailabilitySet(Context.Loc)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount  = 2,
                Sku = new Azure.ResourceManager.Compute.Models.Sku()
                {
                    Name = "Aligned"
                }
            };

            aset = computeClient.AvailabilitySets.CreateOrUpdate(Context.RgName, Context.VmName + "_aSet", aset).Value;

            // Create VNet
            Console.WriteLine("--------Start create VNet--------");
            string vnetName = Context.VmName + "_vnet";
            var    vnet     = new VirtualNetwork()
            {
                Location     = Context.Loc,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16"
                    }
                }
            };

            vnet = networkClient.VirtualNetworks.StartCreateOrUpdate(Context.RgName, vnetName, vnet).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            //create subnet
            Console.WriteLine("--------Start create Subnet--------");
            var nsg = new NetworkSecurityGroup {
                Location = Context.Loc
            };

            nsg.SecurityRules = new List <SecurityRule> {
                new SecurityRule
                {
                    Name                     = "Port80",
                    Priority                 = 1001,
                    Protocol                 = SecurityRuleProtocol.Tcp,
                    Access                   = SecurityRuleAccess.Allow,
                    Direction                = SecurityRuleDirection.Inbound,
                    SourcePortRange          = "*",
                    SourceAddressPrefix      = "*",
                    DestinationPortRange     = "80",
                    DestinationAddressPrefix = "*",
                    Description              = $"Port_80"
                }
            };

            nsg = networkClient.NetworkSecurityGroups.StartCreateOrUpdate(Context.RgName, Context.NsgName, nsg).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;
            var subnet = new Subnet()
            {
                Name                 = Context.SubnetName,
                AddressPrefix        = "10.0.0.0/24",
                NetworkSecurityGroup = nsg
            };

            subnet = networkClient.Subnets.StartCreateOrUpdate(Context.RgName, vnetName, Context.SubnetName, subnet).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            // Create IP Address
            Console.WriteLine("--------Start create IP Address--------");
            var ipAddress = new PublicIPAddress()
            {
                PublicIPAddressVersion   = Azure.ResourceManager.Network.Models.IPVersion.IPv4.ToString(),
                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                Location = Context.Loc,
            };

            ipAddress = networkClient.PublicIPAddresses.StartCreateOrUpdate(Context.RgName, $"{Context.VmName}_ip", ipAddress).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            // Create Network Interface
            Console.WriteLine("--------Start create Network Interface--------");
            var nic = new NetworkInterface()
            {
                Location         = Context.Loc,
                IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name    = "Primary",
                        Primary = true,
                        Subnet  = new Subnet()
                        {
                            Id = subnet.Id
                        },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        PublicIPAddress           = new PublicIPAddress()
                        {
                            Id = ipAddress.Id
                        }
                    }
                }
            };

            nic = networkClient.NetworkInterfaces.StartCreateOrUpdate(Context.RgName, $"{Context.VmName}_nic", nic).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            // Create VM
            Console.WriteLine("--------Start create VM--------");
            var vm = new VirtualMachine(Context.Loc)
            {
                NetworkProfile = new Azure.ResourceManager.Compute.Models.NetworkProfile {
                    NetworkInterfaces = new[] { new NetworkInterfaceReference()
                                                {
                                                    Id = nic.Id
                                                } }
                },
                OsProfile = new OSProfile
                {
                    ComputerName         = Context.VmName,
                    AdminUsername        = "******",
                    AdminPassword        = "******",
                    WindowsConfiguration = new WindowsConfiguration {
                        TimeZone = "Pacific Standard Time", ProvisionVMAgent = true
                    }
                },
                StorageProfile = new StorageProfile()
                {
                    ImageReference = new ImageReference()
                    {
                        Offer     = "WindowsServer",
                        Publisher = "MicrosoftWindowsServer",
                        Sku       = "2019-Datacenter",
                        Version   = "latest"
                    },
                    DataDisks = new List <DataDisk>()
                },
                HardwareProfile = new HardwareProfile()
                {
                    VmSize = VirtualMachineSizeTypes.StandardB1Ms
                },
                // The namespace-qualified type for SubResource is needed because all 3 libraries define an identical SubResource type. In the proposed model, the common type would be part of the core library
                AvailabilitySet = new Azure.ResourceManager.Compute.Models.SubResource()
                {
                    Id = aset.Id
                }
            };

            vm = computeClient.VirtualMachines.StartCreateOrUpdate(Context.RgName, Context.VmName, vm).WaitForCompletionAsync().ConfigureAwait(false).GetAwaiter().GetResult().Value;

            Console.WriteLine("VM ID: " + vm.Id);
            Console.WriteLine("--------Done create VM--------");
        }
        public void TestVMImageListFilters()
        {
            using (var context = UndoContext.Current)
            {
                context.Start();
                ComputeManagementClient _pirClient =
                    ComputeManagementTestUtilities.GetComputeManagementClient(new RDFETestEnvironmentFactory(),
                                                                              new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                VirtualMachineImageListParameters listParametersWithFilter = new VirtualMachineImageListParameters()
                {
                    Location      = listParameters.Location,
                    PublisherName = listParameters.PublisherName,
                    Offer         = listParameters.Offer,
                    Skus          = listParameters.Skus,
                };

                // Filter: top - Negative Test
                listParametersWithFilter.FilterExpression = "$top=0";
                var vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 0);

                // Filter: top - Positive Test
                listParametersWithFilter.FilterExpression = "$top=1";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 1);

                // Filter: top - Positive Test
                listParametersWithFilter.FilterExpression = "$top=2";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 2);
                Assert.True(vmimages.Resources.Count(vmi => vmi.Name == "1.0.0") != 0);
                Assert.True(vmimages.Resources.Count(vmi => vmi.Name == "1.1.0") != 0);

                // Filter: orderby - Positive Test
                listParametersWithFilter.FilterExpression = "$orderby=name desc";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 2);
                Assert.True(vmimages.Resources[0].Name == "1.1.0");
                Assert.True(vmimages.Resources[1].Name == "1.0.0");

                // Filter: orderby - Positive Test
                listParametersWithFilter.FilterExpression = "$orderby=name asc";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 2);
                Assert.True(vmimages.Resources[0].Name == "1.0.0");
                Assert.True(vmimages.Resources[1].Name == "1.1.0");

                // Filter: top orderby - Positive Test
                listParametersWithFilter.FilterExpression = "$top=1&$orderby=name desc";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 1);
                Assert.True(vmimages.Resources[0].Name == "1.1.0");

                // Filter: top orderby - Positive Test
                listParametersWithFilter.FilterExpression = "$top=1&$orderby=name asc";
                vmimages = _pirClient.VirtualMachineImages.List(listParametersWithFilter);
                Assert.True(vmimages.Resources.Count == 1);
                Assert.True(vmimages.Resources[0].Name == "1.0.0");
            }
        }
Exemple #14
0
        public static async Task <VirtualMachine> CreateVirtualMachineAsync(TokenCredentials credential, string groupName, string subscriptionId, string location, string nicName, string avsetName, string storageName, string adminName, string adminPassword, string vmName)
        {
            var networkManagementClient = new NetworkManagementClient(credential)
            {
                SubscriptionId = subscriptionId,
                BaseUri        = new Uri("https://management.chinacloudapi.cn")
            };
            var computeManagementClient = new ComputeManagementClient(credential)
            {
                SubscriptionId = subscriptionId,
                BaseUri        = new Uri("https://management.chinacloudapi.cn")
            };

            var nic = await networkManagementClient.NetworkInterfaces.GetAsync(
                groupName,
                nicName);

            var avSet = await computeManagementClient.AvailabilitySets.GetAsync(
                groupName,
                avsetName);

            Console.WriteLine("Creating the virtual machine...");
            return(await computeManagementClient.VirtualMachines.CreateOrUpdateAsync(
                       groupName,
                       vmName,
                       new VirtualMachine
            {
                Location = location,
                AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource
                {
                    Id = avSet.Id
                },
                HardwareProfile = new HardwareProfile
                {
                    VmSize = "Standard_A0"
                },
                OsProfile = new OSProfile
                {
                    AdminUsername = adminName,
                    AdminPassword = adminPassword,
                    ComputerName = vmName,
                    WindowsConfiguration = new WindowsConfiguration
                    {
                        ProvisionVMAgent = true
                    }
                },
                NetworkProfile = new NetworkProfile
                {
                    NetworkInterfaces = new List <NetworkInterfaceReference>
                    {
                        new NetworkInterfaceReference {
                            Id = nic.Id
                        }
                    }
                },
                StorageProfile = new StorageProfile
                {
                    ImageReference = new ImageReference
                    {
                        Publisher = "MicrosoftWindowsServer",
                        Offer = "WindowsServer",
                        Sku = "2012-R2-Datacenter",
                        Version = "latest"
                    },
                    OsDisk = new OSDisk
                    {
                        Name = "mytestod1",
                        CreateOption = DiskCreateOptionTypes.FromImage,
                        Vhd = new VirtualHardDisk
                        {
                            Uri = "http://" + storageName + ".blob.core.windows.net/vhds/mytestod1.vhd"
                        }
                    },
                    DataDisks = new List <DataDisk> {
                        new DataDisk()
                        {
                            Name = "",
                            DiskSizeGB = 100,
                            ManagedDisk = new ManagedDiskParameters(),
                            Caching = CachingTypes.ReadWrite,
                            CreateOption = DiskCreateOptionTypes.Attach,
                            Image = new VirtualHardDisk()
                            {
                                Uri = ""
                            },
                            Lun = 0,
                            Vhd = new VirtualHardDisk()
                            {
                                Uri = ""
                            }
                        }
                    }
                }
            }
                       ));
        }
Exemple #15
0
        static async Task Main(string[] args)
        {
            var creds = new LoginHelper();

            m_subId           = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
            m_ResourcesClient = new ResourceManagementClient(creds);
            m_NrpClient       = new NetworkManagementClient(creds);
            m_CrpClient       = new ComputeManagementClient(creds);
            m_SrpClient       = new StorageManagementClient(creds);
            m_ResourcesClient.SubscriptionId = m_subId;
            m_NrpClient.SubscriptionId       = m_subId;
            m_CrpClient.SubscriptionId       = m_subId;
            m_SrpClient.SubscriptionId       = m_subId;

            // Initialize variable names
            var    rgName              = "QuickStartRG";
            var    resourceGroup       = new ResourceGroup(m_location);
            var    csName              = "ContosoCS";
            string cloudServiceName    = "HelloWorldTest_WebRole";
            string publicIPAddressName = "contosoCSpip1";
            string vnetName            = "contosocsvnet1";
            string subnetName          = "contososubnet1";
            string dnsName             = "contosodns1";
            string lbName              = "contosolb1";
            string lbfeName            = "contosolbfe1";
            string roleInstanceSize    = "Standard_D2_v2";

            // Create Resource Group
            Console.WriteLine("--------Start create group--------");
            var resourceGroups = m_ResourcesClient.ResourceGroups;

            resourceGroup = await resourceGroups.CreateOrUpdateAsync(rgName, resourceGroup);

            Console.WriteLine("--------Finish create group--------");

            // Create Resource Group
            Console.WriteLine("--------Creating Virtual Network--------");
            CreateVirtualNetwork(rgName, vnetName, subnetName);
            Console.WriteLine("--------Finish Virtual Network--------");

            Console.WriteLine("--------Creating Public IP--------");
            PublicIPAddress publicIPAddress = CreatePublicIP(publicIPAddressName, rgName, dnsName);

            Console.WriteLine("--------Finish Public IP--------");

            // Define Configurations to add roles
            Dictionary <string, RoleConfiguration> roleNameToPropertiesMapping = new Dictionary <string, RoleConfiguration>
            {
                { "HelloWorldTest1", new RoleConfiguration {
                      InstanceCount = 1, RoleInstanceSize = roleInstanceSize
                  } }
            };

            ///
            /// Create: Create 1 WebRole, and RDP Extension.
            ///

            string rdpExtensionPublicConfig = "<PublicConfig>" +
                                              "<UserName>adminRdpTest</UserName>" +
                                              "<Expiration>2021-10-27T23:59:59</Expiration>" +
                                              "</PublicConfig>";
            string rdpExtensionPrivateConfig = "<PrivateConfig>" +
                                               "<Password>VsmrdpTest!</Password>" +
                                               "</PrivateConfig>";

            Extension rdpExtension = CreateExtension("RDPExtension", "Microsoft.Windows.Azure.Extensions", "RDP", "1.2.1", autoUpgrade: true,
                                                     publicConfig: rdpExtensionPublicConfig,
                                                     privateConfig: rdpExtensionPrivateConfig);

            // Generate Cloud Service Object
            CloudService cloudService = GenerateCloudServiceWithNetworkProfile(
                resourceGroupName: rgName,
                serviceName: cloudServiceName,
                cspkgSasUri: CreateCspkgSasUrl(rgName, WebRoleSasUri),
                roleNameToPropertiesMapping: roleNameToPropertiesMapping,
                publicIPAddressName: publicIPAddressName,
                vnetName: vnetName,
                subnetName: subnetName,
                lbName: lbName,
                lbFrontendName: lbfeName);

            // Add Extension Profile
            cloudService.Properties.ExtensionProfile = new CloudServiceExtensionProfile()
            {
                Extensions = new List <Extension>()
                {
                    rdpExtension
                }
            };

            // Create Cloud Service
            Console.WriteLine("--------Creating Cloud Service--------");
            CloudService getResponse = CreateCloudService_NoAsyncTracking(
                rgName,
                csName,
                cloudService);

            Console.WriteLine("--------Finish Cloud Service--------");

            Console.WriteLine(getResponse.ToString());

            //Delete resource group
            Console.WriteLine("--------Start delete group--------");
            await resourceGroups.DeleteAsync(rgName);

            Console.WriteLine("--------Finish delete group--------");
            Console.ReadKey();
        }
Exemple #16
0
 public ComputeManagementPaginators(ComputeManagementClient client)
 {
     this.client = client;
 }
Exemple #17
0
 public void StartVirtualMachine(string virtualMachineName)
 {
     azureLogin.Authenticate();
     using (var computeManagementClient = new ComputeManagementClient(azureLogin.Credentials))
     {
         HandleResult($"Start VM '{virtualMachineName}'", 
             () => computeManagementClient.VirtualMachines.Start(demo.Group, virtualMachineName));
     }
 }
        public static async Task CreateVirtualMachineAsync(
            TokenCredentials credential,
            string vmName,
            string groupName,
            string nicName,
            string avsetName,
            string storageName,
            string adminName,
            string adminPassword,
            string subscriptionId,
            string location)
        {
            var networkManagementClient = new NetworkManagementClient(credential);

            networkManagementClient.SubscriptionId = subscriptionId;
            var nic = await networkManagementClient.NetworkInterfaces.GetAsync(groupName, nicName);

            var computeManagementClient = new ComputeManagementClient(credential);

            computeManagementClient.SubscriptionId = subscriptionId;
            var avSet = await computeManagementClient.AvailabilitySets.GetAsync(groupName, avsetName);


            try
            {
                var sampleVM = await computeManagementClient.VirtualMachines.GetAsync("hbbu-res-group", "hbbu-vm");

                Console.WriteLine($"{nameof(sampleVM.Name)}={sampleVM.Name}");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"{ex}");
            }

            var vmSizes = await computeManagementClient.VirtualMachineSizes.ListAsync(location);

            foreach (var vmSize in vmSizes)
            {
                Console.WriteLine($"{nameof(vmSize.Name)}={vmSize.Name}");
                Console.WriteLine($"{nameof(vmSize.MaxDataDiskCount)}={vmSize.MaxDataDiskCount}");
                Console.WriteLine($"{nameof(vmSize.MemoryInMB)}={vmSize.MemoryInMB}");
                Console.WriteLine($"{nameof(vmSize.NumberOfCores)}={vmSize.NumberOfCores}");
                Console.WriteLine($"{nameof(vmSize.OsDiskSizeInMB)}={vmSize.OsDiskSizeInMB}");
                Console.WriteLine($"{nameof(vmSize.ResourceDiskSizeInMB)}={vmSize.ResourceDiskSizeInMB}");
                Console.WriteLine();
            }



            Console.WriteLine("Creating the virtual machine...");

            bool bCreateNewDataDisk = true;
            bool bAttcheExisting    = true;
            var  vm = await computeManagementClient.VirtualMachines.CreateOrUpdateAsync(
                groupName,
                vmName,
                new VirtualMachine
            {
                Location        = location,
                AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource
                {
                    Id = avSet.Id
                },
                HardwareProfile = new HardwareProfile
                {
                    //VmSize = "Standard_A0"
                    VmSize = "Standard_DS1_V2"
                },
                OsProfile = new OSProfile
                {
                    AdminUsername        = adminName,
                    AdminPassword        = adminPassword,
                    ComputerName         = vmName,
                    WindowsConfiguration = new WindowsConfiguration
                    {
                        ProvisionVMAgent = true
                    }
                },
                NetworkProfile = new NetworkProfile
                {
                    NetworkInterfaces = new List <NetworkInterfaceReference>
                    {
                        new NetworkInterfaceReference {
                            Id = nic.Id
                        }
                    }
                },

                StorageProfile = new StorageProfile
                {
                    ImageReference = new ImageReference
                    {
                        Publisher = "MicrosoftWindowsServer",
                        Offer     = "WindowsServer",
                        Sku       = "2012-R2-Datacenter",
                        Version   = "latest"
                    },
                    OsDisk = new OSDisk
                    {
                        Name         = "mytestod1",
                        CreateOption = DiskCreateOptionTypes.FromImage,
                        Vhd          = new VirtualHardDisk
                        {
                            Uri = "https://" + storageName + ".blob.core.windows.net/vhds/mytestod1.vhd"
                        }
                    },
                    DataDisks = bCreateNewDataDisk? new List <DataDisk>()
                    {
                        new DataDisk()
                        {
                            Caching      = CachingTypes.ReadOnly,
                            CreateOption = bAttcheExisting? DiskCreateOptionTypes.Attach : DiskCreateOptionTypes.Empty,
                            DiskSizeGB   = 1023,
                            Lun          = 0,
                            Name         = "sssDataDisk0",
                            Vhd          = new VirtualHardDisk()
                            {
                                Uri = "https://" + storageName + ".blob.core.windows.net/vhds/sssDataDisk0.vhd"
                            }
                        },


                        new DataDisk()
                        {
                            Caching      = CachingTypes.ReadOnly,
                            CreateOption = bAttcheExisting? DiskCreateOptionTypes.Attach : DiskCreateOptionTypes.Empty,
                            DiskSizeGB   = 1023,
                            Lun          = 1,
                            Name         = "sssDataDisk1",
                            Vhd          = new VirtualHardDisk()
                            {
                                Uri = "https://" + storageName + ".blob.core.windows.net/vhds/sssDataDisk1.vhd"
                            }
                        }
                    } :
                    new List <DataDisk>()
                }
            }
                );

            Console.WriteLine(vm.ProvisioningState);
        }
Exemple #19
0
 public void ResizeVirtualMachine(string virtualMachineName, AzureVmSize size)
 {
     azureLogin.Authenticate();
     using (var computeManagementClient = new ComputeManagementClient(azureLogin.Credentials))
     {
         var vm = new VirtualMachine()
         {
             Name = virtualMachineName,
             Location = demo.Location,
             HardwareProfile = new HardwareProfile()
             {
                 VirtualMachineSize = size,
             },
         };
         HandleResult($"Resize VM '{virtualMachineName}' to {size}", 
             () => computeManagementClient.VirtualMachines.CreateOrUpdate(demo.Group, vm));
     }
 }
        private void Initialize()
        {
            handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
            resourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(handler);
            computeClient = ComputeManagementTestUtilities.GetComputeManagementClient(handler);

            subId = computeClient.Credentials.SubscriptionId;
            location = ComputeManagementTestUtilities.DefaultLocation;

            resourceGroupName = TestUtilities.GenerateName(testPrefix);

            resourceGroup = resourcesClient.ResourceGroups.CreateOrUpdate(
                resourceGroupName,
                new ResourceGroup
                {
                    Location = location
                });
        }
Exemple #21
0
        /**
         * Azure Compute sample for managing virtual machines -
         *  - Create a virtual machine with managed OS Disk
         *  - Start a virtual machine
         *  - Stop a virtual machine
         *  - Restart a virtual machine
         *  - Update a virtual machine
         *    - Tag a virtual machine (there are many possible variations here)
         *    - Attach data disks
         *    - Detach data disks
         *  - List virtual machines
         *  - Delete a virtual machine.
         */
        public static async Task RunSample(TokenCredential credential)
        {
            var region         = "westcentralus";
            var windowsVmName  = Utilities.CreateRandomName("wVM");
            var linuxVmName    = Utilities.CreateRandomName("lVM");
            var rgName         = Utilities.CreateRandomName("rgCOMV");
            var userName       = "******";
            var password       = "******";
            var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");

            var networkManagementClient = new NetworkManagementClient(subscriptionId, credential);
            var virtualNetworks         = networkManagementClient.VirtualNetworks;
            var networkInterfaces       = networkManagementClient.NetworkInterfaces;
            var computeManagementClient = new ComputeManagementClient(subscriptionId, credential);
            var virtualMachines         = computeManagementClient.VirtualMachines;
            var disks = computeManagementClient.Disks;

            try
            {
                await ResourceGroupHelper.CreateOrUpdateResourceGroup(rgName, region);

                //=============================================================
                // Create a Windows virtual machine

                // Create a data disk to attach to VM
                //
                Utilities.Log("Creating a data disk");

                var dataDisk = new Disk(region)
                {
                    DiskSizeGB   = 50,
                    CreationData = new CreationData(DiskCreateOption.Empty)
                };
                dataDisk = await(await disks
                                 .StartCreateOrUpdateAsync(rgName, Utilities.CreateRandomName("dsk-"), dataDisk)).WaitForCompletionAsync();

                Utilities.Log("Created a data disk");

                // Create VNet
                //
                Utilities.Log("Creating a VNet");

                var vnet = new VirtualNetwork
                {
                    Location     = region,
                    AddressSpace = new AddressSpace {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16"
                        }
                    },
                    Subnets = new List <Subnet>
                    {
                        new Subnet
                        {
                            Name          = "mySubnet",
                            AddressPrefix = "10.0.0.0/28",
                        }
                    },
                };
                vnet = await virtualNetworks
                       .StartCreateOrUpdate(rgName, windowsVmName + "_vent", vnet).WaitForCompletionAsync();

                Utilities.Log("Created a VNet");

                // Create Network Interface
                //
                Utilities.Log("Creating a Network Interface");

                var nic = new NetworkInterface
                {
                    Location         = region,
                    IpConfigurations = new List <NetworkInterfaceIPConfiguration>
                    {
                        new NetworkInterfaceIPConfiguration
                        {
                            Name    = "Primary",
                            Primary = true,
                            Subnet  = new Subnet {
                                Id = vnet.Subnets.First().Id
                            },
                            PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        }
                    }
                };
                nic = await networkInterfaces
                      .StartCreateOrUpdate(rgName, windowsVmName + "_nic", nic).WaitForCompletionAsync();

                Utilities.Log("Created a Network Interface");

                var t1 = new DateTime();

                // Create VM
                //
                Utilities.Log("Creating a Windows VM");

                var windowsVM = new VirtualMachine(region)
                {
                    NetworkProfile = new Azure.ResourceManager.Compute.Models.NetworkProfile
                    {
                        NetworkInterfaces = new[]
                        {
                            new NetworkInterfaceReference {
                                Id = nic.Id
                            }
                        }
                    },
                    OsProfile = new OSProfile
                    {
                        ComputerName  = windowsVmName,
                        AdminUsername = userName,
                        AdminPassword = password,
                    },
                    StorageProfile = new StorageProfile
                    {
                        ImageReference = new ImageReference
                        {
                            Offer     = "WindowsServer",
                            Publisher = "MicrosoftWindowsServer",
                            Sku       = "2016-Datacenter",
                            Version   = "latest"
                        },
                        DataDisks = new List <DataDisk>
                        {
                            new DataDisk(0, DiskCreateOptionTypes.Empty)
                            {
                                DiskSizeGB = 10
                            },
                            new DataDisk(1, DiskCreateOptionTypes.Empty)
                            {
                                Name       = Utilities.CreateRandomName("dsk-"),
                                DiskSizeGB = 100,
                            },
                            new DataDisk(2, DiskCreateOptionTypes.Attach)
                            {
                                ManagedDisk = new ManagedDiskParameters()
                                {
                                    Id = dataDisk.Id
                                }
                            }
                        }
                    },
                    HardwareProfile = new HardwareProfile {
                        VmSize = VirtualMachineSizeTypes.StandardD3V2
                    },
                };

                windowsVM = (await(await virtualMachines
                                   .StartCreateOrUpdateAsync(rgName, windowsVmName, windowsVM)).WaitForCompletionAsync()).Value;

                var t2 = new DateTime();
                Utilities.Log($"Created VM: (took {(t2 - t1).TotalSeconds} seconds) " + windowsVM.Id);
                // Print virtual machine details
                Utilities.PrintVirtualMachine(windowsVM);

                //=============================================================
                // Update - Tag the virtual machine

                var update = new VirtualMachineUpdate
                {
                    Tags = new Dictionary <string, string>
                    {
                        { "who-rocks", "java" },
                        { "where", "on azure" }
                    }
                };

                windowsVM = await(await virtualMachines.StartUpdateAsync(rgName, windowsVmName, update)).WaitForCompletionAsync();

                Utilities.Log("Tagged VM: " + windowsVM.Id);

                //=============================================================
                // Update - Add data disk

                windowsVM.StorageProfile.DataDisks.Add(new DataDisk(3, DiskCreateOptionTypes.Empty)
                {
                    DiskSizeGB = 10
                });
                windowsVM = (await(await virtualMachines
                                   .StartCreateOrUpdateAsync(rgName, windowsVmName, windowsVM)).WaitForCompletionAsync()).Value;

                Utilities.Log("Added a data disk to VM" + windowsVM.Id);
                Utilities.PrintVirtualMachine(windowsVM);

                //=============================================================
                // Update - detach data disk
                var removeDisk = windowsVM.StorageProfile.DataDisks.First(x => x.Lun == 0);
                windowsVM.StorageProfile.DataDisks.Remove(removeDisk);
                windowsVM = (await(await virtualMachines
                                   .StartCreateOrUpdateAsync(rgName, windowsVmName, windowsVM)).WaitForCompletionAsync()).Value;

                Utilities.Log("Detached data disk at lun 0 from VM " + windowsVM.Id);

                //=============================================================
                // Restart the virtual machine

                Utilities.Log("Restarting VM: " + windowsVM.Id);
                await(await virtualMachines.StartRestartAsync(rgName, windowsVmName)).WaitForCompletionAsync();

                Utilities.Log("Restarted VM: " + windowsVM.Id);

                //=============================================================
                // Stop (powerOff) the virtual machine

                Utilities.Log("Powering OFF VM: " + windowsVM.Id);

                await(await virtualMachines.StartPowerOffAsync(rgName, windowsVmName)).WaitForCompletionAsync();

                Utilities.Log("Powered OFF VM: " + windowsVM.Id);

                //=============================================================
                // Create a Linux VM in the same virtual network

                Utilities.Log("Creating a Network Interface #2");

                var nic2 = new NetworkInterface
                {
                    Location         = region,
                    IpConfigurations = new List <NetworkInterfaceIPConfiguration>
                    {
                        new NetworkInterfaceIPConfiguration
                        {
                            Name    = "Primary",
                            Primary = true,
                            Subnet  = new Subnet {
                                Id = vnet.Subnets.First().Id
                            },
                            PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        }
                    }
                };
                nic2 = await networkInterfaces
                       .StartCreateOrUpdate(rgName, linuxVmName + "_nic", nic2).WaitForCompletionAsync();

                Utilities.Log("Created a Network Interface #2");

                Utilities.Log("Creating a Linux VM in the network");

                var linuxVM = new VirtualMachine(region)
                {
                    NetworkProfile = new Azure.ResourceManager.Compute.Models.NetworkProfile
                    {
                        NetworkInterfaces = new[]
                        {
                            new NetworkInterfaceReference {
                                Id = nic2.Id
                            }
                        }
                    },
                    OsProfile = new OSProfile
                    {
                        ComputerName       = linuxVmName,
                        AdminUsername      = userName,
                        AdminPassword      = password,
                        LinuxConfiguration = new LinuxConfiguration
                        {
                            DisablePasswordAuthentication = false,
                            ProvisionVMAgent = true
                        }
                    },
                    StorageProfile = new StorageProfile
                    {
                        ImageReference = new ImageReference
                        {
                            Offer     = "UbuntuServer",
                            Publisher = "Canonical",
                            Sku       = "18.04-LTS",
                            Version   = "latest"
                        },
                        DataDisks = new List <DataDisk>()
                    },
                    HardwareProfile = new HardwareProfile {
                        VmSize = VirtualMachineSizeTypes.StandardD3V2
                    },
                };

                linuxVM = await(await virtualMachines.StartCreateOrUpdateAsync(rgName, linuxVmName, linuxVM)).WaitForCompletionAsync();

                Utilities.Log("Created a Linux VM (in the same virtual network): " + linuxVM.Id);
                Utilities.PrintVirtualMachine(linuxVM);

                //=============================================================
                // List virtual machines in the resource group

                Utilities.Log("Printing list of VMs =======");

                foreach (var virtualMachine in await virtualMachines.ListAsync(rgName).ToEnumerableAsync())
                {
                    Utilities.PrintVirtualMachine(virtualMachine);
                }

                //=============================================================
                // Delete the virtual machine
                Utilities.Log("Deleting VM: " + windowsVM.Id);

                await(await virtualMachines.StartDeleteAsync(rgName, windowsVmName)).WaitForCompletionAsync();

                Utilities.Log("Deleted VM: " + windowsVM.Id);
            }
            finally
            {
                try
                {
                    await ResourceGroupHelper.DeleteResourceGroup(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
Exemple #22
0
        //Получение информации о виртуальной машине
        public static async Task <string> GetVirtualMachineStatusAsync(
            TokenCredentials credential,
            string groupName,
            string vmName,
            string subscriptionId)
        {
            var computeManagementClient = new ComputeManagementClient(credential)
            {
                SubscriptionId = subscriptionId
            };
            var vmResult = await computeManagementClient.VirtualMachines.GetAsync(
                groupName,
                vmName,
                InstanceViewTypes.InstanceView);

            //Console.WriteLine("hardwareProfile");
            //Console.WriteLine("   vmSize: " + vmResult.HardwareProfile.VmSize);

            //Console.WriteLine("\nstorageProfile");
            //Console.WriteLine("  imageReference");
            //Console.WriteLine("    publisher: " + vmResult.StorageProfile.ImageReference.Publisher);
            //Console.WriteLine("    offer: " + vmResult.StorageProfile.ImageReference.Offer);
            //Console.WriteLine("    sku: " + vmResult.StorageProfile.ImageReference.Sku);
            //Console.WriteLine("    version: " + vmResult.StorageProfile.ImageReference.Version);
            //Console.WriteLine("  osDisk");
            //Console.WriteLine("    osType: " + vmResult.StorageProfile.OsDisk.OsType);
            //Console.WriteLine("    name: " + vmResult.StorageProfile.OsDisk.Name);
            //Console.WriteLine("    createOption: " + vmResult.StorageProfile.OsDisk.CreateOption);
            //Console.WriteLine("    uri: " + vmResult.StorageProfile.OsDisk.Vhd.Uri);
            //Console.WriteLine("    caching: " + vmResult.StorageProfile.OsDisk.Caching);
            //Console.WriteLine("\nosProfile");
            //Console.WriteLine("  computerName: " + vmResult.OsProfile.ComputerName);
            //Console.WriteLine("  adminUsername: "******"  provisionVMAgent: " + vmResult.OsProfile.WindowsConfiguration.ProvisionVMAgent.Value);
            //Console.WriteLine("  enableAutomaticUpdates: " + vmResult.OsProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);

            //Console.WriteLine("\nnetworkProfile");
            //foreach (NetworkInterfaceReference nic in vmResult.NetworkProfile.NetworkInterfaces)
            //{
            //    Console.WriteLine("  networkInterface id: " + nic.Id);
            //}

            //Console.WriteLine("\nvmAgent");
            //Console.WriteLine("  vmAgentVersion" + vmResult.InstanceView.VmAgent.VmAgentVersion);
            //Console.WriteLine("    statuses");
            //foreach (InstanceViewStatus stat in vmResult.InstanceView.VmAgent.Statuses)
            //{
            //    Console.WriteLine("    code: " + stat.Code);
            //    Console.WriteLine("    level: " + stat.Level);
            //    Console.WriteLine("    displayStatus: " + stat.DisplayStatus);
            //    Console.WriteLine("    message: " + stat.Message);
            //    Console.WriteLine("    time: " + stat.Time);
            //}

            //Console.WriteLine("\ndisks");
            //foreach (DiskInstanceView idisk in vmResult.InstanceView.Disks)
            //{
            //    Console.WriteLine("  name: " + idisk.Name);
            //    Console.WriteLine("  statuses");
            //    foreach (InstanceViewStatus istat in idisk.Statuses)
            //    {
            //        Console.WriteLine("    code: " + istat.Code);
            //        Console.WriteLine("    level: " + istat.Level);
            //        Console.WriteLine("    displayStatus: " + istat.DisplayStatus);
            //        Console.WriteLine("    time: " + istat.Time);
            //    }
            //}

            //Console.WriteLine("\nVM general status");
            //Console.WriteLine("  provisioningStatus: " + vmResult.ProvisioningState);
            //Console.WriteLine("  id: " + vmResult.Id);
            //Console.WriteLine("  name: " + vmResult.Name);
            //Console.WriteLine("  type: " + vmResult.Type);
            //Console.WriteLine("  location: " + vmResult.Location);
            //Console.WriteLine("\nVM instance status");
            //foreach (InstanceViewStatus istat in vmResult.InstanceView.Statuses)
            //{
            //    Console.WriteLine("\n  code: " + istat.Code);
            //    Console.WriteLine("  level: " + istat.Level);
            //    Console.WriteLine("  displayStatus: " + istat.DisplayStatus);
            //}
            return(vmResult.InstanceView.Statuses[1].DisplayStatus);
        }
Exemple #23
0
        public void TestVMImageListFilters()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context,
                                                                                                               new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                // Filter: top - Negative Test
                var vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 0);
                Assert.True(vmimages.Count == 0);

                // Filter: top - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 1);
                Assert.True(vmimages.Count == 1);

                // Filter: top - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 2);
                Assert.True(vmimages.Count == 2);

                // Filter: orderby - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    orderby: "name desc");

                // Filter: orderby - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 2,
                    orderby: "name asc");
                Assert.True(vmimages.Count == 2);

                // Filter: top orderby - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 1,
                    orderby: "name desc");
                Assert.True(vmimages.Count == 1);

                // Filter: top orderby - Positive Test
                vmimages = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    top: 1,
                    orderby: "name asc");
                Assert.True(vmimages.Count == 1);
            }
        }
        private static string InitializeToken()
        {
            var token = GetToken();

            var creds = new Microsoft.Rest.TokenCredentials(token);

            s_netclient = new NetworkManagementClient(creds) { SubscriptionId = Config.Current.subscription_id };
            s_computeClient = new ComputeManagementClient(creds) { SubscriptionId = Config.Current.subscription_id };
            return token;
        }
Exemple #25
0
        public void TestVMImageAutomaticOSUpgradeProperties()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context,
                                                                                                               new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                // Validate if images supporting automatic OS upgrades return
                // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = true in GET VMImageVesion call
                string   imagePublisher = "MicrosoftWindowsServer";
                string   imageOffer     = "WindowsServer";
                string   imageSku       = "2016-Datacenter";
                string[] availableWindowsServerImageVersions = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray();

                string firstVersion = availableWindowsServerImageVersions.First();
                string lastVersion  = null;
                if (availableWindowsServerImageVersions.Length >= 2)
                {
                    lastVersion = availableWindowsServerImageVersions.Last();
                }

                var vmimage = _pirClient.VirtualMachineImages.Get(
                    ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion);
                Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported);

                if (!string.IsNullOrEmpty(lastVersion))
                {
                    vmimage = _pirClient.VirtualMachineImages.Get(
                        ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion);
                    Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported);
                }

                // Validate if image not whitelisted to support automatic OS upgrades, return
                // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = false in GET VMImageVesion call
                imagePublisher = "Canonical";
                imageOffer     = "UbuntuServer";
                imageSku       = _pirClient.VirtualMachineImages.ListSkus(ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer).FirstOrDefault().Name;
                string[] availableUbuntuImageVersions = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray();

                firstVersion = availableUbuntuImageVersions.First();
                lastVersion  = null;
                if (availableUbuntuImageVersions.Length >= 2)
                {
                    lastVersion = availableUbuntuImageVersions.Last();
                }

                vmimage = _pirClient.VirtualMachineImages.Get(
                    ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion);
                Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported);

                if (!string.IsNullOrEmpty(lastVersion))
                {
                    vmimage = _pirClient.VirtualMachineImages.Get(
                        ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion);
                    Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported);
                }
            }
        }
 public VirtualMachineImageHelper(ComputeManagementClient computeClient)
 {
     this.computeClient = computeClient;
 }
Exemple #27
0
        /// <summary>
        /// Rollback all imported cloud services.
        /// </summary>
        /// <param name="cloudServices">Cloud services to be deleted.</param>
        private void RollBackServices(List <string> cloudServices)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted, ResourceType.CloudService.ToString());
            Logger.Info(methodName, ProgressResources.RollbackCloudServices, ResourceType.CloudService.ToString());
            dcMigrationManager.ReportProgress(ProgressResources.RollbackCloudServices);
            Stopwatch swTotalServices = new Stopwatch();

            swTotalServices.Start();
            //string origServiceName = null;
            if (cloudServices.Count > 0)
            {
                using (var client = new ComputeManagementClient(importParameters.DestinationSubscriptionSettings.Credentials))
                {
                    Parallel.ForEach(cloudServices, cloudService =>
                    {
                        try
                        {
                            Stopwatch swService = new Stopwatch();
                            swService.Start();
                            string origServiceName = resourceImporter.GetSourceResourceName(ResourceType.CloudService, cloudService);
                            Retry.RetryOperation(() => client.HostedServices.DeleteAll(cloudService),
                                                 (BaseParameters)importParameters, ResourceType.CloudService, cloudService, ignoreResourceNotFoundEx: true);

                            CloudService service = subscription.DataCenters.FirstOrDefault().CloudServices.
                                                   Where(ser => (ser.CloudServiceDetails.ServiceName == origServiceName)).FirstOrDefault();
                            if (service.DeploymentDetails != null)
                            {
                                string deploymentName = resourceImporter.GetDestinationResourceName(
                                    ResourceType.Deployment, service.DeploymentDetails.Name, ResourceType.CloudService,
                                    resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                    );
                                resourceImporter.UpdateMedatadaFile(ResourceType.Deployment, deploymentName, false,
                                                                    resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                                                    );
                                Logger.Info(methodName, string.Format(ProgressResources.RollbackDeployment, service.DeploymentDetails.Name,
                                                                      service.DeploymentDetails.Name), ResourceType.Deployment.ToString(), service.DeploymentDetails.Name);

                                foreach (VirtualMachine vm in service.DeploymentDetails.VirtualMachines)
                                {
                                    string virtualmachineName = resourceImporter.GetDestinationResourceName(
                                        ResourceType.VirtualMachine, vm.VirtualMachineDetails.RoleName, ResourceType.CloudService,
                                        resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                        );

                                    resourceImporter.UpdateMedatadaFile(ResourceType.VirtualMachine, virtualmachineName, false,
                                                                        resourceImporter.GetDestinationResourceName(ResourceType.CloudService, service.CloudServiceDetails.ServiceName)
                                                                        );
                                    Logger.Info(methodName, string.Format(ProgressResources.RollbackVirtualMachine, vm.VirtualMachineDetails.RoleName),
                                                ResourceType.VirtualMachine.ToString(), vm.VirtualMachineDetails.RoleName);
                                }
                            }
                            resourceImporter.UpdateMedatadaFile(ResourceType.CloudService, cloudService, false);
                            swService.Stop();
                            Logger.Info(methodName, string.Format(ProgressResources.RollbackCloudService, cloudService, swService.Elapsed.Days, swService.Elapsed.Hours,
                                                                  swService.Elapsed.Minutes, swService.Elapsed.Seconds), ResourceType.CloudService.ToString(), cloudService);
                        }
                        catch (AggregateException exAgg)
                        {
                            foreach (var ex in exAgg.InnerExceptions)
                            {
                                Logger.Error(methodName, exAgg, ResourceType.CloudService.ToString(), cloudService);
                            }
                            throw;
                        }
                    });
                    Logger.Info(methodName, ProgressResources.RollbackCloudServicesWaiting, ResourceType.CloudService.ToString());
                    dcMigrationManager.ReportProgress(ProgressResources.RollbackCloudServicesWaiting);
                    Task.Delay(Constants.DelayTimeInMilliseconds_Rollback).Wait();
                }
            }
            swTotalServices.Stop();
            Logger.Info(methodName, string.Format(ProgressResources.ExecutionCompletedWithTime, swTotalServices.Elapsed.Days, swTotalServices.Elapsed.Hours, swTotalServices.Elapsed.Minutes,
                                                  swTotalServices.Elapsed.Seconds), ResourceType.CloudService.ToString());
        }
 public AzureVirtualMachinesManager(IAzureCloudAuthenticationInfo authInfo) : base(authInfo)
 {
     this._computeManagementClient = new Microsoft.Azure.Management.Compute.ComputeManagementClient(base.ServiceCredentials);
     this._computeManagementClient.SubscriptionId = base.AuthInfo.SubscriptionId;
 }
        internal CloudServiceClient(
            WindowsAzureSubscription subscription,
            ManagementClient managementClient,
            StorageManagementClient storageManagementClient,
            ComputeManagementClient computeManagementClient)
            : this((string)null, null, null, null)
        {
            Subscription = subscription;
            CurrentDirectory = null;
            DebugStream = null;
            VerboseStream = null;
            WarningStream = null;

            CloudBlobUtility = new CloudBlobUtility();
            ManagementClient = managementClient;
            StorageClient = storageManagementClient;
            ComputeClient = computeManagementClient;
        }
Exemple #30
-1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="credentials">Credentials to authorize application</param>
        /// <param name="subscriptionId">SubscriptionID that identifies subscription to create resoruce in</param>
        /// <param name="resourceGroup">Name of resource group</param>
        /// <param name="location">Location for resource</param>
        /// <param name="storageAccountName">Name of Storage Account used to store Virtual HDD on</param>
        /// <param name="vmName">Name of Virtual Machine</param>
        /// <param name="vmSize">VM Size as allowed for the current location</param>
        /// <param name="vmAdminUsername">Admin username</param>
        /// <param name="vmAdminPassword">Admin password</param>
        /// <param name="vmImagePublisher">Publisher of VM Image</param>
        /// <param name="vmImageOffer">Offer from Publisher</param>
        /// <param name="vmImageSku">SKU of Offer</param>
        /// <param name="vmImageVersion">Version of SKU</param>
        /// <param name="vmOSDiskName">Internal name for operating system disk</param>
        /// <param name="nicId">NIC Identifer, used to attach NIC to VM</param>
        /// <returns>Awaitable task</returns>
        private static async Task<VirtualMachine> CreateVirtualMachineAsync(TokenCredentials credentials, string subscriptionId, string resourceGroup, string location, string storageAccountName, string vmName, string vmSize, string vmAdminUsername, string vmAdminPassword, string vmImagePublisher, string vmImageOffer, string vmImageSku, string vmImageVersion, string vmOSDiskName, string nicId)
        {
            Console.WriteLine("Creating Virtual Machine (this may take a while)");
            var computeClient = new ComputeManagementClient(credentials) { SubscriptionId = subscriptionId };
            var vm = await computeClient.VirtualMachines.CreateOrUpdateAsync(resourceGroup, vmName,
                new VirtualMachine
                {
                    Location = location,
                    HardwareProfile = new HardwareProfile(vmSize),
                    OsProfile = new OSProfile(vmName, vmAdminUsername, vmAdminPassword),
                    StorageProfile = new StorageProfile(
                        new ImageReference
                        {
                            Publisher = vmImagePublisher,
                            Offer = vmImageOffer,
                            Sku = vmImageSku,
                            Version = vmImageVersion
                        },
                        new OSDisk
                        {
                            Name = vmOSDiskName,
                            Vhd = new VirtualHardDisk($"http://{storageAccountName}.blob.core.windows.net/vhds/{vmOSDiskName}.vhd"),
                            Caching = "ReadWrite",
                            CreateOption = "FromImage"
                        }),
                    NetworkProfile = new NetworkProfile(
                        new[] { new NetworkInterfaceReference { Id = nicId } }),
                    DiagnosticsProfile = new DiagnosticsProfile(
                        new BootDiagnostics
                        {
                            Enabled = true,
                            StorageUri = $"http://{storageAccountName}.blob.core.windows.net"
                        })
                });

            return vm;
        }
 public VirtualMachineManager( TokenCredentials cred, string subid )
 {
     this._client = new ComputeManagementClient(cred)
                         { SubscriptionId = subid };
 }