public void GetPreviewedFeatures()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{

                    'name': 'Providers.Test/DONOTDELETEBETA',

                    'properties': {

                    'state': 'NotRegistered'

                     },

                    'id': '/subscriptions/fda3b6ba-8803-441c-91fb-6cc798cf6ea0/providers/Microsoft.Features/providers/Providers.Test/features/DONOTDELETEBETA',

                    'type': 'Microsoft.Features/providers/features'

              }
            ")
            };

            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetFeatureClient(handler);

            string resourceProviderNamespace = "Providers.Test";

            string featureName = "DONOTDELETEBETA";

            // ----Verify API calls for get all features under current subid----
            var getResult = client.Features.Get( resourceProviderNamespace,featureName);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            //Valid payload
            //Construct expected URL
            string expectedUrl = "/subscriptions/" + Uri.EscapeDataString(client.Credentials.SubscriptionId) + "/providers/Microsoft.Features/providers/"+Uri.EscapeDataString(resourceProviderNamespace) + "/features/" + Uri.EscapeDataString(featureName) + "?";
            expectedUrl = expectedUrl + "api-version=2015-12-01";
            string baseUrl = client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (expectedUrl[0] == '/')
            {
                expectedUrl = expectedUrl.Substring(1);
            }
            expectedUrl = baseUrl + "/" + expectedUrl;
            expectedUrl = expectedUrl.Replace(" ", "%20");

            Assert.Equal(expectedUrl, handler.Uri.ToString());

            // Valid response
            Assert.Equal(getResult.StatusCode, HttpStatusCode.OK);
            //-------------
        }
        public void ProviderGetThrowsExceptions()
        {
            var handler = new RecordedDelegatingHandler();
            var client = GetResourceManagementClient(handler);

            Assert.Throws<ArgumentNullException>(() => client.Providers.Get(null));
        }
        public void CreateListAndDeleteSubscriptionTagValue()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();

                string tagName = TestUtilities.GenerateName("csmtg");
                string tagValue = TestUtilities.GenerateName("csmtgv");

                var client = GetResourceManagementClient(handler);
                var createNameResult = client.Tags.CreateOrUpdate(tagName);
                var createValueResult = client.Tags.CreateOrUpdateValue(tagName, tagValue);

                Assert.Equal(tagName, createNameResult.Tag.Name);
                Assert.Equal(tagValue, createValueResult.Value.Value);

                var listResult = client.Tags.List();
                Assert.True(listResult.Tags.Count > 0);

                client.Tags.DeleteValue(tagName, tagValue);
                client.Tags.Delete(tagName);
            }
        }
        public void ProviderGetValidateMessage()
        {
            TestUtilities.StartTest();
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetResourceManagementClient(handler);

            var reg = client.Providers.Register(ProviderName);
            Assert.NotNull(reg);
            Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, reg.StatusCode);

            var result = client.Providers.Get(ProviderName);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate result
            Assert.NotNull(result);
            Assert.NotEmpty(result.Provider.Id);
            Assert.Equal(ProviderName, result.Provider.Namespace);
            Assert.True(ProviderRegistrationState.Registered == result.Provider.RegistrationState ||
                ProviderRegistrationState.Registering == result.Provider.RegistrationState,
                string.Format("Provider registration state was not 'Registered' or 'Registering', instead it was '{0}'", result.Provider.RegistrationState));
            Assert.NotEmpty(result.Provider.ResourceTypes);
            Assert.NotEmpty(result.Provider.ResourceTypes[0].Locations);
            TestUtilities.EndTest();
        }
        public void DeleteResourceGroupRemovesGroupResources()
        {
            TestUtilities.StartTest();
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };

            var client = GetResourceManagementClient(handler);
            string location = "westus";
            var resourceGroupName = TestUtilities.GenerateName("csmrg");
            var resourceName = TestUtilities.GenerateName("csmr");
            var createResult = client.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location });
            var createResourceResult = client.Resources.CreateOrUpdate(resourceGroupName, new ResourceIdentity
                {
                    ResourceName = resourceName,
                    ResourceProviderNamespace = "Microsoft.Web",
                    ResourceType = "sites",
                    ResourceProviderApiVersion = "2014-04-01"
                },
                new GenericResource
                    {
                        Location = location,
                        Properties = "{'name':'" + resourceName + "','siteMode': 'Standard','computeMode':'Shared'}"
                    });
            var deleteResult = client.ResourceGroups.Delete(resourceGroupName);
            var listGroupsResult = client.ResourceGroups.List(null);

            Assert.Throws<CloudException>(() => client.Resources.List(new ResourceListParameters
                {
                    ResourceGroupName = resourceGroupName
                }));

            Assert.Equal(HttpStatusCode.OK, deleteResult.StatusCode);
            Assert.False(listGroupsResult.ResourceGroups.Any(rg => rg.Name == resourceGroupName));
            TestUtilities.EndTest();
        }
        public void ProviderListValidateMessage()
        {
            TestUtilities.StartTest();
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetResourceManagementClient(handler);

            var reg = client.Providers.Register(ProviderName);
            Assert.NotNull(reg);
            Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, reg.StatusCode);

            var result = client.Providers.List(null);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate result
            Assert.True(result.Providers.Any());
            var websiteProvider =
                result.Providers.First(
                    p => p.Namespace.Equals(ProviderName, StringComparison.InvariantCultureIgnoreCase));
            Assert.Equal(ProviderName, websiteProvider.Namespace);
            Assert.True(ProviderRegistrationState.Registered == websiteProvider.RegistrationState ||
                ProviderRegistrationState.Registering == websiteProvider.RegistrationState,
                string.Format("Provider registration state was not 'Registered' or 'Registering', instead it was '{0}'", websiteProvider.RegistrationState));
            Assert.NotEmpty(websiteProvider.ResourceTypes);
            Assert.NotEmpty(websiteProvider.ResourceTypes[0].Locations);
            TestUtilities.EndTest();
        }
        public void StorageAccountDeleteTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (var context = UndoContext.Current)
            {
                context.Start();

                var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(handler);

                // Create resource group
                var rgname = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Delete an account which does not exist
                var deleteRequest = storageMgmtClient.StorageAccounts.Delete(rgname, "missingaccount");

                // Create storage account
                string accountName = StorageManagementTestUtilities.CreateStorageAccount(storageMgmtClient, rgname);

                // Delete an account
                deleteRequest = storageMgmtClient.StorageAccounts.Delete(rgname, accountName);

                // Delete an account which was just deleted
                deleteRequest = storageMgmtClient.StorageAccounts.Delete(rgname, accountName);
            }
        }
        public FeatureClient GetFeatureClient(RecordedDelegatingHandler handler)
        {
            var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
            handler.IsPassThrough = false;
            var client = new FeatureClient(token).WithHandler(handler);

            HttpMockServer.Mode = HttpRecorderMode.Playback;
            return client;
        }
 public static StorageManagementClient GetStorageManagementClient(RecordedDelegatingHandler handler)
 {
     if (IsTestTenant)
     {
         return new StorageManagementClient(GetCreds(), testUri);
     }
     else
     {
         handler.IsPassThrough = true;
         return TestBase.GetServiceClient<StorageManagementClient>(new CSMTestEnvironmentFactory()).WithHandler(handler);
     }
 }
 public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = true;
     var client = this.GetResourceManagementClient();
     client = client.WithHandler(handler);
     if (HttpMockServer.Mode == HttpRecorderMode.Playback)
     {
         client.LongRunningOperationInitialTimeout = 0;
         client.LongRunningOperationRetryTimeout = 0;
     }
     return client;
 }
 public static ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
 {
     if (IsTestTenant)
     {
         ResourceManagementClient resourcesClient = new ResourceManagementClient(GetCreds());
         return resourcesClient;
     }
     else
     {
         handler.IsPassThrough = true;
         return TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory()).WithHandler(handler);
     }
 }
