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

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

                AzureOperationResponse registerResult = client.Providers.Register(ProviderName);

                Assert.Equal(HttpStatusCode.OK, registerResult.StatusCode);

                ProviderGetResult provider = client.Providers.Get(ProviderName);
                Assert.True(provider.Provider.RegistrationState == ProviderRegistrationState.Registered ||
                            provider.Provider.RegistrationState == ProviderRegistrationState.Registering);

                AzureOperationResponse unregisterResult = client.Providers.Unregister(ProviderName);

                Assert.Equal(HttpStatusCode.OK, unregisterResult.StatusCode);

                provider = client.Providers.Get(ProviderName);
                Assert.True(provider.Provider.RegistrationState == ProviderRegistrationState.NotRegistered ||
                            provider.Provider.RegistrationState == ProviderRegistrationState.Unregistering,
                            "RegistrationState is expected NotRegistered or Unregistering. Actual value " +
                            provider.Provider.RegistrationState);
            }
        }
示例#2
0
        public ResourceGroupFixture()
        {
            ResourceManagementClient client =
                TestBase.GetServiceClient <ResourceManagementClient>(new CSMTestEnvironmentFactory());

            // Register subscription
            AzureOperationResponse registerResponse = client.Providers.Register(SearchNamespace);

            Assert.Equal(HttpStatusCode.OK, registerResponse.StatusCode);

            // Get a valid location for search services.
            ProviderGetResult providerResult = client.Providers.Get(SearchNamespace);

            Assert.Equal(HttpStatusCode.OK, providerResult.StatusCode);

            // We only support one resource type.
            Location = providerResult.Provider.ResourceTypes.First().Locations.First();

            // Create resource group
            ResourceGroupName = TestUtilities.GenerateName();
            ResourceGroupCreateOrUpdateResult resourceGroupResult =
                client.ResourceGroups.CreateOrUpdate(ResourceGroupName, new ResourceGroup(Location));

            Assert.Equal(HttpStatusCode.Created, resourceGroupResult.StatusCode);
        }
        public void DoesNotHangForLongRegistrationCalls()
        {
            // Setup
            Mock <ResourceManagementClient> mockClient = new Mock <ResourceManagementClient>();
            Mock <IProviderOperations>      mockProvidersOperations = new Mock <IProviderOperations>();

            mockClient.Setup(f => f.Providers).Returns(mockProvidersOperations.Object);
            mockProvidersOperations.Setup(f => f.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(
                (string rp, CancellationToken token) =>
            {
                ProviderGetResult r = new ProviderGetResult
                {
                    Provider = new Provider
                    {
                        RegistrationState = RegistrationState.Pending.ToString()
                    }
                };

                return(Task.FromResult(r));
            }
                );
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, compatibleUri);
            Dictionary <HttpRequestMessage, List <HttpResponseMessage> > mapping = new Dictionary <HttpRequestMessage, List <HttpResponseMessage> >
            {
                {
                    request, new List <HttpResponseMessage>
                    {
                        new HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            Content = new StringContent("registered to use namespace")
                        },
                        new HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            Content = new StringContent("registered to use namespace")
                        }
                    }
                }
            };
            List <string> msgs = new List <string>();
            RPRegistrationDelegatingHandler rpHandler = new RPRegistrationDelegatingHandler(() => mockClient.Object, s => msgs.Add(s))
            {
                InnerHandler = new MockResponseDelegatingHandler(mapping)
            };
            HttpClient httpClient = new HttpClient(rpHandler);

            // Test
            HttpResponseMessage response = httpClient.SendAsync(request).Result;

            // Assert
            Assert.True(msgs.Any(s => s.Equals("Failed to register resource provider 'microsoft.compute'.Details: 'The operation has timed out.'")));
            Assert.Equal(response.StatusCode, HttpStatusCode.Conflict);
            Assert.Equal(response.Content.ReadAsStringAsync().Result, "registered to use namespace");
            mockProvidersOperations.Verify(f => f.RegisterAsync("microsoft.compute", It.IsAny <CancellationToken>()), Times.AtMost(4));
        }
