public void DeleteEnvironmentAsyncSuccess()
        {
            string expectedEnvironmentName = Guid.NewGuid().ToString();
            string expectedRequestUri      = $"https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments/{expectedEnvironmentName}?api-version=2018-01-01";

            HttpRequestMessage expectedRequest = TestHelper.CreateHttpRequest(
                HttpMethod.Delete,
                expectedRequestUri);

            _httpClient.RegisterExpectedRequest(new ExpectedRequest(expectedRequest));

            HttpResponseMessage expectedResponse = TestHelper.CreateHttpResponse(
                HttpStatusCode.Accepted,
                null,
                null,
                "application/json",
                null);

            _httpClient.RegisterExpectedResponse(
                expectedRequestUri,
                new ExpectedResponse(expectedResponse));

            IPowerAppsClient client = new PowerAppsClient(_tokenProvider);

            AzureResponseBase response = client.DeleteEnvironmentAsync(expectedEnvironmentName).Result;

            Assert.IsNotNull(response, "The response should not be null!");
        }
        /// <summary>
        /// Creates a CDS database.
        /// </summary>
        /// <param name="environmentName">The name of the environment to create the CDS database in.</param>
        /// <param name="cdsDatabase">Configuration information regarding the CDS database to create.</param>
        /// <returns>The response content as an AzureResponseBase object.</returns>
        public async Task <AzureResponseBase> CreateCdsDatabaseAsync(string environmentName, CreatePowerAppsCdsDatabaseRequest cdsDatabase)
        {
            LogInformation($"Looking for existing Common Data Services database for PowerApps environment with id '{environmentName}'...");
            PowerAppsEnvironment findEnvironment = (PowerAppsEnvironment) await GetEnvironmentsAsync(environmentName);

            if (findEnvironment != null &&
                findEnvironment.Properties != null &&
                findEnvironment.Properties.LinkedEnvironmentMetadata != null)
            {
                LogInformation($"Common Data Services database for PowerApps environment with id '{environmentName}' already exists.");
                return(new AzureResponseBase()
                {
                    AlreadyExists = true,
                });
            }

            LogInformation("Acquiring access token...");
            IHttpClient httpClient = TokenProvider.GetHttpClient(Audience);

            HttpContent body = new StringContent(
                JsonConvert.SerializeObject(cdsDatabase),
                Encoding.UTF8,
                "application/json");

            LogInformation($"Creating Common Data Services database for PowerApps environment '{environmentName}'...");
            HttpResponseMessage response = await httpClient.PostAsync(
                _newCdsDatabaseUri.Replace("{environmentName}", environmentName),
                body);

            AzureResponseBase result = new AzureResponseBase();

            if (response.IsSuccessStatusCode)
            {
                if (response.Headers.Contains("Azure-AsyncOperation"))
                {
                    result.AzureAsyncOperationUri = response.Headers.GetValues("Azure-AsyncOperation").First();
                }
                else if (response.Headers.Contains("Location"))
                {
                    result.LocationUri = response.Headers.GetValues("Location").First();
                }

                if (response.Headers.Contains("Retry-After"))
                {
                    result.RetryAfter = int.Parse(response.Headers.GetValues("Retry-After").First());
                }

                await response.Content.ReadAsStringAsync();
            }
            else
            {
                LogError($"ERROR: ({response.StatusCode}) {response.ReasonPhrase}");
                throw new RequestException(response);
            }

            return(result);
        }
        /// <summary>
        /// Create a CDS database.
        /// </summary>
        /// <param name="environmentName">The name of the environment to create the CDS database in.</param>
        /// <param name="cdsDatabase">Configuration information regarding the new CDS database.</param>
        /// <returns>Information regarding the PowerApps environment after the CDS database creation.</returns>
        public PowerAppsEnvironment CreateCdsDatabase(string environmentName, CreatePowerAppsCdsDatabaseRequest cdsDatabase)
        {
            LogInformation($"Looking for existing Common Data Services database for PowerApps environment with id '{environmentName}'...");
            PowerAppsEnvironment findEnvironment = (PowerAppsEnvironment)GetEnvironmentsAsync(environmentName).Result;

            if (findEnvironment != null &&
                findEnvironment.Properties != null &&
                findEnvironment.Properties.LinkedEnvironmentMetadata != null)
            {
                LogInformation($"Common Data Services database for PowerApps environment with id '{environmentName}' already exists.");
                return(findEnvironment);
            }

            LogInformation($"Creating Common Data Services database for PowerApps environment '{environmentName}'...");
            AzureResponseBase response = CreateCdsDatabaseAsync(
                environmentName,
                cdsDatabase).Result;

            DateTime startTime   = DateTime.Now;
            DateTime currentTime = DateTime.Now;
            TimeSpan timeDiff    = currentTime - startTime;

            int timeoutInSeconds = 300;

            HttpResponseMessage httpResponse = null;

            while (httpResponse == null ||
                   (httpResponse.StatusCode != HttpStatusCode.OK &&
                    httpResponse.StatusCode != HttpStatusCode.NotFound &&
                    httpResponse.StatusCode != HttpStatusCode.InternalServerError &&
                    timeDiff.TotalSeconds < timeoutInSeconds &&
                    !response.AlreadyExists))
            {
                LogInformation("Sleeping until next poll...");
                Thread.Sleep(5000);

                LogInformation("Polling for Common Data Service database creation completion...");
                httpResponse = GetLocationAsync(Audience, new Uri(response.LocationUri)).Result;
                currentTime  = DateTime.Now;
                timeDiff     = currentTime - startTime;
            }

            LogInformation("Common Data Service database creation completed.");
            return(JsonConvert.DeserializeObject <PowerAppsEnvironment>(httpResponse.Content.ReadAsStringAsync().Result));
        }
        /// <summary>
        /// Deletes an environment.
        /// </summary>
        /// <param name="environmentName">The name of the environment to delete.</param>
        /// <returns>The response content as an AzureResponseBase content.</returns>
        public async Task <AzureResponseBase> DeleteEnvironmentAsync(string environmentName)
        {
            LogInformation("Acquiring access token...");
            IHttpClient httpClient = TokenProvider.GetHttpClient(Audience);

            LogInformation($"Deleting PowerApps environment with id '{environmentName}'...");
            HttpResponseMessage response = await httpClient.DeleteAsync(
                _deleteEnvironmentUri
                .Replace("{environmentName}", environmentName));

            AzureResponseBase result = new AzureResponseBase();

            if (response.IsSuccessStatusCode)
            {
                if (response.Headers.Contains("Azure-AsyncOperation"))
                {
                    result.AzureAsyncOperationUri = response.Headers.GetValues("Azure-AsyncOperation").First();
                }
                else if (response.Headers.Contains("Location"))
                {
                    result.LocationUri = response.Headers.GetValues("Location").First();
                }

                if (response.Headers.Contains("Retry-After"))
                {
                    result.RetryAfter = int.Parse(response.Headers.GetValues("Retry-After").First());
                }
            }
            else
            {
                LogError($"ERROR: ({response.StatusCode}) {response.ReasonPhrase}");
                throw new RequestException(response);
            }

            return(result);
        }