示例#12
0
        public void UsageTest()
        {
            var handler = new RecordedDelegatingHandler {StatusCodeToReturn = HttpStatusCode.OK};

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/networkSecurityGroups");
                
                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                    new ResourceGroup
                    {
                        Location = location
                    });

                string networkSecurityGroupName = TestUtilities.GenerateName();

                var networkSecurityGroup = new NetworkSecurityGroup()
                {
                    Location = location,
                };

                // Put Nsg
                var putNsgResponse = networkResourceProviderClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);
                Assert.Equal(HttpStatusCode.OK, putNsgResponse.StatusCode);
                Assert.Equal("Succeeded", putNsgResponse.Status);

                var getNsgResponse = networkResourceProviderClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                Assert.Equal(HttpStatusCode.OK, getNsgResponse.StatusCode);

                // Query for usages
                var usagesResponse = networkResourceProviderClient.Usages.List(getNsgResponse.NetworkSecurityGroup.Location.Replace(" ", string.Empty));
                Assert.True(usagesResponse.StatusCode == HttpStatusCode.OK);

                // Verify that the strings are populated
                Assert.NotNull(usagesResponse.Usages);
                Assert.True(usagesResponse.Usages.Any());

                foreach (var usage in usagesResponse.Usages)
                {
                    Assert.True(usage.Limit > 0);
                    Assert.NotNull(usage.Name);
                    Assert.True(!string.IsNullOrEmpty(usage.Name.LocalizedValue));
                    Assert.True(!string.IsNullOrEmpty(usage.Name.Value));
                }
            }
        }
        public void CreateDummyDeploymentTemplateWorks()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };

            var dictionary = new Dictionary<string, object> {
                    {"string", new Dictionary<string, object>() {
                        {"value", "myvalue"},
                    }},
                    {"securestring", new Dictionary<string, object>() {
                        {"value", "myvalue"},
                    }},
                    {"int", new Dictionary<string, object>() {
                        {"value", 42},
                    }},
                    {"bool", new Dictionary<string, object>() {
                        {"value", true},
                    }}
                };
            var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling = TypeNameHandling.None
            });

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetResourceManagementClient(handler);
                var parameters = new Deployment
                {
                    Properties = new DeploymentProperties()
                    {
                        TemplateLink = new TemplateLink
                        {
                            Uri = new Uri(DummyTemplateUri)
                        },
                        Parameters = serializedDictionary,
                        Mode = DeploymentMode.Incremental,
                    }
                };

                string groupName = TestUtilities.GenerateName("csmrg");
                string deploymentName = TestUtilities.GenerateName("csmd");
                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });
                client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);

                JObject json = JObject.Parse(handler.Request);

                Assert.Equal(HttpStatusCode.OK, client.Deployments.Get(groupName, deploymentName).StatusCode);
            }
        }
        public void ListSubscriptionWorksWithNextLink()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'value': [
                          {
                        'id':'/subscriptions/38b598fc-e57a-423f-b2e7-dc0ddb631f1f',
                        'subscriptionId': '38b598fc-e57a-423f-b2e7-dc0ddb631f1f',
                        'displayName':'test-release-3',
                        'state': 'Enabled',
                        'subscriptionPolicies':
                            {
                                'locationPlacementId':'Public_2014-09-01',
                                'quotaId':'MSDN'
                            }
                          }
                        ],
                    'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw'
                    }
                ")
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetSubscriptionClient(handler);

            var result = client.Subscriptions.List();

            response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'value': []
                    }")
            };

            handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            client = GetSubscriptionClient(handler);

            result = client.Subscriptions.ListNext(result.NextLink);

            // Validate body
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
            Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", handler.Uri.ToString());

            // Validate response
            Assert.Equal(null, result.NextLink);
        }
        public void ResourceGroupCreateOrUpdateValidateMessage()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio',
                    'name': 'foo',
                    'location': 'WestEurope',
                    'tags' : {
                        'department':'finance',
                        'tagname':'tagvalue'
                    },
                    'properties': {
                        'provisioningState': 'Succeeded'
                      }
                }")
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetResourceManagementClient(handler);

            var result = client.ResourceGroups.CreateOrUpdate("foo", new ResourceGroup
            {
                Location = "WestEurope",
                Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
            });

            JObject json = JObject.Parse(handler.Request);

            // Validate headers
            Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
            Assert.Equal(HttpMethod.Put, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate payload
            Assert.Equal("WestEurope", json["location"].Value<string>());
            Assert.Equal("finance", json["tags"]["department"].Value<string>());
            Assert.Equal("tagvalue", json["tags"]["tagname"].Value<string>());

            // Validate response
            Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.ResourceGroup.Id);
            Assert.Equal("Succeeded", result.ResourceGroup.ProvisioningState);
            Assert.Equal("foo", result.ResourceGroup.Name);
            Assert.Equal("finance", result.ResourceGroup.Tags["department"]);
            Assert.Equal("tagvalue", result.ResourceGroup.Tags["tagname"]);
            Assert.Equal("WestEurope", result.ResourceGroup.Location);
        }
        public void CRUDResourceGroupLock()
        {
            var handler = new RecordedDelegatingHandler();

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetAuthorizationClient(handler);

                string resourceGroupName = "myRG";
                string lockName = TestUtilities.GenerateName("mylock");
                string lockType = "Microsoft.Authorization/locks";
                var lockProperties = new ManagementLockProperties()
                {
                    Level = "CanNotDelete",
                    Notes = "optional text."
                };
               
               // 1 Create lock
                var createResult1 = client.ManagementLocks.CreateOrUpdateAtResourceGroupLevel(resourceGroupName, lockName, lockProperties);

                Assert.Equal(HttpStatusCode.Created, createResult1.StatusCode);
                Assert.Equal(lockName, createResult1.ManagementLock.Name);
                Assert.Equal(lockProperties.Level, createResult1.ManagementLock.Properties.Level);
                Assert.Equal(lockProperties.Notes, createResult1.ManagementLock.Properties.Notes);
                Assert.Equal(lockType, createResult1.ManagementLock.Type);

                // 2 Get all RG locks with no filter
                var getResult1 = client.ManagementLocks.ListResourceGroupLevel(resourceGroupName, new ManagementLockGetQueryParameter { AtScope = "" });

                Assert.Equal(HttpStatusCode.OK, getResult1.StatusCode);
                Assert.True(getResult1.Lock.Count > 0);
                Assert.True(getResult1.Lock.Any(p => p.Name == lockName));

                // Get all subscription level locks with filter
                var getResult2 = client.ManagementLocks.ListResourceGroupLevel(resourceGroupName, new ManagementLockGetQueryParameter() { AtScope = "atScope()" });

                Assert.Equal(HttpStatusCode.OK, getResult2.StatusCode);
                Assert.True(getResult2.Lock.Count == 1);
                Assert.True(getResult2.Lock.Any(p => p.Name == lockName));

                //Delete lock
                var deleteResult = client.ManagementLocks.DeleteAtResourceGroupLevel(resourceGroupName,lockName);
                Assert.Equal(HttpStatusCode.OK, deleteResult.StatusCode);
            }
        }
        public void StorageAccountCreateTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (var context = UndoContext.Current)
            {
                context.Start();

                var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(handler);

                // Create resource group
                var rgname = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                StorageAccountCreateParameters parameters = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                var createRequest = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters);

                Assert.Equal(createRequest.StorageAccount.Location, StorageManagementTestUtilities.DefaultLocation);
                Assert.Equal(createRequest.StorageAccount.AccountType, AccountType.StandardGRS);
                Assert.Equal(createRequest.StorageAccount.Tags.Count, 2);

                // Make sure a second create returns immediately
                createRequest = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters);
                Assert.Equal(createRequest.StatusCode, HttpStatusCode.OK);

                Assert.Equal(createRequest.StorageAccount.Location, StorageManagementTestUtilities.DefaultLocation);
                Assert.Equal(createRequest.StorageAccount.AccountType, AccountType.StandardGRS);
                Assert.Equal(createRequest.StorageAccount.Tags.Count, 2);

                // Create storage account with only required params
                accountName = TestUtilities.GenerateName("sto");
                parameters = new StorageAccountCreateParameters
                {
                    AccountType = AccountType.StandardGRS,
                    Location = StorageManagementTestUtilities.DefaultLocation
                };
                createRequest = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters);

                Assert.Equal(createRequest.StorageAccount.Location, StorageManagementTestUtilities.DefaultLocation);
                Assert.Equal(createRequest.StorageAccount.AccountType, AccountType.StandardGRS);
                Assert.Empty(createRequest.StorageAccount.Tags);
            }
        }
        public void StorageAccountBeginCreateTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (var context = UndoContext.Current)
            {
                context.Start();

                var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(handler);
                var storageMgmtClient = StorageManagementTestUtilities.GetStorageManagementClient(handler);

                // Create resource group
                var rgname = StorageManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create storage account
                string accountName = TestUtilities.GenerateName("sto");
                StorageAccountCreateParameters parameters = StorageManagementTestUtilities.GetDefaultStorageAccountParameters();
                StorageAccountCreateResponse response = storageMgmtClient.StorageAccounts.BeginCreate(rgname, accountName, parameters);
                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                // Poll for creation
                while (response.StatusCode == HttpStatusCode.Accepted)
                {
                    TestUtilities.Wait(response.RetryAfter * 1000);
                    response = storageMgmtClient.GetCreateOperationStatus(response.OperationStatusLink);
                }

                // Verify create succeeded
                StorageAccount result = response.StorageAccount;
                Assert.Equal(result.Location, StorageManagementTestUtilities.DefaultLocation);
                Assert.Equal(result.AccountType, AccountType.StandardGRS);
                Assert.Equal(result.Tags.Count, 2);

                // Make sure a second create returns immediately
                response = storageMgmtClient.StorageAccounts.BeginCreate(rgname, accountName, parameters);
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                // Verify create succeeded
                Assert.Equal(result.Location, StorageManagementTestUtilities.DefaultLocation);
                Assert.Equal(result.AccountType, AccountType.StandardGRS);
                Assert.Equal(result.Tags.Count, 2);
            }
        }
        public void CheckDnsAvailabilityTest()
        {
            var handler = new RecordedDelegatingHandler {StatusCodeToReturn = HttpStatusCode.OK};

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var location = GetNrpServiceEndpoint(NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"));

                string domainNameLabel = TestUtilities.GenerateName("domainnamelabel");

                var dnsNameAvailability = networkResourceProviderClient.CheckDnsNameAvailability(location, domainNameLabel);

                Assert.True(dnsNameAvailability.DnsNameAvailability);
            }
        }
        public FeatureClient GetFeatureClient(RecordedDelegatingHandler handler)
        {
            //var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
            //handler.IsPassThrough = false;
            ////FeatureClientDiscoveryExtensions.CreateCloudServiceManagementClient();
            //return new FeatureClient(token).WithHandler(handler);


            handler.IsPassThrough = true;
            var client = this.GetFeatureClient();
            client = client.WithHandler(handler);
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                client.LongRunningOperationInitialTimeout = 0;
                client.LongRunningOperationRetryTimeout = 0;
            }

            return client;
        }
        public void ExpressRouteServiceProviderTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (var context = UndoContext.Current)
            {
                context.Start();
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var listServiceProviders = networkResourceProviderClient.ExpressRouteServiceProviders.List();

                // Verify properties
                Assert.Equal(HttpStatusCode.OK, listServiceProviders.StatusCode);

                Assert.True(listServiceProviders.ExpressRouteServiceProviders.Any());
                Assert.True(listServiceProviders.ExpressRouteServiceProviders[0].PeeringLocations.Any());
                Assert.True(listServiceProviders.ExpressRouteServiceProviders[0].BandwidthsOffered.Any());
                Assert.NotNull(listServiceProviders.ExpressRouteServiceProviders[0].Name);
            }
        }
        public void ProviderGetValidateMessage()
        { 
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                   'namespace': 'Microsoft.Websites',
                   'registrationState': 'Registered',
                   'resourceTypes': [
                    {
                       'resourceType': 'sites',
                       'locations': [
                         'Central US'
                       ]
                     },
                     {
                       'resourceType': 'sites/pages',
                       'locations': [
                         'West US'
                       ]
                     }
                   ]   
                }")
            };
            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetResourceManagementClient(handler);

            var result = client.Providers.Get("Microsoft.Websites");

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate result
            Assert.Equal("Microsoft.Websites", result.Provider.Namespace);
            Assert.Equal("Registered", result.Provider.RegistrationState);
            Assert.Equal(2, result.Provider.ResourceTypes.Count);
            Assert.Equal("sites", result.Provider.ResourceTypes[0].Name);
            Assert.Equal(1, result.Provider.ResourceTypes[0].Locations.Count);
            Assert.Equal("Central US", result.Provider.ResourceTypes[0].Locations[0]);
        }
        public void CheckExistenceReturnsCorrectValue()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                string groupName = TestUtilities.GenerateName("csmrg");
                var client = GetResourceManagementClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var checkExistenceFirst = client.ResourceGroups.CheckExistence(groupName);
                Assert.False(checkExistenceFirst.Exists);

                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = DefaultLocation });

                var checkExistenceSecond = client.ResourceGroups.CheckExistence(groupName);

                Assert.True(checkExistenceSecond.Exists);
            }
        }
        public void GetSubscriptionDetails()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSubscriptionClient(handler);
                var rmclient = GetResourceManagementClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var subscriptionDetails = client.Subscriptions.Get(rmclient.Credentials.SubscriptionId);

                Assert.NotNull(subscriptionDetails);
                Assert.Equal(HttpStatusCode.OK, subscriptionDetails.StatusCode);
                Assert.NotNull(subscriptionDetails.Subscription.Id);
                Assert.NotNull(subscriptionDetails.Subscription.SubscriptionId);
                Assert.NotNull(subscriptionDetails.Subscription.DisplayName);
                Assert.NotNull(subscriptionDetails.Subscription.State);
            }
        }
        public void ListTenants()
        {
            // NEXT environment variables used to record the mock

            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSubscriptionClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var tenants = client.Tenants.List();

                Assert.NotNull(tenants);
                Assert.Equal(HttpStatusCode.OK, tenants.StatusCode);
                Assert.NotNull(tenants.TenantIds);
                Assert.NotEqual(0, tenants.TenantIds.Count());
                Assert.NotNull(tenants.TenantIds[0].Id);
                Assert.NotNull(tenants.TenantIds[0].TenantId);
            }
        }
        public void ListSubscriptions()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSubscriptionClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var subscription = client.Subscriptions.List();

                Assert.NotNull(subscription);
                Assert.Equal(HttpStatusCode.OK, subscription.StatusCode);
                Assert.NotNull(subscription.Subscriptions);
                Assert.NotEqual(0, subscription.Subscriptions.Count());
                Assert.NotNull(subscription.Subscriptions[0].Id);
                Assert.NotNull(subscription.Subscriptions[0].SubscriptionId);
                Assert.NotNull(subscription.Subscriptions[0].DisplayName);
                Assert.NotNull(subscription.Subscriptions[0].State);
            }
        }
        public void ListSubscriptionLocations()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSubscriptionClient(handler);
                var rmclient = GetResourceManagementClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var locations = client.Subscriptions.ListLocations(rmclient.Credentials.SubscriptionId);

                Assert.NotNull(locations);
                Assert.Equal(HttpStatusCode.OK, locations.StatusCode);
                Assert.NotNull(locations.Locations[0].Id);
                Assert.NotNull(locations.Locations[0].Name);
                Assert.NotNull(locations.Locations[0].DisplayName);
                Assert.NotNull(locations.Locations[0].Latitude);
                Assert.NotNull(locations.Locations[0].Longitude);
            }
        }
        public void ResourceGetValidateMessage()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                  'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Web/Sites/site1',
                  'name': 'site1',
                  'location': 'South Central US',
                   'properties': {
                        'name':'site1',
	                    'siteMode': 'Standard',
                        'computeMode':'Dedicated',
                        'provisioningState':'Running'
                    }
                }")
            };
            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetResourceManagementClient(handler);

            var result = client.Resources.Get("foo", new ResourceIdentity
            {
                ResourceName = "site1",
                ResourceProviderNamespace = "Microsoft.Web",
                ResourceProviderApiVersion = "2014-01-04",
                ResourceType = "Sites"
            });

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate result
            Assert.Equal("South Central US", result.Resource.Location);
            Assert.Equal("site1", result.Resource.Name);
            Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Web/Sites/site1", result.Resource.Id);
            Assert.True(result.Resource.Properties.Contains("Dedicated"));
            Assert.Equal("Running", result.Resource.ProvisioningState);
        }
        public void CleanupAllResources()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetResourceManagementClient(handler);
                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                var groups = client.ResourceGroups.List(null);
                foreach (var group in groups.ResourceGroups)
                {
                    TracingAdapter.Information("Deleting resources for RG {0}", group.Name);
                    var resources = client.Resources.List(new ResourceListParameters { ResourceGroupName = group.Name, ResourceType = "Microsoft.Web/sites" });
                    foreach (var resource in resources.Resources)
                    {
                        var response = client.Resources.Delete(group.Name, CreateResourceIdentity(resource));
                    }
                    var groupResponse = client.ResourceGroups.BeginDeleting(group.Name);
                }
            }
        }
        public void CheckExistenceReturnsCorrectValue()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetResourceManagementClient(handler);
                string resourceName = TestUtilities.GenerateName("csmr");

                var parameters = new Deployment
                {
                    Properties = new DeploymentProperties()
                    {
                        TemplateLink = new TemplateLink
                        {
                            Uri = new Uri(GoodWebsiteTemplateUri),
                        },
                        Parameters =
                            @"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}",
                        Mode = DeploymentMode.Incremental,
                    }
                };
                string groupName = TestUtilities.GenerateName("csmrg");
                string deploymentName = TestUtilities.GenerateName("csmd");
                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "West Europe" });

                var checkExistenceFirst = client.Deployments.CheckExistence(groupName, deploymentName);
                Assert.False(checkExistenceFirst.Exists);

                var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);

                var checkExistenceSecond = client.Deployments.CheckExistence(groupName, deploymentName);

                Assert.True(checkExistenceSecond.Exists);
            }
        }
        public void WhatIf_ReceivingResponse_DeserializesResult()
        {
            // Arrange.
            var deploymentWhatIf = new DeploymentWhatIf(new DeploymentWhatIfProperties());
            var response         = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'status': 'Succeeded',
                    'properties': {
                        'changes': [
                            {
                                'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                'changeType': 'Modify',
                                'before': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2'
                                },
                                'after': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2',
                                    'tags': {
                                        'myNewTag': 'my tag value'
                                    }
                                },
                                'delta': [
                                    {
                                        'path': 'tags.myNewTag',
                                        'propertyChangeType': 'Create',
                                        'after': 'my tag value'
                                    }
                                ]
                            }
                        ]
                    }
                }")
            };
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (ResourceManagementClient client = CreateResourceManagementClient(handler))
            {
                // Act.
                WhatIfOperationResult result = client.Deployments.WhatIf("test-rg", "test-deploy", deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.Equal(1, result.Changes.Count);

                WhatIfChange change = result.Changes[0];
                Assert.Equal(ChangeType.Modify, change.ChangeType);

                Assert.NotNull(change.Before);
                Assert.Equal("myExistingIdentity", JToken.FromObject(change.Before)["name"]);

                Assert.NotNull(change.After);
                Assert.Equal("myExistingIdentity", JToken.FromObject(change.After)["name"]);

                Assert.NotNull(change.Delta);
                Assert.Equal(1, change.Delta.Count);
                Assert.Equal("tags.myNewTag", change.Delta[0].Path);
                Assert.Equal(PropertyChangeType.Create, change.Delta[0].PropertyChangeType);
                Assert.Equal("my tag value", change.Delta[0].After);
            }
        }
        public void GetPreviewedFeatures()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{                    
                       
                    'name': 'Providers.Test/DONOTDELETEBETA',

                    'properties': {

                    'state': 'NotRegistered'

                     },

                    'id': '/subscriptions/fda3b6ba-8803-441c-91fb-6cc798cf6ea0/providers/Microsoft.Features/providers/Providers.Test/features/DONOTDELETEBETA',

                    'type': 'Microsoft.Features/providers/features'  
              
              }
            ")
            };

            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var client = GetFeatureClient(handler);

            string resourceProviderNamespace = "Providers.Test";

            string featureName = "DONOTDELETEBETA";

            // ----Verify API calls for get all features under current subid----
            var getResult = client.Features.Get(resourceProviderNamespace, featureName);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            //Valid payload
            //Construct expected URL
            string expectedUrl = "/subscriptions/" + Uri.EscapeDataString(client.Credentials.SubscriptionId) + "/providers/Microsoft.Features/providers/" + Uri.EscapeDataString(resourceProviderNamespace) + "/features/" + Uri.EscapeDataString(featureName) + "?";

            expectedUrl = expectedUrl + "api-version=2015-12-01";
            string baseUrl = client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (expectedUrl[0] == '/')
            {
                expectedUrl = expectedUrl.Substring(1);
            }
            expectedUrl = baseUrl + "/" + expectedUrl;
            expectedUrl = expectedUrl.Replace(" ", "%20");

            Assert.Equal(expectedUrl, handler.Uri.ToString());

            // Valid response
            Assert.Equal(getResult.StatusCode, HttpStatusCode.OK);
            //-------------
        }
        public void ListAllPreviewedFeatures()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{                    
            'value': [
                    {
                    'name': 'Providers.Test/DONOTDELETEBETA',

                    'properties': {

                    'state': 'NotRegistered'

                     },

                    'id': '/subscriptions/fda3b6ba-8803-441c-91fb-6cc798cf6ea0/providers/Microsoft.Features/providers/Providers.Test/features/DONOTDELETEBETA',

                    'type': 'Microsoft.Features/providers/features'   
                }            
                ],
              'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw'
              }
            ")
            };
            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = GetFeatureClient(handler);

            //-------------Verify get all features within a resource provider
            var getResult = client.Features.ListAll();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            //Valid payload
            //Construct expected URL
            string expectedUrl = "/subscriptions/" + Uri.EscapeDataString(client.Credentials.SubscriptionId) + "/providers/Microsoft.Features/features?";

            expectedUrl = expectedUrl + "api-version=2015-12-01";
            string baseUrl = client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (expectedUrl[0] == '/')
            {
                expectedUrl = expectedUrl.Substring(1);
            }
            expectedUrl = baseUrl + "/" + expectedUrl;
            expectedUrl = expectedUrl.Replace(" ", "%20");

            Assert.Equal(expectedUrl, handler.Uri.ToString());

            // Valid response
            Assert.Equal(getResult.StatusCode, HttpStatusCode.OK);
            // Assert.Equal(getResult.Features.First(), new FeatureOperationsListResult(new FeatureResponse());
        }