示例#4
0
        /// <summary>
        /// Obtains a list of locations via the specified <see cref="Microsoft.Azure.Management.Resources.IResourceManagementClient"/>
        /// and prompts the user to select a location from the list.
        /// </summary>
        /// <param name="resourceManagementClient">The <see cref="Microsoft.Azure.Management.Resources.IResourceManagementClient"/>
        /// to use when obtaining a list of datacenter locations.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        private static async Task <string> PromptUserForLocationAsync(IResourceManagementClient resourceManagementClient)
        {
            // Obtain the list of available datacenter locations for Batch accounts supported by this subscription
            ProviderGetResult batchProvider = await resourceManagementClient.Providers.GetAsync(BatchNameSpace);

            ProviderResourceType batchResource = batchProvider.Provider.ResourceTypes.Where(p => p.Name == BatchAccountResourceType).First();

            string[] locations = batchResource.Locations.ToArray();

            // Ask the user where they would like to create the resource group and account
            return(PromptForSelectionFromCollection(locations, "Enter the number of the location where you'd like to create your Batch account: "));
        }
        public void InvokeRegistrationForUnregisteredResourceProviders()
        {
            // Setup
            Mock <ResourceManagementClient> mockClient = new Mock <ResourceManagementClient>();
            Mock <IProviderOperations>      mockProvidersOperations = new Mock <IProviderOperations>();

            mockClient.Setup(f => f.Providers).Returns(mockProvidersOperations.Object);
            mockProvidersOperations.Setup(f => f.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns(
                (string rp, CancellationToken token) =>
            {
                ProviderGetResult r = new ProviderGetResult
                {
                    Provider = new Provider
                    {
                        RegistrationState = RegistrationState.Registered.ToString()
                    }
                };

                return(Task.FromResult(r));
            }
                );
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, compatibleUri);
            Dictionary <HttpRequestMessage, List <HttpResponseMessage> > mapping = new Dictionary <HttpRequestMessage, List <HttpResponseMessage> >
            {
                {
                    request, new List <HttpResponseMessage>
                    {
                        new HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            Content = new StringContent("registered to use namespace")
                        },
                        new HttpResponseMessage(HttpStatusCode.Accepted)
                        {
                            Content = new StringContent("Azure works!")
                        }
                    }
                }
            };
            List <string> msgs = new List <string>();
            RPRegistrationDelegatingHandler rpHandler = new RPRegistrationDelegatingHandler(() => mockClient.Object, s => msgs.Add(s))
            {
                InnerHandler = new MockResponseDelegatingHandler(mapping)
            };
            HttpClient httpClient = new HttpClient(rpHandler);

            // Test
            HttpResponseMessage response = httpClient.SendAsync(request).Result;

            // Assert
            Assert.True(msgs.Any(s => s.Equals("Succeeded to register resource provider 'microsoft.compute'")));
            Assert.Equal(response.StatusCode, HttpStatusCode.Accepted);
            Assert.Equal(response.Content.ReadAsStringAsync().Result, "Azure works!");
        }
        /// <summary>
        /// Gets a resource provider.
        /// </summary>
        /// <param name='resourceProviderNamespace'>
        /// Required. Namespace of the resource provider.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Resource provider information.
        /// </returns>
        public async Task <ProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceProviderNamespace == null)
            {
                throw new ArgumentNullException("resourceProviderNamespace");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/providers/" + Uri.EscapeDataString(resourceProviderNamespace) + "?";

            url = url + "api-version=2014-04-01-preview";
            string baseUrl = this.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 (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ProviderGetResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ProviderGetResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            Provider providerInstance = new Provider();
                            result.Provider = providerInstance;

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                providerInstance.Id = idInstance;
                            }

                            JToken namespaceValue = responseDoc["namespace"];
                            if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                            {
                                string namespaceInstance = ((string)namespaceValue);
                                providerInstance.Namespace = namespaceInstance;
                            }

                            JToken registrationStateValue = responseDoc["registrationState"];
                            if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                            {
                                string registrationStateInstance = ((string)registrationStateValue);
                                providerInstance.RegistrationState = registrationStateInstance;
                            }

                            JToken resourceTypesArray = responseDoc["resourceTypes"];
                            if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                            {
                                foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                {
                                    ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                    providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                    JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                    if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                    {
                                        string resourceTypeInstance = ((string)resourceTypeValue);
                                        providerResourceTypeInstance.Name = resourceTypeInstance;
                                    }

                                    JToken locationsArray = resourceTypesValue["locations"];
                                    if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken locationsValue in ((JArray)locationsArray))
                                        {
                                            providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }