Exemple #1
0
        public IEnumerable <MSADLA.Models.USqlCredential> ListCredential(AnalyticsAccount account, string dbname)
        {
            var    oDataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <MSADLA.Models.USqlCredential>();
            string @select    = null;
            bool?  count      = null;

            var page = this.RestClient.Catalog.ListCredentials(account.Name, dbname, oDataQuery, @select, count);

            foreach (var cred in RestUtil.EnumItemsInPages <MSADLA.Models.USqlCredential>(page, p => this.RestClient.Catalog.ListCredentialsNext(p.NextPageLink)))
            {
                yield return(cred);
            }
        }
Exemple #2
0
        public IEnumerable <MSADLA.Models.USqlTableType> ListTableTypes(AnalyticsAccount account, string dbname, string schema)
        {
            var    oDataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <MSADLA.Models.USqlTableType>();
            string @select    = null;
            bool?  count      = null;

            var page = this.RestClient.Catalog.ListTableTypes(account.Name, dbname, schema, oDataQuery, @select, count);

            foreach (var tabletype in RestUtil.EnumItemsInPages <MSADLA.Models.USqlTableType>(page, p => this.RestClient.Catalog.ListTableTypesNext(p.NextPageLink)))
            {
                yield return(tabletype);
            }
        }
Exemple #3
0
        protected IPage <GenericResource> GetAllServiceFabricClusterResources(
            MockContext context,
            ResourceGroup rg)
        {
            var resouceClient = GetResourceManagementClient(context);

            var query = new Microsoft.Rest.Azure.OData.ODataQuery <
                GenericResourceFilter>();

            query.SetFilter(
                f => f.ResourceType == "Microsoft.ServiceFabric/clusters");

            return(resouceClient.ResourceGroups.ListResources(rg.Name, query));
        }
Exemple #4
0
        public IEnumerable <Microsoft.Azure.Management.DataLake.Analytics.Models.USqlView> ListViews(AnalyticsAccount account, string dbname, string schema)
        {
            var    oDataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <Microsoft.Azure.Management.DataLake.Analytics.Models.USqlView>();
            string @select    = null;
            bool?  count      = null;


            var page = this.RestClient.Catalog.ListViews(account.Name, dbname, schema, oDataQuery, @select, count);

            foreach (var view in RestUtil.EnumItemsInPages <MSADLA.Models.USqlView>(page, p => this.RestClient.Catalog.ListViewsNext(p.NextPageLink)))
            {
                yield return(view);
            }
        }