示例#34
0
        public void CreateDummyDeploymentProducesOperations()
        {
            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.Created
            };
            var dictionary = new Dictionary <string, object> {
                { "string", new Dictionary <string, object>()
                  {
                      { "value", "myvalue" },
                  } },
                { "securestring", new Dictionary <string, object>()
                  {
                      { "value", "myvalue" },
                  } },
                { "int", new Dictionary <string, object>()
                  {
                      { "value", 42 },
                  } },
                { "bool", new Dictionary <string, object>()
                  {
                      { "value", true },
                  } }
            };
            var serializedDictionary = JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client     = GetResourceManagementClient(handler);
                var parameters = new Deployment
                {
                    Properties = new DeploymentProperties()
                    {
                        TemplateLink = new TemplateLink
                        {
                            Uri = new Uri(DummyTemplateUri)
                        },
                        Parameters = serializedDictionary,
                        Mode       = DeploymentMode.Incremental,
                    }
                };

                string groupName      = TestUtilities.GenerateName("csmrg");
                string deploymentName = TestUtilities.GenerateName("csmd");
                string resourceName   = TestUtilities.GenerateName("csmr");

                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup {
                    Location = "West Europe"
                });
                client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);

                // Wait until deployment completes
                TestUtilities.Wait(30000);
                var operations = client.DeploymentOperations.List(groupName, deploymentName, null);

                Assert.True(operations.Operations.Any());
                Assert.NotNull(operations.Operations[0].Id);
                Assert.NotNull(operations.Operations[0].OperationId);
                Assert.NotNull(operations.Operations[0].Properties);
            }
        }
 public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = true;
     return(this.GetResourceManagementClientWithHandler(context, handler));
 }
