/// <summary>
        /// Creates a new environment.
        /// </summary>
        /// <param name="environment">Configuration information for the new environment.</param>
        /// <returns>Information regarding the new environment.</returns>
        public async Task <CreatePowerAppsEnvironmentResponse> CreateEnvironmentAsync(CreatePowerAppsEnvironmentRequest environment)
        {
            LogInformation($"Looking for existing PowerApps environment named '{environment.Properties.DisplayName}'...");
            PowerAppsEnvironment findEnvironment = await GetEnvironmentByDisplayNameAsync(environment.Properties.DisplayName);

            if (findEnvironment != null)
            {
                LogInformation($"PowerApps environment named '{environment.Properties.DisplayName}' already exists.");

                return(new CreatePowerAppsEnvironmentResponse()
                {
                    Id = findEnvironment.Id,
                    Name = findEnvironment.Name,
                    Type = findEnvironment.Type,
                    Location = findEnvironment.Location,
                    Properties = findEnvironment.Properties,
                });
            }

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

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

            LogInformation($"Creating PowerApps environment named '{environment.Properties.DisplayName}' in location '{environment.Location}' with SKU '{environment.Properties.EnvironmentSku}'...");
            HttpResponseMessage response = await httpClient.PostAsync(
                _newEnvironmentUri,
                body);

            CreatePowerAppsEnvironmentResponse result = null;

            if (response.IsSuccessStatusCode)
            {
                result = JsonConvert.DeserializeObject <CreatePowerAppsEnvironmentResponse>(await response.Content.ReadAsStringAsync());
            }
            else
            {
                LogError($"ERROR: ({response.StatusCode}) {response.ReasonPhrase}");
                throw new RequestException(response);
            }

            return(result);
        }
        public void CreateEnvironmentAsyncSuccess()
        {
            string expectedEnvironmentName = Guid.NewGuid().ToString();
            string expectedLocation        = "unitedstates";
            string expectedDisplayName     = "TestEnvironment";
            string expectedSku             = "Trial";
            string expectedRequestUri      = $"https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments?$filter=properties.displayName%20eq%20'{expectedDisplayName}'&api-version=2016-11-01";
            string expectedRequestUri2     = "https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/environments?api-version=2018-01-01&id=/providers/Microsoft.BusinessAppPlatform/scopes/admin/environments";
            string responseFilePath        = @"./data/templates/responses/powerApps/emptyValueResponse.json";
            string responseFilePath2       = @"./data/templates/responses/powerApps/environment.json";

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

            _httpClient.RegisterExpectedRequest(new ExpectedRequest(expectedRequest));
            HttpRequestMessage expectedRequest2 = TestHelper.CreateHttpRequest(
                HttpMethod.Post,
                expectedRequestUri2);

            _httpClient.RegisterExpectedRequest(new ExpectedRequest(expectedRequest2));

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

            _httpClient.RegisterExpectedResponse(
                expectedRequestUri,
                new ExpectedResponse(expectedResponse));
            HttpResponseMessage expectedResponse2 = TestHelper.CreateHttpResponse(
                HttpStatusCode.OK,
                null,
                responseFilePath2,
                "application/json",
                new Dictionary <string, string>()
            {
                { "environmentName", expectedEnvironmentName },
                { "location", expectedLocation },
                { "displayName", expectedDisplayName },
            });

            _httpClient.RegisterExpectedResponse(
                expectedRequestUri2,
                new ExpectedResponse(expectedResponse2));

            IPowerAppsClient client = new PowerAppsClient(_tokenProvider);

            CreatePowerAppsEnvironmentRequest powerAppsEnv = new CreatePowerAppsEnvironmentRequest()
            {
                Location   = expectedLocation,
                Properties = new NewPowerAppsEnvironmentProperties()
                {
                    DisplayName    = expectedDisplayName,
                    EnvironmentSku = expectedSku,
                },
            };

            CreatePowerAppsEnvironmentResponse response = client.CreateEnvironmentAsync(powerAppsEnv).Result;

            Assert.IsNotNull(response, "The response should not be null!");
            Assert.IsNotNull(response.Properties, "The response Properties member should not be null!");
            Assert.AreEqual(expectedEnvironmentName, response.Name, $"Unexpected name ('{expectedEnvironmentName}' != '{response.Name}')");
            Assert.AreEqual(expectedLocation, response.Location, $"Unexpected location ('{expectedLocation}' != '{response.Location}')");
            Assert.AreEqual(expectedDisplayName, response.Properties.DisplayName, $"Unexpected location ('{expectedDisplayName}' != '{response.Properties.DisplayName}')");
            Assert.AreEqual(expectedDisplayName, response.Properties.DisplayName, $"Unexpected location ('{expectedDisplayName}' != '{response.Properties.DisplayName}')");
            Assert.IsNotNull(response.Properties.LinkedEnvironmentMetadata, "The response Properties.LinkedEnvironmentMetadata member should not be null!");
        }