Exemple #5
0
        public IEnumerable <Microsoft.Azure.Management.DataLake.Analytics.Models.USqlExternalDataSource> ListExternalDatasources(AnalyticsAccount account, string dbname)
        {
            var oDataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <MSADLA.Models.USqlExternalDataSource>();

            string @select = null;
            bool?  count   = null;

            var page = this.RestClient.Catalog.ListExternalDataSources(account.Name, dbname, oDataQuery, @select, count);

            foreach (var ds in RestUtil.EnumItemsInPages <MSADLA.Models.USqlExternalDataSource>(page, p => this.RestClient.Catalog.ListExternalDataSourcesNext(p.NextPageLink)))
            {
                yield return(ds);
            }
        }
        public IEnumerable <JobInfo> ListJobs(JobListingParameters parameters)
        {
            var odata_query = new Microsoft.Rest.Azure.OData.ODataQuery <MSADL.Analytics.Models.JobInformation>();

            odata_query.OrderBy = parameters.Sorting.CreateOrderByString();
            odata_query.Filter  = parameters.Filter.ToFilterString();

            // enumerate the job objects
            var jobs = this.RestClients._JobRest.JobList(this.Account, odata_query, parameters.Top);

            // convert them to the JobInfo
            var jobinfos = jobs.Select(j => new JobInfo(j, this.Account));

            return(jobinfos);
        }
        public void GetMetricDefinitionsTest()
        {
            IList <MetricDefinition> expectedMetricDefinitionCollection = GetMetricDefinitionCollection(ResourceUri);
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(string.Concat("{ \"value\":", expectedMetricDefinitionCollection.ToJson(), "}"))
            };

            RecordedDelegatingHandler handler = new RecordedDelegatingHandler(response);
            var insightsClient = GetInsightsClient(handler);

            var filterString            = new Microsoft.Rest.Azure.OData.ODataQuery <MetricDefinition>("names eq 'CpuPercentage'");
            var actualMetricDefinitions = insightsClient.MetricDefinitions.ListAsync(resourceUri: ResourceUri, odataQuery: filterString, cancellationToken: new CancellationToken()).Result;

            AreEqual(expectedMetricDefinitionCollection, actualMetricDefinitions.ToList <MetricDefinition>());
        }
        public void GetMetricsTest()
        {
            IList <Metric> expectedMetricCollection = GetMetricCollection(ResourceUri);
            var            response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(string.Concat("{ \"value\":", expectedMetricCollection.ToJson(), "}"))
            };

            RecordedDelegatingHandler handler = new RecordedDelegatingHandler(response);
            var insightsClient = GetInsightsClient(handler);

            var filterString  = new Microsoft.Rest.Azure.OData.ODataQuery <Metric>("timeGrain eq duration'PT1M' and startTime eq 2014-01-01T06:00:00Z and endTime eq 2014-01-10T06:00:00Z");
            var actualMetrics = insightsClient.Metrics.ListAsync(resourceUri: ResourceUri, odataQuery: filterString, cancellationToken: CancellationToken.None).Result;

            AreEqual(expectedMetricCollection, actualMetrics.ToList <Metric>());
        }
        public override void ExecuteCmdlet()
        {
            string resourceGroupName;
            string vmScaleSetName;

            resourceGroupName = this.ResourceGroupName;
            vmScaleSetName    = this.VMScaleSetName;

            var expand = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();

            expand.Expand = "instanceView";
            var vmList       = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName, expand);
            var resultList   = vmList.ToList();
            var nextPageLink = vmList.NextPageLink;

            while (!string.IsNullOrEmpty(nextPageLink))
            {
                var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                foreach (var pageItem in pageResult)
                {
                    resultList.Add(pageItem);
                }
                nextPageLink = pageResult.NextPageLink;
            }
            List <VirtualMachineScaleSetVM> listOfVms = new List <VirtualMachineScaleSetVM>(resultList);

            Rest.Azure.AzureOperationResponse result = null;
            foreach (VirtualMachineScaleSetVM vm in listOfVms)
            {
                result = VirtualMachineScaleSetVMRunCommandsClient.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmScaleSetName, vm.InstanceId, this.RunCommandName).GetAwaiter().GetResult();
            }

            PSOperationStatusResponse output = new PSOperationStatusResponse
            {
                StartTime = this.StartTime,
                EndTime   = DateTime.Now
            };

            if (result != null && result.Request != null && result.Request.RequestUri != null)
            {
                output.Name = GetOperationIdFromUrlString(result.Request.RequestUri.ToString());
            }

            WriteObject(output);
        }
Exemple #10
0
        public void TestGetAllVirtualNetworksOData()
        {
            RunTest((client) =>
            {
                Microsoft.Rest.Azure.OData.ODataQuery <VirtualNetwork> odataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualNetwork>();
                odataQuery.Top = 10;

                var networks = client.VirtualNetworks.List(odataQuery);
                Common.MapOverIPage(networks, client.VirtualNetworks.ListNext, (network) =>
                {
                    NetworkCommon.ValidateBaseResources(network);

                    ValidateBaseResourceTenant(network);

                    ValidateConfigurationState(network.ConfigurationState);
                });
            });
        }
Exemple #11
0
        protected ImageReference FindVMImage(string publisher, string offer, string sku)
        {
            var query = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineImageResource>();

            query.Top = 1;
            var images = m_CrpClient.VirtualMachineImages.List(
                location: m_location, publisherName: publisher, offer: offer, skus: sku,
                odataQuery: query);
            var image = images.First();

            return(new ImageReference
            {
                Publisher = publisher,
                Offer = offer,
                Sku = sku,
                Version = image.Name
            });
        }
Exemple #12
0
        protected void ExecuteVirtualMachineScaleSetVMListMethod(object[] invokeMethodInputParameters)
        {
            string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
            string virtualMachineScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]);
            Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM> odataQuery = (Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM>)ParseParameter(invokeMethodInputParameters[2]);
            string select = (string)ParseParameter(invokeMethodInputParameters[3]);

            var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, virtualMachineScaleSetName, odataQuery, select);
            var resultList = result.ToList();
            var nextPageLink = result.NextPageLink;
            while (!string.IsNullOrEmpty(nextPageLink))
            {
                var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                foreach (var pageItem in pageResult)
                {
                    resultList.Add(pageItem);
                }
                nextPageLink = pageResult.NextPageLink;
            }
            WriteObject(resultList, true);
        }