示例#36
0
 public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = true;
     return(this.GetResourceManagementClient().WithHandler(handler));
 }
示例#37
0
        public void ResourceLinkList()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'value': [
                        {
                            'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
                            'name': 'myLink',
                            'properties': {
                                'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
                                'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
                                'notes': 'myLinkNotes'
                              }
                         },
                         {
                            'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount/providers/Microsoft.Resources/links/myLink2',
                            'name': 'myLink2',
                            'properties': {
                                'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount',
                                'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount2',
                                'notes': 'myLinkNotes2'
                              }
                         }],
                      'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
                }")
            };

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = GetManagementLinkClient(handler);

            var result = client.ResourceLinks.ListAtSubscription();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate result
            Assert.Equal(2, result.Count());
            Assert.Equal("myLink", result.First().Name);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.First().Id);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.First().Properties.SourceId);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.First().Properties.TargetId);
            Assert.Equal("myLinkNotes", result.First().Properties.Notes);
            Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", result.NextPageLink);

            // Filter by targetId

            var filteredResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'value': [
                        {
                            'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
                            'name': 'myLink',
                            'properties': {
                                'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
                                'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
                                'notes': 'myLinkNotes'
                              }
                         }],
                      'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
                }")
            };

            var filteredHandler = new RecordedDelegatingHandler(filteredResponse)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            client = GetManagementLinkClient(filteredHandler);
            var filteredResult = client.ResourceLinks.ListAtSubscription(new ODataQuery <ResourceLinkFilter>(f => f.TargetId == "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2"));

            // Validate result
            Assert.Single(filteredResult);
            Assert.Equal("myLink", filteredResult.First().Name);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", filteredResult.First().Id);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", filteredResult.First().Properties.SourceId);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", filteredResult.First().Properties.TargetId);
            Assert.Equal("myLinkNotes", filteredResult.First().Properties.Notes);
            Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", filteredResult.NextPageLink);
        }
