public void CheckServiceNameAvailability()
        {
            using (var context = UndoContext.Current)
            {
                context.Start("ResourceProviderFunctionalTests", "CheckServiceNameAvailability");

                var apiManagementClient = ApiManagementHelper.GetApiManagementClient();

                var validServiceName = TestUtilities.GenerateName("hydraapimservicevalid");
                var response =
                    apiManagementClient.ApiManagement.CheckServiceNameAvailability(
                        new ApiServiceCheckNameAvailabilityParameters(validServiceName));
                Assert.NotNull(response);
                Assert.True(response.IsAvailable);
                Assert.Null(response.Reason);

                const string invalidName = "!!!invalidname";
                response =
                    apiManagementClient.ApiManagement.CheckServiceNameAvailability(
                        new ApiServiceCheckNameAvailabilityParameters(invalidName));
                Assert.NotNull(response);
                Assert.False(response.IsAvailable);
                Assert.NotNull(response.Reason);

                // create api management service 
                var location = this.ManagmentClient.TryGetLocation("West US");
                var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location);
                if (string.IsNullOrWhiteSpace(resourceGroup))
                {
                    resourceGroup = TestUtilities.GenerateName("Api-Default");
                    this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup);
                }
                var createServiceParameters = new ApiServiceCreateOrUpdateParameters(
                    location,
                    new ApiServiceProperties
                    {
                        CreatedAtUtc = DateTime.UtcNow,
                        SkuProperties = new ApiServiceSkuProperties
                        {
                            Capacity = 1,
                            SkuType = SkuType.Developer
                        },
                        AddresserEmail = "*****@*****.**",
                        PublisherEmail = "*****@*****.**",
                        PublisherName = "publisher"
                    });

                var createResponse = apiManagementClient.ApiManagement.CreateOrUpdate(resourceGroup, validServiceName,
                    createServiceParameters);
                Assert.NotNull(createResponse);

                response =
                    apiManagementClient.ApiManagement.CheckServiceNameAvailability(
                        new ApiServiceCheckNameAvailabilityParameters(validServiceName));
                Assert.NotNull(response);
                Assert.False(response.IsAvailable);
                Assert.NotNull(response.Reason);
            }
        }
        public void ManageVirtualNetworks()
        {
            using (var context = UndoContext.Current)
            {
                context.Start("ResourceProviderFunctionalTests", "ManageVirtualNetworks");

                var location = this.ManagmentClient.TryGetLocation("West US");
                var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location);
                if (string.IsNullOrWhiteSpace(resourceGroup))
                {
                    resourceGroup = TestUtilities.GenerateName("Api-Default");
                    this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup);
                }

                this.ApiManagementClient.RefreshAccessToken();

                // create premium API Management sevice
                var serviceName = TestUtilities.GenerateName("hydraapimservice");
                var createServiceParameters = new ApiServiceCreateOrUpdateParameters(
                    location,
                    new ApiServiceProperties
                    {
                        CreatedAtUtc = DateTime.UtcNow,
                        SkuProperties = new ApiServiceSkuProperties
                        {
                            Capacity = 1,
                            SkuType = SkuType.Premium // vpn configuration is only available for premium sku
                        },
                        AddresserEmail = "*****@*****.**",
                        PublisherEmail = "*****@*****.**",
                        PublisherName = "publisher"
                    });
                var createResponse = this.ApiManagementClient.ResourceProvider.CreateOrUpdate(resourceGroup, serviceName, createServiceParameters);
                Assert.NotNull(createResponse);

                this.ApiManagementClient.RefreshAccessToken();

                // we cannot test this in any environment except prod, so just verify the data accepted
                const string vnetLocation = "East US";
                var vnetId = Guid.Parse("53F96AC5-9F46-46CE-BA0F-77DE89943258");
                const string subnetName = "Subnet-1";

                // TODO: add verification of ManageVirtualNetworks method. 
                // This functionality relies on environment. Currently there's no ability to create a vnet and get it's GUID id.
                // Let's just verify the contract at least

                try
                {
                    var result = this.ApiManagementClient.ResourceProvider.BeginManagingVirtualNetworksAsync(
                        resourceGroup,
                        serviceName,
                        new ApiServiceManageVirtualNetworksParameters
                        {
                            VirtualNetworkConfigurations = new[]
                            {
                                new VirtualNetworkConfiguration
                                {
                                    Location = vnetLocation,
                                    SubnetName = subnetName,
                                    VnetId = vnetId
                                }
                            }
                        }).Result;

                    Assert.NotNull(result);
                    Assert.NotNull(result.Error);
                }
                catch (AggregateException exc)
                {
                    Assert.NotNull(exc.InnerException);
                    Assert.True(exc.InnerException.Message.Contains("Virtual Network configuration not found for location"));
                }
            }
        }
 /// <summary>
 /// Creates new or updates existing Api Management service
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.IApiManagementOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='name'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the CreateOrUpdate Api Management
 /// service operation.
 /// </param>
 /// <returns>
 /// The response of the CreateOrUpdate Api Management service long
 /// running operation.
 /// </returns>
 public static Task<ApiServiceLongRunningOperationResponse> CreateOrUpdateAsync(this IApiManagementOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters)
 {
     return operations.CreateOrUpdateAsync(resourceGroupName, name, parameters, CancellationToken.None);
 }
 /// <summary>
 /// Creates new or updates existing Api Management service
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.IApiManagementOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='name'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the CreateOrUpdate Api Management
 /// service operation.
 /// </param>
 /// <returns>
 /// The response of the CreateOrUpdate Api Management service long
 /// running operation.
 /// </returns>
 public static ApiServiceLongRunningOperationResponse CreateOrUpdate(this IApiManagementOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IApiManagementOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public ApiManagementLongRunningOperation BeginCreateApiManagementService(
            string resourceGroupName,
            string serviceName,
            string location,
            string organization,
            string administratorEmail,
            PsApiManagementSku sku = PsApiManagementSku.Developer,
            int capacity = 1,
            IDictionary<string, string> tags = null)
        {
            var parameters = new ApiServiceCreateOrUpdateParameters
            {
                Location = location,
                Properties = new ApiServiceProperties
                {
                    SkuProperties = new ApiServiceSkuProperties
                    {
                        Capacity = capacity,
                        SkuType = MapSku(sku)
                    },
                    PublisherEmail = administratorEmail,
                    PublisherName = organization
                },
                Tags = tags
            };

            var longrunningResponse = Client.ResourceProvider.BeginCreatingOrUpdating(resourceGroupName, serviceName, parameters);
            AdjustRetryAfter(longrunningResponse, _client.LongRunningOperationInitialTimeout);
            return ApiManagementLongRunningOperation.CreateLongRunningOperation("New-AzureRmApiManagement", longrunningResponse);
        }
        public void CreateListUpdateDelete()
        {
            using (var context = UndoContext.Current)
            {
                context.Start("ResourceProviderFunctionalTests", "CreateListUpdateDelete");

                TryCreateApiService();

                this.ApiManagementClient.RefreshAccessToken();

                // get different resource group name.
                var resourceGroupName =
                    this.ResourceManagementClient.GetResourceGroups()
                        .Where(group => !group.Name.Equals(ResourceGroupName))
                        .Select(group => group.Name)
                        .FirstOrDefault();

                if (resourceGroupName == null)
                {
                    resourceGroupName = TestUtilities.GenerateName("hydraapimresourcegroup");
                }

                // create one more Api Management service (one is already created)
                var serviceName = TestUtilities.GenerateName("hydraapimservice2");
                var createServiceParameters = new ApiServiceCreateOrUpdateParameters(
                    Location,
                    new ApiServiceProperties
                    {
                        CreatedAtUtc = DateTime.UtcNow,
                        AddresserEmail = "*****@*****.**",
                        PublisherEmail = "*****@*****.**",
                        PublisherName = "publisher"
                    },
                    new ApiServiceSkuProperties
                    {
                        Capacity = 1,
                        SkuType = SkuType.Developer
                    });
                var createResponse = this.ApiManagementClient.ResourceProvider.CreateOrUpdate(resourceGroupName, serviceName, createServiceParameters);
                Assert.NotNull(createResponse);
                Assert.Equal(HttpStatusCode.OK, createResponse.StatusCode);

                var getResponse = this.ApiManagementClient.ResourceProvider.Get(resourceGroupName, serviceName);
                Assert.NotNull(getResponse);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                Assert.NotNull(getResponse.Value);
                Assert.Equal("Succeeded", getResponse.Value.Properties.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                Assert.Equal(createServiceParameters.SkuProperties.Capacity, getResponse.Value.SkuProperties.Capacity);
                Assert.Equal(createServiceParameters.SkuProperties.SkuType, getResponse.Value.SkuProperties.SkuType);
                Assert.Equal(createServiceParameters.Properties.AddresserEmail, getResponse.Value.Properties.AddresserEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherEmail, getResponse.Value.Properties.PublisherEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherName, getResponse.Value.Properties.PublisherName);
                Assert.Equal(VirtualNetworkType.None, getResponse.Value.Properties.VpnType);
                Assert.Equal(0, getResponse.Value.Tags.Count);

                this.ApiManagementClient.RefreshAccessToken();

                // list all services
                var listResponse = this.ApiManagementClient.ResourceProvider.List(null);
                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.Value);
                Assert.True(listResponse.Value.Count >= 2);
                Assert.True(listResponse.Value.Any(service => service.Name == serviceName));

                // list services only within new group
                listResponse = this.ApiManagementClient.ResourceProvider.List(resourceGroupName);
                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.Value);

                Assert.True(listResponse.Value.Count >= 1);
                Assert.True(listResponse.Value.Any(service => service.Name == serviceName));
                Assert.True(listResponse.Value.All(service => service.Id.Contains(resourceGroupName)));

                // update service: current implementation update only tags
                var updateRequest = new ApiServiceCreateOrUpdateParameters
                {
                    Location = Location,
                    Properties = new ApiServiceProperties // this should not change via update
                    {
                        AddresserEmail = "*****@*****.**",
                        PublisherEmail = "*****@*****.**",
                        PublisherName = "changed.publisher"
                    },
                    SkuProperties = new ApiServiceSkuProperties
                    {
                        Capacity = 2,
                        SkuType = SkuType.Standard
                    },
                    Tags = // only tags shoud be updated
                    {
                        {"tag1", "tag1 value"},
                        {"tag2", "tag2 value"}
                    }
                };

                var updateResponse = this.ApiManagementClient.ResourceProvider.CreateOrUpdate(resourceGroupName, serviceName,
                    updateRequest);
                Assert.NotNull(updateResponse);
                Assert.Equal(HttpStatusCode.OK, updateResponse.StatusCode);
                Assert.NotNull(updateResponse.Value);
                Assert.Equal("Succeeded", updateResponse.Value.Properties.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                Assert.Equal(updateRequest.SkuProperties.Capacity, updateResponse.Value.SkuProperties.Capacity);
                Assert.Equal(updateRequest.SkuProperties.SkuType, updateResponse.Value.SkuProperties.SkuType);
                Assert.Equal(createServiceParameters.Properties.AddresserEmail, updateResponse.Value.Properties.AddresserEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherEmail, updateResponse.Value.Properties.PublisherEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherName, updateResponse.Value.Properties.PublisherName);
                Assert.Equal(2, updateResponse.Value.Tags.Count);
                Assert.Equal(1, updateResponse.Value.Tags.Count(keyValue => keyValue.Key == "tag1" && keyValue.Value == "tag1 value"));
                Assert.Equal(1, updateResponse.Value.Tags.Count(keyValue => keyValue.Key == "tag2" && keyValue.Value == "tag2 value"));

                getResponse = this.ApiManagementClient.ResourceProvider.Get(resourceGroupName, serviceName);
                Assert.NotNull(getResponse);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                Assert.NotNull(getResponse.Value);
                Assert.Equal("Succeeded", getResponse.Value.Properties.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                Assert.Equal(updateRequest.SkuProperties.Capacity, getResponse.Value.SkuProperties.Capacity);
                Assert.Equal(updateRequest.SkuProperties.SkuType, getResponse.Value.SkuProperties.SkuType);
                Assert.Equal(createServiceParameters.Properties.AddresserEmail, getResponse.Value.Properties.AddresserEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherEmail, getResponse.Value.Properties.PublisherEmail);
                Assert.Equal(createServiceParameters.Properties.PublisherName, getResponse.Value.Properties.PublisherName);
                Assert.Equal(2, getResponse.Value.Tags.Count);
                Assert.Equal(1, getResponse.Value.Tags.Count(keyValue => keyValue.Key == "tag1" && keyValue.Value == "tag1 value"));
                Assert.Equal(1, getResponse.Value.Tags.Count(keyValue => keyValue.Key == "tag2" && keyValue.Value == "tag2 value"));

                // delete service

                ApiManagementHelper.RefreshAccessToken(this.ApiManagementClient);

                var deleteResponse = this.ApiManagementClient.ResourceProvider.Delete(resourceGroupName, serviceName);
                Assert.NotNull(deleteResponse);
                Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

                try
                {
                    this.ApiManagementClient.ResourceProvider.Get(resourceGroupName, serviceName);
                    Assert.True(false, "The code should not have been executed");
                }
                catch (CloudException ex)
                {
                    Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                }
            }
        }
 /// <summary>
 /// Begins creating new or updating existing Api Management service.To
 /// determine whether the operation has finished processing the
 /// request, call GetApiServiceLongRunningOperationStatus.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.IResourceProviderOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='name'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the CreateOrUpdate Api Management
 /// service operation.
 /// </param>
 /// <returns>
 /// The response of the CreateOrUpdate Api Management service long
 /// running operation.
 /// </returns>
 public static Task<ApiServiceLongRunningOperationResponse> BeginCreatingOrUpdatingAsync(this IResourceProviderOperations operations, string resourceGroupName, string name, ApiServiceCreateOrUpdateParameters parameters)
 {
     return operations.BeginCreatingOrUpdatingAsync(resourceGroupName, name, parameters, CancellationToken.None);
 }