Exemple #13
0
        public IEnumerable <JobInfo> ListJobs(ListJobOptions options)
        {
            var odata_query = new Microsoft.Rest.Azure.OData.ODataQuery <MSADL.Analytics.Models.JobInformation>();

            // if users requests top, set the value appropriately relative to the page size
            if ((options.Top > 0) && (options.Top <= JobCommands.ADLJobPageSize))
            {
                odata_query.Top = options.Top;
            }

            odata_query.OrderBy = options.Sorting.CreateOrderByString();
            odata_query.Filter  = options.Filter.ToFilterString();

            // enumerate the job objects
            var jobs = this.clients._JobRest.JobList(this.account, odata_query, options.Top);

            // convert them to the JobInfo
            var jobinfos = jobs.Select(j => new JobInfo(j, this.account));

            return(jobinfos);
        }
        public IEnumerable <MSADLA.Models.JobInformation> JobList(AnalyticsAccountRef account,
                                                                  Microsoft.Rest.Azure.OData.ODataQuery <MSADLA.Models.JobInformation> odata_query, int top)
        {
            // Other parameters
            string opt_select = null;
            bool?  opt_count  = null;

            int item_count = 0;
            var page       = this.RestClient.Job.List(account.Name, odata_query, opt_select, opt_count);

            foreach (
                var job in
                RestUtil.EnumItemsInPages(page, p => this.RestClient.Job.ListNext(p.NextPageLink)))
            {
                yield return(job);

                item_count++;

                if ((top > 0) && (item_count >= top))
                {
                    break;
                }
            }
        }
Exemple #15
0
        public void TestGetAllPublicIpAddressesOData()
        {
            RunTest((client) =>
            {
                Microsoft.Rest.Azure.OData.ODataQuery <PublicIpAddress> odataQuery = new Microsoft.Rest.Azure.OData.ODataQuery <PublicIpAddress>();
                odataQuery.Top = 10;

                var addresses = client.PublicIPAddresses.List(odataQuery);

                // This test should be using the SessionRecord which has an existing PublicIPAddress created
                if (addresses != null)
                {
                    addresses.ForEach((address) =>
                    {
                        NetworkCommon.ValidateBaseResources(address);

                        ValidateBaseResourceTenant(address);

                        Assert.NotNull(address.IpAddress);
                        Assert.NotNull(address.IpPool);
                    });
                }
            });
        }