示例#38
0
        public void ResourceLinkCRUD()
        {
            var response = new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = new StringContent(@"{
                    'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
                    'name': 'myLink',
                    'properties': {
                        'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
                        'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
                        'notes': 'myLinkNotes'
                      }
                }")
            };

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.Created
            };
            var client = GetManagementLinkClient(handler);

            var result = client.ResourceLinks.CreateOrUpdate(
                linkId: "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink",
                parameters: new ResourceLink
            {
                Properties = new ResourceLinkProperties
                {
                    TargetId = "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2",
                    Notes    = "myLinkNotes"
                }
            });

            JObject json = JObject.Parse(handler.Request);

            // Validate headers
            Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
            Assert.Equal(HttpMethod.Put, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate payload
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", json["properties"]["targetId"].Value <string>());
            Assert.Equal("myLinkNotes", json["properties"]["notes"].Value <string>());

            // Validate response
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.Id);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.Properties.SourceId);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.Properties.TargetId);
            Assert.Equal("myLinkNotes", result.Properties.Notes);
            Assert.Equal("myLink", result.Name);

            //Get resource link and validate properties

            var getResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
                    'name': 'myLink',
                    'properties': {
                        'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
                        'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
                        'notes': 'myLinkNotes'
                      }
                }")
            };

            var getHandler = new RecordedDelegatingHandler(getResponse)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            client = GetManagementLinkClient(getHandler);
            var getResult = client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");

            // Validate response
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", getResult.Id);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", getResult.Properties.SourceId);
            Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", getResult.Properties.TargetId);
            Assert.Equal("myLinkNotes", getResult.Properties.Notes);
            Assert.Equal("myLink", getResult.Name);

            //Delete resource link
            var deleteResponse = new HttpResponseMessage(HttpStatusCode.OK);

            deleteResponse.Headers.Add("x-ms-request-id", "1");
            var deleteHandler = new RecordedDelegatingHandler(deleteResponse)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            client = GetManagementLinkClient(deleteHandler);

            client.ResourceLinks.Delete("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");

            // Validate headers
            Assert.Equal(HttpMethod.Delete, deleteHandler.Method);

            // Get a deleted link throws exception
            Assert.Throws <CloudException>(() => client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink"));
        }
