/// <summary>
 /// Creates new authorization server.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.IAuthorizationServersOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='authsid'>
 /// Required. Identifier of the authorization server.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update parameters.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static AzureOperationResponse Create(this IAuthorizationServersOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerCreateOrUpdateParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IAuthorizationServersOperations)s).CreateAsync(resourceGroupName, serviceName, authsid, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public void AuthorizationServersCreateListUpdateDelete()
        {
            TestUtilities.StartTest("SmapiFunctionalTests", "AuthorizationServersCreateListUpdateDelete");

            try
            {
                // list all server
                var listResponse = ApiManagementClient.AuthorizationServers.List(
                    ResourceGroupName,
                    ApiManagementServiceName,
                    null);

                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.Result);
                Assert.NotNull(listResponse.Result.Values);
                Assert.Equal(0, listResponse.Result.TotalCount);
                Assert.Equal(0, listResponse.Result.Values.Count);

                // create server
                string authsid = TestUtilities.GenerateName("authsid");
                try
                {
                    var oAuth2AuthorizationServerContract = new OAuth2AuthorizationServerContract()
                    {
                        Name = TestUtilities.GenerateName("authName"),
                        DefaultScope = TestUtilities.GenerateName("oauth2scope"),
                        AuthorizationEndpoint = "https://contoso.com/auth",
                        TokenEndpoint = "https://contoso.com/token",
                        ClientRegistrationEndpoint = "https://contoso.com/clients/reg",
                        GrantTypes = new[] {GrantTypesContract.AuthorizationCode, GrantTypesContract.Implicit, GrantTypesContract.ResourceOwnerPassword},
                        AuthorizationMethods = new[] {MethodContract.Post, MethodContract.Get},
                        BearerTokenSendingMethods = new[] {BearerTokenSendingMethodsContract.AuthorizationHeader, BearerTokenSendingMethodsContract.Query},
                        ClientId = TestUtilities.GenerateName("clientid"),
                        Description = TestUtilities.GenerateName("authdescription"),
                        ClientAuthenticationMethod = new[] {ClientAuthenticationMethodContract.Basic},
                        ClientSecret = TestUtilities.GenerateName("authclientsecret"),
                        ResourceOwnerPassword = TestUtilities.GenerateName("authresourceownerpwd"),
                        ResourceOwnerUsername = TestUtilities.GenerateName("authresourceownerusername"),
                        SupportState = true,
                        TokenBodyParameters = new[]
                        {
                            new TokenBodyParameterContract
                            {
                                Name = TestUtilities.GenerateName("tokenname"),
                                Value = TestUtilities.GenerateName("tokenvalue")
                            }
                        }
                    };
                    var createParameters = new AuthorizationServerCreateOrUpdateParameters(oAuth2AuthorizationServerContract);
                    var createResponse = ApiManagementClient.AuthorizationServers.Create(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        authsid,
                        createParameters);

                    Assert.NotNull(createResponse);

                    // get to check is was created
                    var getResponse = ApiManagementClient.AuthorizationServers.Get(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        authsid);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.ETag);
                    Assert.NotNull(getResponse.Value);

                    Assert.Equal(authsid, getResponse.Value.Id);
                    Assert.Equal(oAuth2AuthorizationServerContract.Name, getResponse.Value.Name);
                    Assert.Equal(oAuth2AuthorizationServerContract.Description, getResponse.Value.Description);
                    Assert.Equal(oAuth2AuthorizationServerContract.DefaultScope, getResponse.Value.DefaultScope);
                    Assert.Equal(oAuth2AuthorizationServerContract.AuthorizationEndpoint, getResponse.Value.AuthorizationEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.TokenEndpoint, getResponse.Value.TokenEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientId, getResponse.Value.ClientId);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientRegistrationEndpoint, getResponse.Value.ClientRegistrationEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientSecret, getResponse.Value.ClientSecret);
                    Assert.Equal(oAuth2AuthorizationServerContract.ResourceOwnerPassword, getResponse.Value.ResourceOwnerPassword);
                    Assert.Equal(oAuth2AuthorizationServerContract.ResourceOwnerUsername, getResponse.Value.ResourceOwnerUsername);
                    Assert.Equal(oAuth2AuthorizationServerContract.GrantTypes.Count, getResponse.Value.GrantTypes.Count);
                    Assert.True(getResponse.Value.GrantTypes.All(gt => oAuth2AuthorizationServerContract.GrantTypes.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.AuthorizationMethods.Count, getResponse.Value.AuthorizationMethods.Count);
                    Assert.True(getResponse.Value.AuthorizationMethods.All(gt => oAuth2AuthorizationServerContract.AuthorizationMethods.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientAuthenticationMethod.Count, getResponse.Value.ClientAuthenticationMethod.Count);
                    Assert.True(getResponse.Value.ClientAuthenticationMethod.All(gt => oAuth2AuthorizationServerContract.ClientAuthenticationMethod.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.SupportState, getResponse.Value.SupportState);
                    Assert.Equal(oAuth2AuthorizationServerContract.TokenBodyParameters.Count, getResponse.Value.TokenBodyParameters.Count);
                    Assert.True(getResponse.Value.TokenBodyParameters.All(p => oAuth2AuthorizationServerContract.TokenBodyParameters.Any(p1 => p1.Name.Equals(p.Name, StringComparison.OrdinalIgnoreCase) && p1.Value.Equals(p.Value, StringComparison.OrdinalIgnoreCase))));

                    // list again
                    listResponse = ApiManagementClient.AuthorizationServers.List(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        null);

                    Assert.NotNull(listResponse);
                    Assert.NotNull(listResponse.Result);
                    Assert.NotNull(listResponse.Result.Values);
                    Assert.Equal(1, listResponse.Result.TotalCount);
                    Assert.Equal(1, listResponse.Result.Values.Count);

                    // update
                    oAuth2AuthorizationServerContract = new OAuth2AuthorizationServerContract
                    {
                        Name = TestUtilities.GenerateName("authName"),
                        DefaultScope = TestUtilities.GenerateName("oauth2scope"),
                        AuthorizationEndpoint = "https://contoso.com/auth1",
                        TokenEndpoint = "https://contoso.com/token1",
                        ClientRegistrationEndpoint = "https://contoso.com/clients/reg1",
                        GrantTypes = new[] {GrantTypesContract.AuthorizationCode, GrantTypesContract.ResourceOwnerPassword},
                        AuthorizationMethods = new[] {MethodContract.Get},
                        BearerTokenSendingMethods = new[] {BearerTokenSendingMethodsContract.AuthorizationHeader},
                        ClientId = TestUtilities.GenerateName("clientid"),
                        Description = TestUtilities.GenerateName("authdescription"),
                        ClientAuthenticationMethod = new[] {ClientAuthenticationMethodContract.Basic},
                        ClientSecret = TestUtilities.GenerateName("authclientsecret"),
                        ResourceOwnerPassword = TestUtilities.GenerateName("authresourceownerpwd"),
                        ResourceOwnerUsername = TestUtilities.GenerateName("authresourceownerusername"),
                        SupportState = true,
                        TokenBodyParameters = new[]
                        {
                            new TokenBodyParameterContract
                            {
                                Name = TestUtilities.GenerateName("tokenname"),
                                Value = TestUtilities.GenerateName("tokenvalue")
                            }
                        }
                    };
                    var updateParameters = new AuthorizationServerCreateOrUpdateParameters(oAuth2AuthorizationServerContract);
                    var updateResponse = ApiManagementClient.AuthorizationServers.Update(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        authsid,
                        updateParameters,
                        getResponse.ETag);

                    Assert.NotNull(updateResponse);

                    // get to check is was updated
                    getResponse = ApiManagementClient.AuthorizationServers.Get(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        authsid);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.ETag);
                    Assert.NotNull(getResponse.Value);

                    Assert.Equal(authsid, getResponse.Value.Id);
                    Assert.Equal(oAuth2AuthorizationServerContract.Name, getResponse.Value.Name);
                    Assert.Equal(oAuth2AuthorizationServerContract.Description, getResponse.Value.Description);
                    Assert.Equal(oAuth2AuthorizationServerContract.DefaultScope, getResponse.Value.DefaultScope);
                    Assert.Equal(oAuth2AuthorizationServerContract.AuthorizationEndpoint, getResponse.Value.AuthorizationEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.TokenEndpoint, getResponse.Value.TokenEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientId, getResponse.Value.ClientId);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientRegistrationEndpoint, getResponse.Value.ClientRegistrationEndpoint);
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientSecret, getResponse.Value.ClientSecret);
                    Assert.Equal(oAuth2AuthorizationServerContract.ResourceOwnerPassword, getResponse.Value.ResourceOwnerPassword);
                    Assert.Equal(oAuth2AuthorizationServerContract.ResourceOwnerUsername, getResponse.Value.ResourceOwnerUsername);
                    Assert.Equal(oAuth2AuthorizationServerContract.GrantTypes.Count, getResponse.Value.GrantTypes.Count);
                    Assert.True(getResponse.Value.GrantTypes.All(gt => oAuth2AuthorizationServerContract.GrantTypes.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.AuthorizationMethods.Count, getResponse.Value.AuthorizationMethods.Count);
                    Assert.True(getResponse.Value.AuthorizationMethods.All(gt => oAuth2AuthorizationServerContract.AuthorizationMethods.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.ClientAuthenticationMethod.Count, getResponse.Value.ClientAuthenticationMethod.Count);
                    Assert.True(getResponse.Value.ClientAuthenticationMethod.All(gt => oAuth2AuthorizationServerContract.ClientAuthenticationMethod.Contains(gt)));
                    Assert.Equal(oAuth2AuthorizationServerContract.SupportState, getResponse.Value.SupportState);
                    Assert.Equal(oAuth2AuthorizationServerContract.TokenBodyParameters.Count, getResponse.Value.TokenBodyParameters.Count);
                    Assert.True(getResponse.Value.TokenBodyParameters.All(p => oAuth2AuthorizationServerContract.TokenBodyParameters.Any(p1 => p1.Name.Equals(p.Name, StringComparison.OrdinalIgnoreCase) && p1.Value.Equals(p.Value, StringComparison.OrdinalIgnoreCase))));
                }
                finally
                {
                    // delete
                    ApiManagementClient.AuthorizationServers.Delete(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        authsid,
                        "*");

                    // get to check is was deleted
                    try
                    {
                        ApiManagementClient.AuthorizationServers.Get(
                            ResourceGroupName,
                            ApiManagementServiceName,
                            authsid);

                        throw new Exception("This code should not have been executed.");
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
            }
            finally
            {
                TestUtilities.EndTest();
            }
        } 
 /// <summary>
 /// Creates new authorization server.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.ApiManagement.IAuthorizationServersOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='serviceName'>
 /// Required. The name of the Api Management service.
 /// </param>
 /// <param name='authsid'>
 /// Required. Identifier of the authorization server.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update parameters.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<AzureOperationResponse> CreateAsync(this IAuthorizationServersOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerCreateOrUpdateParameters parameters)
 {
     return operations.CreateAsync(resourceGroupName, serviceName, authsid, parameters, CancellationToken.None);
 }
        public void ApisCreateListUpdateDelete()
        {
            TestUtilities.StartTest("SmapiFunctionalTests", "ApisCreateListUpdateDelete");

            try
            {
                // list all the APIs
                var listResponse = ApiManagementClient.Apis.List(
                    ResourceGroupName,
                    ApiManagementServiceName,
                    null);

                // there should be 'Echo API' which is created by default for every new instance of :
                /*
                {  
                   "value":[  
                      {  
                         "id":"/apis/5515969a0a6a4406e8040001",
                         "name":"Echo API",
                         "description":null,
                         "serviceUrl":"http://echoapi.cloudapp.net/api",
                         "path":"echo",
                         "protocols":[  
                            "https"
                         ],
                         "authenticationSettings":null,
                         "subscriptionKeyParameterNames":null
                      }
                   ],
                   "count":1,
                   "nextLink":null
                }
                */

                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.Result.Values);
                Assert.Equal(1, listResponse.Result.TotalCount);
                Assert.Equal(1, listResponse.Result.Values.Count);
                Assert.Null(listResponse.Result.NextLink);

                Assert.Equal("Echo API", listResponse.Result.Values[0].Name);
                Assert.Null(listResponse.Result.Values[0].Description);
                Assert.Equal("http://echoapi.cloudapp.net/api", listResponse.Result.Values[0].ServiceUrl);
                Assert.Equal("echo", listResponse.Result.Values[0].Path);

                Assert.NotNull(listResponse.Result.Values[0].Protocols);
                Assert.Equal(1, listResponse.Result.Values[0].Protocols.Count);
                Assert.Equal(ApiProtocolContract.Https, listResponse.Result.Values[0].Protocols[0]);

                // get the API by id
                var getResponse = ApiManagementClient.Apis.Get(
                    ResourceGroupName,
                    ApiManagementServiceName,
                    listResponse.Result.Values[0].Id);

                Assert.NotNull(getResponse);
                Assert.NotNull(getResponse.Value);

                Assert.Equal("Echo API", getResponse.Value.Name);
                Assert.Null(getResponse.Value.Description);
                Assert.Equal("http://echoapi.cloudapp.net/api", getResponse.Value.ServiceUrl);
                Assert.Equal("echo", getResponse.Value.Path);

                Assert.NotNull(getResponse.Value.Protocols);
                Assert.Equal(1, getResponse.Value.Protocols.Count);
                Assert.Equal(ApiProtocolContract.Https, getResponse.Value.Protocols[0]);

                // add new api

                // create autorization server
                string newApiAuthorizationServerId = TestUtilities.GenerateName("authorizationServerId");
                try
                {
                    var createAuthServerParams = new AuthorizationServerCreateOrUpdateParameters(
                        new OAuth2AuthorizationServerContract
                        {
                            Name = TestUtilities.GenerateName("authName"),
                            DefaultScope = TestUtilities.GenerateName("oauth2scope"),
                            AuthorizationEndpoint = "https://contoso.com/auth",
                            TokenEndpoint = "https://contoso.com/token",
                            ClientRegistrationEndpoint = "https://contoso.com/clients/reg",
                            GrantTypes = new[] {GrantTypesContract.AuthorizationCode, GrantTypesContract.Implicit},
                            AuthorizationMethods = new[] {MethodContract.Post, MethodContract.Get},
                            BearerTokenSendingMethods = new[] {BearerTokenSendingMethodsContract.AuthorizationHeader, BearerTokenSendingMethodsContract.Query},
                            ClientId = TestUtilities.GenerateName("clientid")
                        });
                    ApiManagementClient.AuthorizationServers.Create(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        newApiAuthorizationServerId,
                        createAuthServerParams);

                    string newApiId = TestUtilities.GenerateName("apiid");
                    string newApiName = TestUtilities.GenerateName("apiname");
                    string newApiDescription = TestUtilities.GenerateName("apidescription");
                    string newApiPath = "newapiPath";
                    string newApiServiceUrl = "http://newechoapi.cloudapp.net/api";
                    string subscriptionKeyParametersHeader = TestUtilities.GenerateName("header");
                    string subscriptionKeyQueryStringParamName = TestUtilities.GenerateName("query");
                    string newApiAuthorizationScope = TestUtilities.GenerateName("oauth2scope");
                    var newApiAuthenticationSettings = new AuthenticationSettingsContract
                    {
                        OAuth2 = new OAuth2AuthenticationSettingsContract
                        {
                            AuthorizationServerId = newApiAuthorizationServerId,
                            Scope = newApiAuthorizationScope
                        }
                    };

                    var createResponse = ApiManagementClient.Apis.CreateOrUpdate(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        newApiId,
                        new ApiCreateOrUpdateParameters(
                            new ApiContract
                            {
                                Name = newApiName,
                                Description = newApiDescription,
                                Path = newApiPath,
                                ServiceUrl = newApiServiceUrl,
                                Protocols = new[] {ApiProtocolContract.Https, ApiProtocolContract.Http},
                                SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
                                {
                                    Header = subscriptionKeyParametersHeader,
                                    Query = subscriptionKeyQueryStringParamName
                                },
                                AuthenticationSettings = newApiAuthenticationSettings
                            }),
                        null
                        );

                    Assert.NotNull(createResponse);
                    Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode);

                    // get new api to check it was added
                    getResponse = ApiManagementClient.Apis.Get(ResourceGroupName, ApiManagementServiceName, newApiId);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.Value);
                    Assert.Equal(newApiId, getResponse.Value.Id);
                    Assert.Equal(newApiName, getResponse.Value.Name);
                    Assert.Equal(newApiDescription, getResponse.Value.Description);
                    Assert.Equal(newApiPath, getResponse.Value.Path);
                    Assert.Equal(newApiServiceUrl, getResponse.Value.ServiceUrl);
                    Assert.Equal(subscriptionKeyParametersHeader, getResponse.Value.SubscriptionKeyParameterNames.Header);
                    Assert.Equal(subscriptionKeyQueryStringParamName, getResponse.Value.SubscriptionKeyParameterNames.Query);
                    Assert.Equal(2, getResponse.Value.Protocols.Count);
                    Assert.True(getResponse.Value.Protocols.Contains(ApiProtocolContract.Http));
                    Assert.True(getResponse.Value.Protocols.Contains(ApiProtocolContract.Https));
                    Assert.NotNull(getResponse.Value.AuthenticationSettings);
                    Assert.NotNull(getResponse.Value.AuthenticationSettings.OAuth2);
                    Assert.Equal(newApiAuthorizationServerId, getResponse.Value.AuthenticationSettings.OAuth2.AuthorizationServerId);

                    // patch added api
                    string patchedName = TestUtilities.GenerateName("patchedname");
                    string patchedDescription = TestUtilities.GenerateName("patchedDescription");
                    string patchedPath = TestUtilities.GenerateName("patchedPath");

                    var patchResponse = ApiManagementClient.Apis.Patch(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        newApiId,
                        new PatchParameters
                        {
                            RawJson = JsonConvert.SerializeObject(new
                            {
                                Name = patchedName,
                                Description = patchedDescription,
                                Path = patchedPath,
                                AuthenticationSettings = new AuthenticationSettingsContract
                                {
                                    OAuth2 = null
                                }
                            })
                        },
                        getResponse.ETag);

                    Assert.NotNull(patchResponse);
                    Assert.Equal(HttpStatusCode.NoContent, patchResponse.StatusCode);

                    // get patched api to check it was patched
                    getResponse = ApiManagementClient.Apis.Get(ResourceGroupName, ApiManagementServiceName, newApiId);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.Value);
                    Assert.Equal(newApiId, getResponse.Value.Id);
                    Assert.Equal(patchedName, getResponse.Value.Name);
                    Assert.Equal(patchedDescription, getResponse.Value.Description);
                    Assert.Equal(patchedPath, getResponse.Value.Path);
                    Assert.Equal(newApiServiceUrl, getResponse.Value.ServiceUrl);
                    Assert.Equal(subscriptionKeyParametersHeader, getResponse.Value.SubscriptionKeyParameterNames.Header);
                    Assert.Equal(subscriptionKeyQueryStringParamName, getResponse.Value.SubscriptionKeyParameterNames.Query);
                    Assert.Equal(2, getResponse.Value.Protocols.Count);
                    Assert.True(getResponse.Value.Protocols.Contains(ApiProtocolContract.Http));
                    Assert.True(getResponse.Value.Protocols.Contains(ApiProtocolContract.Https));

                    // list with paging
                    listResponse = ApiManagementClient.Apis.List(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        new QueryParameters {Top = 1});

                    Assert.NotNull(listResponse);
                    Assert.NotNull(listResponse.Result.Values);
                    Assert.Equal(2, listResponse.Result.TotalCount);
                    Assert.Equal(1, listResponse.Result.Values.Count);
                    Assert.NotNull(listResponse.Result.NextLink);

                    listResponse = ApiManagementClient.Apis.ListNext(listResponse.Result.NextLink);

                    Assert.NotNull(listResponse);
                    Assert.NotNull(listResponse.Result.Values);
                    Assert.Equal(2, listResponse.Result.TotalCount);
                    Assert.Equal(1, listResponse.Result.Values.Count);
                    Assert.Null(listResponse.Result.NextLink);

                    // delete the api
                    var deleteResponse = ApiManagementClient.Apis.Delete(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        newApiId,
                        "*");

                    Assert.NotNull(deleteResponse);
                    Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode);

                    // get the deleted api to make sure it was deleted
                    try
                    {
                        ApiManagementClient.Apis.Get(ResourceGroupName, ApiManagementServiceName, newApiId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    // delete authorization server
                    ApiManagementClient.AuthorizationServers.Delete(
                        ResourceGroupName,
                        ApiManagementServiceName,
                        newApiAuthorizationServerId,
                        "*");
                }
            }
            finally
            {
                TestUtilities.EndTest();
            }
        }