Exemple #16
0
        public IEnumerable <JobInfo> ListJobs(JobListingParameters parameters)
        {
            var odata_query = new Microsoft.Rest.Azure.OData.ODataQuery <MSADL.Analytics.Models.JobInformation>();

            odata_query.OrderBy = parameters.Sorting.CreateOrderByString();
            odata_query.Filter  = parameters.Filter.ToFilterString();

            // enumerate the job objects
            // Other parameters
            string opt_select = null;
            bool?  opt_count  = null;

            var pageiter = new Rest.PagedIterator <MSADLA.Models.JobInformation>();

            pageiter.GetFirstPage = () => this.RestClients.JobsClient.Job.List(this.Account.Name, odata_query, opt_select, opt_count);
            pageiter.GetNextPage  = p => this.RestClients.JobsClient.Job.ListNext(p.NextPageLink);

            var jobs = pageiter.EnumerateItems(parameters.Top);

            // convert them to the JobInfo
            var jobinfos = jobs.Select(j => new JobInfo(j, this.Account));

            return(jobinfos);
        }
        private void TestScaleSetOperationsInternal(MockContext context, string vmSize = null, bool hasManagedDisks = false, bool useVmssExtension = true,
                                                    bool hasDiffDisks = false, IList <string> zones = null, int?osDiskSizeInGB = null, bool isPpgScenario = false, bool?enableUltraSSD = false,
                                                    Action <VirtualMachineScaleSet> vmScaleSetCustomizer = null, Action <VirtualMachineScaleSet> vmScaleSetValidator = null, string diskEncryptionSetId = null)
        {
            EnsureClientsInitialized(context);

            ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
            // Create resource group
            var    rgName             = TestUtilities.GenerateName(TestPrefix);
            var    vmssName           = TestUtilities.GenerateName("vmss");
            string storageAccountName = TestUtilities.GenerateName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;

            VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
            {
                Extensions = new List <VirtualMachineScaleSetExtension>()
                {
                    GetTestVMSSVMExtension(),
                }
            };

            try
            {
                var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);

                m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");

                string ppgId   = null;
                string ppgName = null;
                if (isPpgScenario)
                {
                    ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest");
                    ppgId   = CreateProximityPlacementGroup(rgName, ppgName);
                }

                VirtualMachineScaleSet getResponse = CreateVMScaleSet_NoAsyncTracking(
                    rgName,
                    vmssName,
                    storageAccountOutput,
                    imageRef,
                    out inputVMScaleSet,
                    useVmssExtension ? extensionProfile : null,
                    (vmScaleSet) => {
                    vmScaleSet.Overprovision = true;
                    if (!String.IsNullOrEmpty(vmSize))
                    {
                        vmScaleSet.Sku.Name = vmSize;
                    }
                    vmScaleSetCustomizer?.Invoke(vmScaleSet);
                },
                    createWithManagedDisks: hasManagedDisks,
                    hasDiffDisks: hasDiffDisks,
                    zones: zones,
                    osDiskSizeInGB: osDiskSizeInGB,
                    ppgId: ppgId,
                    enableUltraSSD: enableUltraSSD,
                    diskEncryptionSetId: diskEncryptionSetId);

                if (diskEncryptionSetId != null)
                {
                    Assert.True(getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null");
                    Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
                                "OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");

                    Assert.Equal(1, getResponse.VirtualMachineProfile.StorageProfile.DataDisks.Count);
                    Assert.True(getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null");
                    Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase),
                                "DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource");
                }

                ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks, ppgId: ppgId);

                var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
                Assert.NotNull(getInstanceViewResponse);
                ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse);

                if (isPpgScenario)
                {
                    ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName);
                    Assert.Equal(1, outProximityPlacementGroup.VirtualMachineScaleSets.Count);
                    string expectedVmssReferenceId = Helpers.GetVMScaleSetReferenceId(m_subId, rgName, vmssName);
                    Assert.Equal(expectedVmssReferenceId, outProximityPlacementGroup.VirtualMachineScaleSets.First().Id, StringComparer.OrdinalIgnoreCase);
                }

                var listResponse = m_CrpClient.VirtualMachineScaleSets.List(rgName);
                ValidateVMScaleSet(inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks);

                var listSkusResponse = m_CrpClient.VirtualMachineScaleSets.ListSkus(rgName, vmssName);
                Assert.NotNull(listSkusResponse);
                Assert.False(listSkusResponse.Count() == 0);

                if (zones != null)
                {
                    var query = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                    query.SetFilter(vm => vm.LatestModelApplied == true);
                    var listVMsResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query);
                    Assert.False(listVMsResponse == null, "VMScaleSetVMs not returned");
                    Assert.True(listVMsResponse.Count() == inputVMScaleSet.Sku.Capacity);

                    foreach (var vmScaleSetVM in listVMsResponse)
                    {
                        string instanceId    = vmScaleSetVM.InstanceId;
                        var    getVMResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmssName, instanceId);
                        ValidateVMScaleSetVM(inputVMScaleSet, instanceId, getVMResponse, hasManagedDisks);
                    }
                }

                vmScaleSetValidator?.Invoke(getResponse);

                m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName);
            }
            finally
            {
                //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
                //of the test to cover deletion. CSM does persistent retrying over all RG resources.
                m_ResourcesClient.ResourceGroups.Delete(rgName);
            }
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                string resourceGroupName = this.ResourceGroupName;
                string vmScaleSetName    = this.VMScaleSetName;
                string instanceId        = this.InstanceId;

                if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId))
                {
                    if (this.ParameterSetName.Equals("FriendMethod"))
                    {
                        var result   = VirtualMachineScaleSetVMsClient.GetInstanceView(resourceGroupName, vmScaleSetName, instanceId);
                        var psObject = new PSVirtualMachineScaleSetVMInstanceView();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineScaleSetVMInstanceView, PSVirtualMachineScaleSetVMInstanceView>(result, psObject);
                        WriteObject(psObject);
                    }
                    else
                    {
                        var result   = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId);
                        var psObject = new PSVirtualMachineScaleSetVM();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineScaleSetVM, PSVirtualMachineScaleSetVM>(result, psObject);
                        WriteObject(psObject);
                    }
                }
                else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName))
                {
                    if (this.ParameterSetName.Equals("FriendMethod"))
                    {
                        var expand    = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                        expand.Expand = "instanceView";

                        var result       = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName, expand);
                        var resultList   = result.ToList();
                        var nextPageLink = result.NextPageLink;
                        while (!string.IsNullOrEmpty(nextPageLink))
                        {
                            var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                            foreach (var pageItem in pageResult)
                            {
                                resultList.Add(pageItem);
                            }
                            nextPageLink = pageResult.NextPageLink;
                        }
                        var psObject = new List <PSVirtualMachineScaleSetVMList>();
                        foreach (var r in resultList)
                        {
                            psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineScaleSetVM, PSVirtualMachineScaleSetVMList>(r));
                        }
                        WriteObject(psObject, true);
                    }
                    else
                    {
                        var result       = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName);
                        var resultList   = result.ToList();
                        var nextPageLink = result.NextPageLink;
                        while (!string.IsNullOrEmpty(nextPageLink))
                        {
                            var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                            foreach (var pageItem in pageResult)
                            {
                                resultList.Add(pageItem);
                            }
                            nextPageLink = pageResult.NextPageLink;
                        }
                        var psObject = new List <PSVirtualMachineScaleSetVMList>();
                        foreach (var r in resultList)
                        {
                            psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineScaleSetVM, PSVirtualMachineScaleSetVMList>(r));
                        }
                        WriteObject(psObject, true);
                    }
                }
            });
        }
        public void TestExtImgListVersionsFilters()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                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 #20