示例#39
0
        public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue()
        {
            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                string groupName          = TestUtilities.GenerateName("csmrg");
                string resourceName       = TestUtilities.GenerateName("csmr");
                string resourceNameNoTags = TestUtilities.GenerateName("csmr");
                string tagName            = TestUtilities.GenerateName("csmtn");
                string tagValue           = TestUtilities.GenerateName("csmtv");
                var    client             = GetResourceManagementClient(context, handler);
                string location           = GetWebsiteLocation(client);

                client.SetRetryPolicy(new RetryPolicy <HttpStatusCodeErrorDetectionStrategy>(1));

                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup {
                    Location = this.ResourceGroupLocation
                });
                client.Resources.CreateOrUpdate(
                    groupName,
                    "Microsoft.Web",
                    "",
                    "serverFarms",
                    resourceName,
                    WebResourceProviderVersion,
                    new GenericResource
                {
                    Tags = new Dictionary <string, string> {
                        { tagName, tagValue }
                    },
                    Location = location,
                    Sku      = new Sku
                    {
                        Name = "S1"
                    },
                    Properties = JObject.Parse("{}")
                }
                    );
                client.Resources.CreateOrUpdate(
                    groupName,
                    "Microsoft.Web",
                    "",
                    "serverFarms",
                    resourceNameNoTags,
                    WebResourceProviderVersion,
                    new GenericResource
                {
                    Location = location,
                    Sku      = new Sku
                    {
                        Name = "S1"
                    },
                    Properties = JObject.Parse("{}")
                }
                    );

                var listResult = client.Resources.ListByResourceGroup(groupName,
                                                                      new ODataQuery <GenericResourceFilter>(r => r.Tagname == tagName && r.Tagvalue == tagValue));

                Assert.Single(listResult);
                Assert.Equal(resourceName, listResult.First().Name);

                var getResult = client.Resources.Get(
                    groupName,
                    "Microsoft.Web",
                    "",
                    "serverFarms",
                    resourceName,
                    WebResourceProviderVersion);

                Assert.Equal(resourceName, getResult.Name);
                Assert.True(getResult.Tags.Keys.Contains(tagName));
            }
        }
        public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
        {
            handler.IsPassThrough = true;
            var client = this.GetResourceManagementClientWithHandler(context, handler);

            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                client.LongRunningOperationRetryTimeout = 0;
            }

            return(client);
        }
        public void CreateDeploymentAndValidateProperties()
        {
            var handler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.Created
            };

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var    client       = GetResourceManagementClient(handler);
                string resourceName = TestUtilities.GenerateName("csmr");

                var parameters = new Deployment
                {
                    Properties = new DeploymentProperties()
                    {
                        TemplateLink = new TemplateLink
                        {
                            Uri = new Uri("https://raw.githubusercontent.com/vivsriaus/armtemplates/master/test3light.json"),
                        },
                        Parameters =
                            @"{ 'hostingPlanName': {'value': 'mctest0101'},'siteLocation': {'value': 'West US'}}",
                        Mode         = DeploymentMode.Incremental,
                        DebugSetting = new DeploymentDebugSetting
                        {
                            DeploymentDebugDetailLevel = "RequestContent"
                        }
                    }
                };
                string groupName      = TestUtilities.GenerateName("csmrg");
                string deploymentName = TestUtilities.GenerateName("csmd");
                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup {
                    Location = "West Europe"
                });
                var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters);

                Assert.NotNull(deploymentCreateResult.Deployment.Id);
                Assert.Equal(deploymentName, deploymentCreateResult.Deployment.Name);

                TestUtilities.Wait(1000);

                var deploymentListResult = client.Deployments.List(groupName, null);
                var deploymentGetResult  = client.Deployments.Get(groupName, deploymentName);

                Assert.NotEmpty(deploymentListResult.Deployments);
                Assert.Equal(deploymentName, deploymentGetResult.Deployment.Name);
                Assert.Equal(deploymentName, deploymentListResult.Deployments[0].Name);
                Assert.Equal("https://raw.githubusercontent.com/vivsriaus/armtemplates/master/test3light.json", deploymentGetResult.Deployment.Properties.TemplateLink.Uri.AbsoluteUri);
                Assert.Equal("https://raw.githubusercontent.com/vivsriaus/armtemplates/master/test3light.json", deploymentListResult.Deployments[0].Properties.TemplateLink.Uri.AbsoluteUri);
                Assert.NotNull(deploymentGetResult.Deployment.Properties.ProvisioningState);
                Assert.NotNull(deploymentListResult.Deployments[0].Properties.ProvisioningState);
                Assert.NotNull(deploymentGetResult.Deployment.Properties.CorrelationId);
                Assert.NotNull(deploymentListResult.Deployments[0].Properties.CorrelationId);
                Assert.True(deploymentGetResult.Deployment.Properties.Parameters.Contains("mctest0101"));
                Assert.True(deploymentListResult.Deployments[0].Properties.Parameters.Contains("mctest0101"));
                Assert.Equal("RequestContent", deploymentGetResult.Deployment.Properties.DebugSetting.DeploymentDebugDetailLevel);
                //stop the deployment
                if (deploymentGetResult.Deployment.Properties.ProvisioningState.Equals("Running") ||
                    deploymentGetResult.Deployment.Properties.ProvisioningState.Equals("Accepted"))
                {
                    client.Deployments.Cancel(groupName, deploymentName);
                }
                TestUtilities.Wait(2000);

                //Delete deployment
                Assert.Equal(HttpStatusCode.NoContent, client.Deployments.Delete(groupName, deploymentName).StatusCode);
            }
        }