Beispiel #3
0
        private void QueueOperations()
        {
            Feature powerAppsEnvironment = DataModel.InstallationConfiguration.Features[$"{FeatureNames.UIComponents}\\{FeatureNames.PowerAppsDynamics365CRM}\\{FeatureNames.PowerAppsEnvironment}"];

            if (powerAppsEnvironment.ShouldInstall)
            {
                SequentialRunner.Operations.Enqueue(new Operation()
                {
                    Name = "CreatePowerAppsEnvironment",
                    OperationFunction         = CreatePowerAppsEnvironmentAsync,
                    OperationCompletedHandler = (result) =>
                    {
                        CreatePowerAppsEnvironmentResponse response = (CreatePowerAppsEnvironmentResponse)result;

                        if (response != null)
                        {
                            DataModel.InstallationConfiguration.PowerApps.SelectedEnvironment = new PowerAppsEnvironment()
                            {
                                DisplayName     = response.Properties.DisplayName,
                                EnvironmentName = response.Name,
                            };
                        }
                    },
                    ValidateFunction = (context) =>
                    {
                        return(context.LastOperationStatusCode == 0);
                    },
                    ExceptionHandler = (ex) =>
                    {
                        DataModel.StatusMessage = "Failed to create PowerApps environment!";
                    },
                });
            }

            Feature powerAppsCdsDatabase = DataModel.InstallationConfiguration.Features[$"{FeatureNames.UIComponents}\\{FeatureNames.PowerAppsDynamics365CRM}\\{FeatureNames.CommonDataServiceDatabase}"];

            if (powerAppsCdsDatabase.ShouldInstall)
            {
                SequentialRunner.Operations.Enqueue(new Operation()
                {
                    Name = "CreatePowerAppsCdsDatabase",
                    OperationFunction         = CreatePowerAppsCdsDatabaseAsync,
                    OperationCompletedHandler = (result) =>
                    {
                        Contract.PowerAppsEnvironment response = (Contract.PowerAppsEnvironment)result;

                        if (response != null)
                        {
                            DataModel.InstallationConfiguration.PowerApps.Environments = new List <PowerAppsEnvironment>();

                            DataModel.InstallationConfiguration.PowerApps.Environments.Add(new PowerAppsEnvironment()
                            {
                                EnvironmentName        = response.Name,
                                DisplayName            = response.Properties.DisplayName,
                                OrganizationName       = response.Properties.LinkedEnvironmentMetadata.UniqueName,
                                OrganizationDomainName = response.Properties.LinkedEnvironmentMetadata.DomainName,
                                WebApplicationUrl      = response.Properties.LinkedEnvironmentMetadata.InstanceUrl,
                            });
                        }
                    },
                    ValidateFunction = (context) =>
                    {
                        return(context.LastOperationStatusCode == 0);
                    },
                    ExceptionHandler = (ex) =>
                    {
                        DataModel.StatusMessage = "Failed to deploy PowerApps CDS database!";
                    },
                });
            }

            DataModel.OperationsProgress.Operations = SequentialRunner.Operations
                                                      .Select(x => new OperationStatus()
            {
                Id         = x.Id,
                Name       = x.Name,
                StatusCode = OperationStatusCode.NotStarted,
            })
                                                      .ToList();
        }