0
        public static VirtualMachine CreateVM(SqlVirtualMachineTestContext context, string name = null, NetworkInterface nic = null, AvailabilitySet availabilitySet = null)
        {
            MockClient client = context.client;

            if (nic == null)
            {
                nic = CreateNetworkInterface(context);
            }

            // Get VM image
            string publisher = Constants.publisher;
            string offer     = Constants.imageOffer;
            string sku       = Constants.imageSku;
            var    query     = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineImageResource>();

            query.Top = 1;
            var images = client.computeClient.VirtualMachineImages.List(
                location: context.location, publisherName: publisher, offer: offer, skus: sku,
                odataQuery: query);
            var            image    = images.First();
            ImageReference imageRef = new ImageReference
            {
                Publisher = publisher,
                Offer     = offer,
                Sku       = sku,
                Version   = image.Name
            };

            // Create VM
            if (name == null)
            {
                name = context.generateResourceName();
            }
            VirtualMachine vm = client.computeClient.VirtualMachines.CreateOrUpdate(context.resourceGroup.Name, name, new VirtualMachine
            {
                Location        = context.location,
                HardwareProfile = new HardwareProfile
                {
                    VmSize = "Standard_DS13-2_v2"
                },
                NetworkProfile = new NetworkProfile
                {
                    NetworkInterfaces = new List <NetworkInterfaceReference>
                    {
                        new NetworkInterfaceReference
                        {
                            Id = nic.Id
                        }
                    }
                },
                StorageProfile = new StorageProfile
                {
                    ImageReference = imageRef,
                    OsDisk         = new OSDisk
                    {
                        Caching = CachingTypes.None,
                        WriteAcceleratorEnabled = false,
                        CreateOption            = DiskCreateOption.FromImage,
                        ManagedDisk             = new ManagedDiskParameters
                        {
                            StorageAccountType = "Standard_LRS"
                        }
                    },
                    DataDisks = new List <DataDisk>()
                    {
                        new DataDisk()
                        {
                            Caching = CachingTypes.None,
                            WriteAcceleratorEnabled = false,
                            CreateOption            = DiskCreateOptionTypes.Empty,
                            Lun         = 0,
                            DiskSizeGB  = 30,
                            ManagedDisk = new ManagedDiskParameters()
                            {
                                StorageAccountType = "Standard_LRS"
                            }
                        }
                    }
                },
                OsProfile = new OSProfile
                {
                    AdminUsername        = Constants.adminLogin,
                    AdminPassword        = Constants.adminPassword,
                    ComputerName         = name,
                    WindowsConfiguration = new WindowsConfiguration()
                    {
                        ProvisionVMAgent = true
                    }
                },
                AvailabilitySet = availabilitySet == null? null : new Compute.Models.SubResource()
                {
                    Id = availabilitySet.Id
                },
            });

            vm.Validate();
            return(vm);
        }