示例#42
0
        public void ListSubscriptions()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
	                'value': [{
		                'id': '/subscriptions/38b598fc-e57a-423f-b2e7-dc0ddb631f1f',
		                'subscriptionId': '38b598fc-e57a-423f-b2e7-dc0ddb631f1f',
		                'displayName': 'Visual Studio Ultimate with MSDN',
		                'state': 'Disabled',
		                'subscriptionPolicies': {
			                'locationPlacementId': 'Public_2014-09-01',
			                'quotaId': 'MSDN_2014-09-01'
		                }
	                },
	                {
		                'id': '/subscriptions/9167af2d-c13e-4d34-9a57-8f37dba6ff31',
		                'subscriptionId': '9167af2d-c13e-4d34-9a57-8f37dba6ff31',
		                'displayName': 'Subscription-1',
		                'state': 'Enabled',
		                'subscriptionPolicies': {
			                'locationPlacementId': 'Internal_2014-09-01',
			                'quotaId': 'Internal_2014-09-01'
		                }
	                },
	                {
		                'id': '/subscriptions/78814224-3c2d-4932-9fe3-913da0f278ee',
		                'subscriptionId': '78814224-3c2d-4932-9fe3-913da0f278ee',
		                'displayName': 'Cloud Tools Development',
		                'state': 'Enabled',
		                'subscriptionPolicies': {
			                'locationPlacementId': 'Internal_2014-09-01',
			                'quotaId': 'Internal_2014-09-01'
		                }
	                }]
                }")
            };

            response.Headers.Add("x-ms-request-id", "1");

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var client = GetSubscriptionClient(handler);

            var listSubscriptionsResult = client.Subscriptions.List();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            // Validate result
            Assert.NotNull(listSubscriptionsResult);
            Assert.Equal("/subscriptions/38b598fc-e57a-423f-b2e7-dc0ddb631f1f", listSubscriptionsResult.FirstOrDefault().Id);
            Assert.Equal("38b598fc-e57a-423f-b2e7-dc0ddb631f1f", listSubscriptionsResult.FirstOrDefault().SubscriptionId);
            Assert.Equal("Visual Studio Ultimate with MSDN", listSubscriptionsResult.FirstOrDefault().DisplayName);
            Assert.Equal("Disabled", listSubscriptionsResult.FirstOrDefault().State);
            Assert.NotNull(listSubscriptionsResult.FirstOrDefault().SubscriptionPolicies);
            Assert.Equal("Public_2014-09-01", listSubscriptionsResult.FirstOrDefault().SubscriptionPolicies.LocationPlacementId);
            Assert.Equal("MSDN_2014-09-01", listSubscriptionsResult.FirstOrDefault().SubscriptionPolicies.QuotaId);
        }