Exemple #21
0
        private void TestScaleSetOperationsInternal(MockContext context, string vmSize = null, bool hasManagedDisks = false, bool useVmssExtension = true,
                                                    bool hasDiffDisks = false, IList <string> zones = null, int?osDiskSizeInGB = null)
        {
            EnsureClientsInitialized(context);

            ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
            // Create resource group
            var    rgName             = TestUtilities.GenerateName(TestPrefix);
            var    vmssName           = TestUtilities.GenerateName("vmss");
            string storageAccountName = TestUtilities.GenerateName(TestPrefix);
            VirtualMachineScaleSet inputVMScaleSet;

            VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
            {
                Extensions = new List <VirtualMachineScaleSetExtension>()
                {
                    GetTestVMSSVMExtension(),
                }
            };

            try
            {
                var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);

                m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");

                var getResponse = CreateVMScaleSet_NoAsyncTracking(
                    rgName,
                    vmssName,
                    storageAccountOutput,
                    imageRef,
                    out inputVMScaleSet,
                    useVmssExtension ? extensionProfile : null,
                    (vmScaleSet) => {
                    vmScaleSet.Overprovision = true;
                    if (!String.IsNullOrEmpty(vmSize))
                    {
                        vmScaleSet.Sku.Name = vmSize;
                    }
                },
                    createWithManagedDisks: hasManagedDisks,
                    hasDiffDisks: hasDiffDisks,
                    zones: zones,
                    osDiskSizeInGB: osDiskSizeInGB);

                ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks);

                var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
                Assert.NotNull(getInstanceViewResponse);
                ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse);

                var listResponse = m_CrpClient.VirtualMachineScaleSets.List(rgName);
                ValidateVMScaleSet(inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks);

                var listSkusResponse = m_CrpClient.VirtualMachineScaleSets.ListSkus(rgName, vmssName);
                Assert.NotNull(listSkusResponse);
                Assert.False(listSkusResponse.Count() == 0);

                if (zones != null)
                {
                    var query = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                    query.SetFilter(vm => vm.LatestModelApplied == true);
                    var listVMsResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query);
                    Assert.False(listVMsResponse == null, "VMScaleSetVMs not returned");
                    Assert.True(listVMsResponse.Count() == inputVMScaleSet.Sku.Capacity);

                    foreach (var vmScaleSetVM in listVMsResponse)
                    {
                        string instanceId    = vmScaleSetVM.InstanceId;
                        var    getVMResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmssName, instanceId);
                        ValidateVMScaleSetVM(inputVMScaleSet, instanceId, getVMResponse, hasManagedDisks);
                    }
                }

                m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName);
            }
            finally
            {
                //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
                //of the test to cover deletion. CSM does persistent retrying over all RG resources.
                m_ResourcesClient.ResourceGroups.Delete(rgName);
            }
        }
Exemple #22
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.VMScaleSetName, "Add"))
                {
                    string resourceGroupName;
                    string vmScaleSetName;
                    switch (this.ParameterSetName)
                    {
                    case "ObjectParameter":
                        resourceGroupName = GetResourceGroupName(this.VirtualMachineScaleSetVM.Id);
                        vmScaleSetName    = GetResourceName(this.VirtualMachineScaleSetVM.Id, "Microsoft.Compute/virtualMachineScaleSets", "virtualMachines");
                        break;

                    default:
                        resourceGroupName = this.ResourceGroupName;
                        vmScaleSetName    = this.VMScaleSetName;
                        break;
                    }
                    VirtualMachineRunCommand vmruncommand;

                    vmruncommand = new VirtualMachineRunCommand
                    {
                        OutputBlobUri    = this.IsParameterBound(c => c.OutputBlobUri) ? this.OutputBlobUri : null,
                        ErrorBlobUri     = this.IsParameterBound(c => c.ErrorBlobUri) ? this.ErrorBlobUri : null,
                        RunAsPassword    = this.IsParameterBound(c => c.RunAsPassword) ? this.RunAsPassword.ToString() : null,
                        RunAsUser        = this.IsParameterBound(c => c.RunAsUser) ? this.RunAsUser : null,
                        TimeoutInSeconds = this.IsParameterBound(c => c.TimeOutInSeconds) ? Convert.ToInt32(this.TimeOutInSeconds) : (int?)null,
                        Location         = this.IsParameterBound(c => c.Location) ? this.Location : null,
                        AsyncExecution   = this.IsParameterBound(c => c.AsyncExecution) ? this.AsyncExecution : null
                    };


                    if (this.IsParameterBound(c => c.ScriptUri))
                    {
                        vmruncommand.Source = new VirtualMachineRunCommandScriptSource
                        {
                            Script    = this.IsParameterBound(c => c.Script) ? this.Script : null,
                            ScriptUri = this.IsParameterBound(c => c.ScriptUri) ? this.ScriptUri : null,
                            CommandId = this.IsParameterBound(c => c.CommandId) ? this.CommandId : null
                        };
                    }
                    else if (this.ScriptPath != null && this.IsParameterBound(c => c.ScriptPath))
                    {
                        List <string> Script       = new List <string>();
                        PathIntrinsics currentPath = SessionState.Path;
                        var filePath       = new System.IO.FileInfo(currentPath.GetUnresolvedProviderPathFromPSPath(this.ScriptPath));
                        string fileContent = Commands.Common.Authentication.Abstractions.FileUtilities.DataStore.ReadFileAsText(filePath.FullName);
                        Script             = fileContent.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                        vmruncommand.Source = new VirtualMachineRunCommandScriptSource(this.Script, this.ScriptPath, this.CommandId);
                    }

                    if (this.Parameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.Parameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();

                            p.Name  = key.ToString();
                            p.Value = this.Parameter[key].ToString();
                            vParameter.Add(p);
                        }
                        vmruncommand.Parameters = vParameter;
                    }
                    else if (this.ProtectedParameter != null)
                    {
                        var vParameter = new List <RunCommandInputParameter>();
                        foreach (var key in this.ProtectedParameter.Keys)
                        {
                            RunCommandInputParameter p = new RunCommandInputParameter();

                            p.Name  = key.ToString();
                            p.Value = this.ProtectedParameter[key].ToString();
                            vParameter.Add(p);
                        }
                        vmruncommand.ProtectedParameters = vParameter;
                    }

                    var expand       = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                    expand.Expand    = "instanceView";
                    var vmList       = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName, expand);
                    var resultList   = vmList.ToList();
                    var nextPageLink = vmList.NextPageLink;
                    while (!string.IsNullOrEmpty(nextPageLink))
                    {
                        var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                        foreach (var pageItem in pageResult)
                        {
                            resultList.Add(pageItem);
                        }
                        nextPageLink = pageResult.NextPageLink;
                    }
                    List <VirtualMachineScaleSetVM> listOfVms = new List <VirtualMachineScaleSetVM>(resultList);
                    List <PSVirtualMachineRunCommand> output  = new List <PSVirtualMachineRunCommand>();


                    foreach (VirtualMachineScaleSetVM vm in listOfVms)
                    {
                        var resultOfRunCmd = VirtualMachineScaleSetVMRunCommandsClient.BeginCreateOrUpdateAsync(resourceGroupName, vmScaleSetName, vm.InstanceId, this.Name, vmruncommand);
                        var Pstemp         = new PSVirtualMachineRunCommand();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineRunCommand, PSVirtualMachineRunCommand>(resultOfRunCmd.Result, Pstemp);
                        output.Add(Pstemp);
                    }

                    WriteObject(output);
                }
            });
        }
        protected PSArgument[] CreateVirtualMachineScaleSetVMListParameters()
        {
            string resourceGroupName = string.Empty;
            string virtualMachineScaleSetName = string.Empty;
            Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM> odataQuery = new Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM>();
            string select = string.Empty;

            return ConvertFromObjectsToArguments(
                 new string[] { "ResourceGroupName", "VirtualMachineScaleSetName", "OdataQuery", "Select" },
                 new object[] { resourceGroupName, virtualMachineScaleSetName, odataQuery, select });
        }
 /// <summary>
 /// Specify filter parameter with value '$filter=id gt 5 and name eq
 /// 'foo'&amp;$orderby=id&amp;$top=10'
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async System.Threading.Tasks.Task GetWithFilterAsync(this IOdataOperations operations, Microsoft.Rest.Azure.OData.ODataQuery <OdataFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <OdataFilter>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     await operations.GetWithFilterWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false);
 }
 /// <summary>
 /// Specify filter parameter with value '$filter=id gt 5 and name eq
 /// 'foo'&amp;$orderby=id&amp;$top=10'
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 public static void GetWithFilter(this IOdataOperations operations, Microsoft.Rest.Azure.OData.ODataQuery <OdataFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <OdataFilter>))
 {
     System.Threading.Tasks.Task.Factory.StartNew(s => ((IOdataOperations)s).GetWithFilterAsync(odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
Exemple #26
0
        public void TestVMImageListFilters()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context,
                                                                                                               new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                var query = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineImageResource>();

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

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

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

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

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

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

                // Filter: top orderby - Positive Test
                query.Top     = 1;
                query.OrderBy = "name asc";
                vmimages      = _pirClient.VirtualMachineImages.List(
                    ComputeManagementTestUtilities.DefaultLocation,
                    "MicrosoftWindowsServer",
                    "WindowsServer",
                    "2012-R2-Datacenter",
                    query);
                Assert.True(vmimages.Count == 1);
            }
        }
Exemple #27
0
        private void TestVMScaleSetVMOperationsInternal(MockContext context, bool hasManagedDisks = false)
        {
            InitializeCommon(context);
            instanceId = "0";

            bool passed = false;

            try
            {
                var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);

                VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(
                    rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet,
                    createWithManagedDisks: hasManagedDisks);

                var getResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmScaleSet.Name, instanceId);

                var imageReference = getResponse.StorageProfile.ImageReference;
                Assert.NotNull(imageReference?.ExactVersion);
                Assert.Equal(imageReference.Version, imageReference.ExactVersion);

                VirtualMachineScaleSetVM vmScaleSetVMModel = GenerateVMScaleSetVMModel(vmScaleSet, instanceId, hasManagedDisks);
                ValidateVMScaleSetVM(vmScaleSetVMModel, vmScaleSet.Sku.Name, getResponse, hasManagedDisks);

                var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName,
                                                                                                    vmScaleSet.Name, instanceId);
                Assert.True(getInstanceViewResponse != null, "VMScaleSetVM not returned.");
                ValidateVMScaleSetVMInstanceView(getInstanceViewResponse, hasManagedDisks);

                var query = new Microsoft.Rest.Azure.OData.ODataQuery <VirtualMachineScaleSetVM>();
                query.SetFilter(vm => vm.LatestModelApplied == true);
                var listResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query);
                Assert.False(listResponse == null, "VMScaleSetVMs not returned");
                Assert.True(listResponse.Count() == inputVMScaleSet.Sku.Capacity);

                query.Filter = null;
                query.Expand = "instanceView";
                listResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query, "instanceView");
                Assert.False(listResponse == null, "VMScaleSetVMs not returned");
                Assert.True(listResponse.Count() == inputVMScaleSet.Sku.Capacity);

                m_CrpClient.VirtualMachineScaleSetVMs.Start(rgName, vmScaleSet.Name, instanceId);
                m_CrpClient.VirtualMachineScaleSetVMs.Reimage(rgName, vmScaleSet.Name, instanceId, tempDisk: null);

                if (hasManagedDisks)
                {
                    m_CrpClient.VirtualMachineScaleSetVMs.ReimageAll(rgName, vmScaleSet.Name, instanceId);
                }

                m_CrpClient.VirtualMachineScaleSetVMs.Restart(rgName, vmScaleSet.Name, instanceId);
                m_CrpClient.VirtualMachineScaleSetVMs.PowerOff(rgName, vmScaleSet.Name, instanceId);
                m_CrpClient.VirtualMachineScaleSetVMs.Deallocate(rgName, vmScaleSet.Name, instanceId);
                m_CrpClient.VirtualMachineScaleSetVMs.Delete(rgName, vmScaleSet.Name, instanceId);

                passed = true;
            }
            finally
            {
                // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
                // of the test to cover deletion. CSM does persistent retrying over all RG resources.
                m_ResourcesClient.ResourceGroups.Delete(rgName);
            }

            Assert.True(passed);
        }
 /// <summary>
 /// Gets the first page of data source instances in a workspace with the link
 /// to the next page.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group to get. The name is case insensitive.
 /// </param>
 /// <param name='workspaceName'>
 /// The workspace that contains the data sources.
 /// </param>
 /// <param name='skiptoken'>
 /// Starting point of the collection of data source instances.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Microsoft.Rest.Azure.IPage <DataSource> > ListByWorkspaceAsync(this IDataSourcesOperations operations, Microsoft.Rest.Azure.OData.ODataQuery <DataSourceFilter> odataQuery, string resourceGroupName, string workspaceName, string skiptoken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.ListByWorkspaceWithHttpMessagesAsync(odataQuery, resourceGroupName, workspaceName, skiptoken, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemple #29
0
        /// <summary>
        /// List the alert rules within a resource group.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <System.Collections.Generic.IEnumerable <AlertRuleResource> > > ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery <AlertRuleResource> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <AlertRuleResource>), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (this.Client.SubscriptionId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2016-03-01";
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <System.Collections.Generic.IEnumerable <AlertRuleResource> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Page1 <AlertRuleResource> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Specify filter parameter with value '$filter=id gt 5 and name eq
        /// 'foo'&amp;$orderby=id&amp;$top=10'
        /// </summary>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse> GetWithFilterWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery <OdataFilterInner> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <OdataFilterInner>), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetWithFilter", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/odata/filter").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 /// <summary>
 /// Gets the first page of data source instances in a workspace with the link
 /// to the next page.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='odataQuery'>
 /// OData parameters to apply to the operation.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group to get. The name is case insensitive.
 /// </param>
 /// <param name='workspaceName'>
 /// The workspace that contains the data sources.
 /// </param>
 /// <param name='skiptoken'>
 /// Starting point of the collection of data source instances.
 /// </param>
 public static Microsoft.Rest.Azure.IPage <DataSource> ListByWorkspace(this IDataSourcesOperations operations, Microsoft.Rest.Azure.OData.ODataQuery <DataSourceFilter> odataQuery, string resourceGroupName, string workspaceName, string skiptoken = default(string))
 {
     return(System.Threading.Tasks.Task.Factory.StartNew(s => ((IDataSourcesOperations)s).ListByWorkspaceAsync(odataQuery, resourceGroupName, workspaceName, skiptoken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }