Esempio n. 1
0
        public static AuthenticationSettingsContract ToAuthenticationSettings(PsApiManagementApi psApiManagementApi)
        {
            if (psApiManagementApi == null)
            {
                return(null);
            }

            if (!string.IsNullOrWhiteSpace(psApiManagementApi.AuthorizationServerId) ||
                !string.IsNullOrEmpty(psApiManagementApi.AuthorizationScope))
            {
                var settings = new AuthenticationSettingsContract()
                {
                    OAuth2 = new OAuth2AuthenticationSettingsContract()
                    {
                        AuthorizationServerId = psApiManagementApi.AuthorizationServerId,
                        Scope = psApiManagementApi.AuthorizationScope
                    }
                };

                return(settings);
            }
            else if (!string.IsNullOrWhiteSpace(psApiManagementApi.OpenidProviderId) ||
                     (psApiManagementApi.BearerTokenSendingMethod != null && psApiManagementApi.BearerTokenSendingMethod.Any()))
            {
                var settings = new AuthenticationSettingsContract()
                {
                    Openid = new OpenIdAuthenticationSettingsContract()
                    {
                        OpenidProviderId          = psApiManagementApi.OpenidProviderId,
                        BearerTokenSendingMethods = psApiManagementApi.BearerTokenSendingMethod
                    }
                };

                return(settings);
            }

            return(null);
        }
Esempio n. 2
0
        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);

                    // TODO: list next page as soon as rewrite URLs goes to dogfood.
                    //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.NotNull(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();
            }
        }
        /// <summary>
        /// List all Product APIs.
        /// </summary>
        /// <param name='nextLink'>
        /// Required. NextLink from the previous successful call to List
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Api operations response details.
        /// </returns>
        public async Task <ApiListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

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

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

            // Construct URL
            string url = "";

            url = url + nextLink;
            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
                    ApiListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            ApiPaged resultInstance = new ApiPaged();
                            result.Result = resultInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    ApiContract apiContractInstance = new ApiContract();
                                    resultInstance.Values.Add(apiContractInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        apiContractInstance.IdPath = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        apiContractInstance.Name = nameInstance;
                                    }

                                    JToken descriptionValue = valueValue["description"];
                                    if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                    {
                                        string descriptionInstance = ((string)descriptionValue);
                                        apiContractInstance.Description = descriptionInstance;
                                    }

                                    JToken serviceUrlValue = valueValue["serviceUrl"];
                                    if (serviceUrlValue != null && serviceUrlValue.Type != JTokenType.Null)
                                    {
                                        string serviceUrlInstance = ((string)serviceUrlValue);
                                        apiContractInstance.ServiceUrl = serviceUrlInstance;
                                    }

                                    JToken pathValue = valueValue["path"];
                                    if (pathValue != null && pathValue.Type != JTokenType.Null)
                                    {
                                        string pathInstance = ((string)pathValue);
                                        apiContractInstance.Path = pathInstance;
                                    }

                                    JToken protocolsArray = valueValue["protocols"];
                                    if (protocolsArray != null && protocolsArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken protocolsValue in ((JArray)protocolsArray))
                                        {
                                            apiContractInstance.Protocols.Add(((ApiProtocolContract)Enum.Parse(typeof(ApiProtocolContract), ((string)protocolsValue), true)));
                                        }
                                    }

                                    JToken authenticationSettingsValue = valueValue["authenticationSettings"];
                                    if (authenticationSettingsValue != null && authenticationSettingsValue.Type != JTokenType.Null)
                                    {
                                        AuthenticationSettingsContract authenticationSettingsInstance = new AuthenticationSettingsContract();
                                        apiContractInstance.AuthenticationSettings = authenticationSettingsInstance;

                                        JToken oAuth2Value = authenticationSettingsValue["oAuth2"];
                                        if (oAuth2Value != null && oAuth2Value.Type != JTokenType.Null)
                                        {
                                            OAuth2AuthenticationSettingsContract oAuth2Instance = new OAuth2AuthenticationSettingsContract();
                                            authenticationSettingsInstance.OAuth2 = oAuth2Instance;

                                            JToken authorizationServerIdValue = oAuth2Value["authorizationServerId"];
                                            if (authorizationServerIdValue != null && authorizationServerIdValue.Type != JTokenType.Null)
                                            {
                                                string authorizationServerIdInstance = ((string)authorizationServerIdValue);
                                                oAuth2Instance.AuthorizationServerId = authorizationServerIdInstance;
                                            }

                                            JToken scopeValue = oAuth2Value["scope"];
                                            if (scopeValue != null && scopeValue.Type != JTokenType.Null)
                                            {
                                                string scopeInstance = ((string)scopeValue);
                                                oAuth2Instance.Scope = scopeInstance;
                                            }
                                        }
                                    }

                                    JToken subscriptionKeyParameterNamesValue = valueValue["subscriptionKeyParameterNames"];
                                    if (subscriptionKeyParameterNamesValue != null && subscriptionKeyParameterNamesValue.Type != JTokenType.Null)
                                    {
                                        SubscriptionKeyParameterNamesContract subscriptionKeyParameterNamesInstance = new SubscriptionKeyParameterNamesContract();
                                        apiContractInstance.SubscriptionKeyParameterNames = subscriptionKeyParameterNamesInstance;

                                        JToken headerValue = subscriptionKeyParameterNamesValue["header"];
                                        if (headerValue != null && headerValue.Type != JTokenType.Null)
                                        {
                                            string headerInstance = ((string)headerValue);
                                            subscriptionKeyParameterNamesInstance.Header = headerInstance;
                                        }

                                        JToken queryValue = subscriptionKeyParameterNamesValue["query"];
                                        if (queryValue != null && queryValue.Type != JTokenType.Null)
                                        {
                                            string queryInstance = ((string)queryValue);
                                            subscriptionKeyParameterNamesInstance.Query = queryInstance;
                                        }
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        ApiTypeContract typeInstance = ((ApiTypeContract)Enum.Parse(typeof(ApiTypeContract), ((string)typeValue), true));
                                        apiContractInstance.Type = typeInstance;
                                    }
                                }
                            }

                            JToken countValue = responseDoc["count"];
                            if (countValue != null && countValue.Type != JTokenType.Null)
                            {
                                long countInstance = ((long)countValue);
                                resultInstance.TotalCount = countInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                resultInstance.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    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();
                }
            }
        }
        /// <summary>
        /// List all Product APIs.
        /// </summary>
        /// <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='pid'>
        /// Required. Identifier of the product.
        /// </param>
        /// <param name='query'>
        /// Optional.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Api operations response details.
        /// </returns>
        public async Task <ApiListResponse> ListAsync(string resourceGroupName, string serviceName, string pid, QueryParameters query, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            if (pid == null)
            {
                throw new ArgumentNullException("pid");
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("pid", pid);
                tracingParameters.Add("query", query);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.ApiManagement";
            url = url + "/service/";
            url = url + Uri.EscapeDataString(serviceName);
            url = url + "/products/";
            url = url + Uri.EscapeDataString(pid);
            url = url + "/apis";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-10-10");
            List <string> odataFilter = new List <string>();

            if (query != null && query.Filter != null)
            {
                odataFilter.Add(Uri.EscapeDataString(query.Filter));
            }
            if (odataFilter.Count > 0)
            {
                queryParameters.Add("$filter=" + string.Join(null, odataFilter));
            }
            if (query != null && query.Top != null)
            {
                queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
            }
            if (query != null && query.Skip != null)
            {
                queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
            }
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            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
                    ApiListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            ApiPaged resultInstance = new ApiPaged();
                            result.Result = resultInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    ApiContract apiContractInstance = new ApiContract();
                                    resultInstance.Values.Add(apiContractInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        apiContractInstance.IdPath = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        apiContractInstance.Name = nameInstance;
                                    }

                                    JToken descriptionValue = valueValue["description"];
                                    if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                    {
                                        string descriptionInstance = ((string)descriptionValue);
                                        apiContractInstance.Description = descriptionInstance;
                                    }

                                    JToken serviceUrlValue = valueValue["serviceUrl"];
                                    if (serviceUrlValue != null && serviceUrlValue.Type != JTokenType.Null)
                                    {
                                        string serviceUrlInstance = ((string)serviceUrlValue);
                                        apiContractInstance.ServiceUrl = serviceUrlInstance;
                                    }

                                    JToken pathValue = valueValue["path"];
                                    if (pathValue != null && pathValue.Type != JTokenType.Null)
                                    {
                                        string pathInstance = ((string)pathValue);
                                        apiContractInstance.Path = pathInstance;
                                    }

                                    JToken protocolsArray = valueValue["protocols"];
                                    if (protocolsArray != null && protocolsArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken protocolsValue in ((JArray)protocolsArray))
                                        {
                                            apiContractInstance.Protocols.Add(((ApiProtocolContract)Enum.Parse(typeof(ApiProtocolContract), ((string)protocolsValue), true)));
                                        }
                                    }

                                    JToken authenticationSettingsValue = valueValue["authenticationSettings"];
                                    if (authenticationSettingsValue != null && authenticationSettingsValue.Type != JTokenType.Null)
                                    {
                                        AuthenticationSettingsContract authenticationSettingsInstance = new AuthenticationSettingsContract();
                                        apiContractInstance.AuthenticationSettings = authenticationSettingsInstance;

                                        JToken oAuth2Value = authenticationSettingsValue["oAuth2"];
                                        if (oAuth2Value != null && oAuth2Value.Type != JTokenType.Null)
                                        {
                                            OAuth2AuthenticationSettingsContract oAuth2Instance = new OAuth2AuthenticationSettingsContract();
                                            authenticationSettingsInstance.OAuth2 = oAuth2Instance;

                                            JToken authorizationServerIdValue = oAuth2Value["authorizationServerId"];
                                            if (authorizationServerIdValue != null && authorizationServerIdValue.Type != JTokenType.Null)
                                            {
                                                string authorizationServerIdInstance = ((string)authorizationServerIdValue);
                                                oAuth2Instance.AuthorizationServerId = authorizationServerIdInstance;
                                            }

                                            JToken scopeValue = oAuth2Value["scope"];
                                            if (scopeValue != null && scopeValue.Type != JTokenType.Null)
                                            {
                                                string scopeInstance = ((string)scopeValue);
                                                oAuth2Instance.Scope = scopeInstance;
                                            }
                                        }
                                    }

                                    JToken subscriptionKeyParameterNamesValue = valueValue["subscriptionKeyParameterNames"];
                                    if (subscriptionKeyParameterNamesValue != null && subscriptionKeyParameterNamesValue.Type != JTokenType.Null)
                                    {
                                        SubscriptionKeyParameterNamesContract subscriptionKeyParameterNamesInstance = new SubscriptionKeyParameterNamesContract();
                                        apiContractInstance.SubscriptionKeyParameterNames = subscriptionKeyParameterNamesInstance;

                                        JToken headerValue = subscriptionKeyParameterNamesValue["header"];
                                        if (headerValue != null && headerValue.Type != JTokenType.Null)
                                        {
                                            string headerInstance = ((string)headerValue);
                                            subscriptionKeyParameterNamesInstance.Header = headerInstance;
                                        }

                                        JToken queryValue = subscriptionKeyParameterNamesValue["query"];
                                        if (queryValue != null && queryValue.Type != JTokenType.Null)
                                        {
                                            string queryInstance = ((string)queryValue);
                                            subscriptionKeyParameterNamesInstance.Query = queryInstance;
                                        }
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        ApiTypeContract typeInstance = ((ApiTypeContract)Enum.Parse(typeof(ApiTypeContract), ((string)typeValue), true));
                                        apiContractInstance.Type = typeInstance;
                                    }
                                }
                            }

                            JToken countValue = responseDoc["count"];
                            if (countValue != null && countValue.Type != JTokenType.Null)
                            {
                                long countInstance = ((long)countValue);
                                resultInstance.TotalCount = countInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                resultInstance.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    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();
                }
            }
        }
Esempio n. 5
0
        public async Task CloneApiUsingSourceApiId()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // add new api
                const string swaggerPath = "./Resources/SwaggerPetStoreV2.json";
                const string path        = "swaggerApi";

                string newApiAuthorizationServerId = TestUtilities.GenerateName("authorizationServerId");
                string newApiId     = TestUtilities.GenerateName("apiid");
                string swaggerApiId = TestUtilities.GenerateName("swaggerApiId");

                try
                {
                    // import API
                    string swaggerApiContent;
                    using (StreamReader reader = File.OpenText(swaggerPath))
                    {
                        swaggerApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.SwaggerJson,
                        Value  = swaggerApiContent
                    };

                    var swaggerApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        swaggerApiId,
                        apiCreateOrUpdate);

                    Assert.NotNull(swaggerApiResponse);
                    Assert.Null(swaggerApiResponse.SubscriptionRequired);
                    Assert.Equal(path, swaggerApiResponse.Path);

                    var swagerApiOperations = await testBase.client.ApiOperation.ListByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        swaggerApiResponse.Name);

                    var createAuthServerParams = new AuthorizationServerContract
                    {
                        DisplayName                = 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 List <string> {
                            GrantType.AuthorizationCode, GrantType.Implicit
                        },
                        AuthorizationMethods = new List <AuthorizationMethod?> {
                            AuthorizationMethod.POST, AuthorizationMethod.GET
                        },
                        BearerTokenSendingMethods = new List <string> {
                            BearerTokenSendingMethod.AuthorizationHeader, BearerTokenSendingMethod.Query
                        },
                        ClientId = TestUtilities.GenerateName("clientid")
                    };

                    await testBase.client.AuthorizationServer.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiAuthorizationServerId,
                        createAuthServerParams);

                    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 createdApiContract = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        new ApiCreateOrUpdateParameter
                    {
                        SourceApiId = swaggerApiResponse.Id,     // create a clone of the Swagger API created above and override the following parameters
                        DisplayName = newApiName,
                        Description = newApiDescription,
                        Path        = newApiPath,
                        ServiceUrl  = newApiServiceUrl,
                        Protocols   = new List <Protocol?> {
                            Protocol.Https, Protocol.Http
                        },
                        SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
                        {
                            Header = subscriptionKeyParametersHeader,
                            Query  = subscriptionKeyQueryStringParamName
                        },
                        AuthenticationSettings = newApiAuthenticationSettings,
                        SubscriptionRequired   = true,
                    });

                    // get new api to check it was added
                    var apiGetResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newApiId);

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

                    var newApiOperations = await testBase.client.ApiOperation.ListByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId);

                    Assert.NotNull(newApiOperations);
                    // make sure all operations got copied
                    Assert.Equal(swagerApiOperations.Count(), newApiOperations.Count());
                }
                finally
                {
                    // delete api server
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        swaggerApiId,
                        "*");

                    // delete api server
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        "*");

                    testBase.client.AuthorizationServer.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiAuthorizationServerId,
                        "*");
                }
            }
        }
Esempio n. 6
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list all the APIs
                var listResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.Null(listResponse.NextPageLink);

                var echoApi = listResponse.First();
                Assert.Equal("Echo API", echoApi.DisplayName);
                Assert.Null(echoApi.Description);
                Assert.Equal("http://echoapi.cloudapp.net/api", echoApi.ServiceUrl);
                Assert.Equal("echo", echoApi.Path);

                Assert.NotNull(echoApi.Protocols);
                Assert.Equal(1, echoApi.Protocols.Count);
                Assert.Equal(Protocol.Https, echoApi.Protocols[0]);

                // get the API by id
                var getResponse = await testBase.client.Api.GetWithHttpMessagesAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    echoApi.Name);

                Assert.NotNull(getResponse);

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

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

                // add new api

                // create autorization server
                string newApiAuthorizationServerId = TestUtilities.GenerateName("authorizationServerId");
                string newApiId       = TestUtilities.GenerateName("apiid");
                string newOpenApiId   = TestUtilities.GenerateName("openApiid");
                string openIdNoSecret = TestUtilities.GenerateName("openId");

                try
                {
                    var createAuthServerParams = new AuthorizationServerContract
                    {
                        DisplayName                = 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 List <string> {
                            GrantType.AuthorizationCode, GrantType.Implicit
                        },
                        AuthorizationMethods = new List <AuthorizationMethod?> {
                            AuthorizationMethod.POST, AuthorizationMethod.GET
                        },
                        BearerTokenSendingMethods = new List <string> {
                            BearerTokenSendingMethod.AuthorizationHeader, BearerTokenSendingMethod.Query
                        },
                        ClientId = TestUtilities.GenerateName("clientid")
                    };

                    testBase.client.AuthorizationServer.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiAuthorizationServerId,
                        createAuthServerParams);

                    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 createdApiContract = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        new ApiCreateOrUpdateParameter
                    {
                        DisplayName = newApiName,
                        Description = newApiDescription,
                        Path        = newApiPath,
                        ServiceUrl  = newApiServiceUrl,
                        Protocols   = new List <Protocol?> {
                            Protocol.Https, Protocol.Http
                        },
                        SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
                        {
                            Header = subscriptionKeyParametersHeader,
                            Query  = subscriptionKeyQueryStringParamName
                        },
                        AuthenticationSettings = newApiAuthenticationSettings
                    });

                    // get new api to check it was added
                    var apiGetResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newApiId);

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

                    // get the API Entity Tag
                    ApiGetEntityTagHeaders apiTag = testBase.client.Api.GetEntityTag(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId);

                    Assert.NotNull(apiTag);
                    Assert.NotNull(apiTag.ETag);

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

                    testBase.client.Api.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        new ApiUpdateContract
                    {
                        DisplayName            = patchedName,
                        Description            = patchedDescription,
                        Path                   = patchedPath,
                        AuthenticationSettings = new AuthenticationSettingsContract
                        {
                            OAuth2 = null
                        }
                    },
                        apiTag.ETag);

                    // get patched api to check it was patched
                    apiGetResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newApiId);

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

                    // add an api with OpenId authentication settings
                    // create a openId connect provider
                    string openIdProviderName            = TestUtilities.GenerateName("openIdName");
                    string metadataEndpoint              = testBase.GetOpenIdMetadataEndpointUrl();
                    string clientId                      = TestUtilities.GenerateName("clientId");
                    var    openIdConnectCreateParameters = new OpenidConnectProviderContract(openIdProviderName,
                                                                                             metadataEndpoint, clientId);

                    var openIdCreateResponse = testBase.client.OpenIdConnectProvider.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        openIdNoSecret,
                        openIdConnectCreateParameters);

                    Assert.NotNull(openIdCreateResponse);
                    Assert.Equal(openIdProviderName, openIdCreateResponse.DisplayName);
                    Assert.Equal(openIdNoSecret, openIdCreateResponse.Name);

                    string newOpenIdApiName                   = TestUtilities.GenerateName("apiname");
                    string newOpenIdApiDescription            = TestUtilities.GenerateName("apidescription");
                    string newOpenIdApiPath                   = "newOpenapiPath";
                    string newOpenIdApiServiceUrl             = "http://newechoapi2.cloudapp.net/api";
                    string newOpenIdAuthorizationScope        = TestUtilities.GenerateName("oauth2scope");
                    var    newnewOpenIdAuthenticationSettings = new AuthenticationSettingsContract
                    {
                        Openid = new OpenIdAuthenticationSettingsContract
                        {
                            OpenidProviderId          = openIdCreateResponse.Name,
                            BearerTokenSendingMethods = new[] { BearerTokenSendingMethods.AuthorizationHeader }
                        }
                    };

                    var createdOpenApiIdContract = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        newOpenApiId,
                        new ApiCreateOrUpdateParameter
                    {
                        DisplayName = newOpenIdApiName,
                        Description = newOpenIdApiDescription,
                        Path        = newOpenIdApiPath,
                        ServiceUrl  = newOpenIdApiServiceUrl,
                        Protocols   = new List <Protocol?> {
                            Protocol.Https, Protocol.Http
                        },
                        SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
                        {
                            Header = subscriptionKeyParametersHeader,
                            Query  = subscriptionKeyQueryStringParamName
                        },
                        AuthenticationSettings = newnewOpenIdAuthenticationSettings
                    });

                    // get new api to check it was added
                    var openApiGetResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newOpenApiId);
                    Assert.NotNull(openApiGetResponse);
                    Assert.Equal(newOpenApiId, openApiGetResponse.Name);
                    Assert.Equal(newOpenIdApiName, openApiGetResponse.DisplayName);
                    Assert.Equal(newOpenIdApiDescription, openApiGetResponse.Description);
                    Assert.Equal(newOpenIdApiPath, openApiGetResponse.Path);
                    Assert.Equal(newOpenIdApiServiceUrl, openApiGetResponse.ServiceUrl);
                    Assert.Equal(subscriptionKeyParametersHeader, openApiGetResponse.SubscriptionKeyParameterNames.Header);
                    Assert.Equal(subscriptionKeyQueryStringParamName, openApiGetResponse.SubscriptionKeyParameterNames.Query);
                    Assert.Equal(2, openApiGetResponse.Protocols.Count);
                    Assert.True(openApiGetResponse.Protocols.Contains(Protocol.Http));
                    Assert.True(openApiGetResponse.Protocols.Contains(Protocol.Https));
                    Assert.NotNull(openApiGetResponse.AuthenticationSettings.Openid);
                    Assert.Equal(openIdCreateResponse.Name, openApiGetResponse.AuthenticationSettings.Openid.OpenidProviderId);

                    // list with paging
                    listResponse = testBase.client.Api.ListByService(
                        testBase.rgName,
                        testBase.serviceName,
                        new Microsoft.Rest.Azure.OData.ODataQuery <ApiContract> {
                        Top = 1
                    });

                    Assert.NotNull(listResponse);
                    Assert.Single(listResponse);
                    Assert.NotNull(listResponse.NextPageLink);

                    listResponse = testBase.client.Api.ListByServiceNext(listResponse.NextPageLink);

                    Assert.NotNull(listResponse);
                    Assert.Single(listResponse);
                    Assert.NotNull(listResponse.NextPageLink);

                    // delete the api
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        "*");

                    // get the deleted api to make sure it was deleted
                    try
                    {
                        testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newApiId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }

                    // delete the api
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newOpenApiId,
                        "*");

                    // get the deleted api to make sure it was deleted
                    try
                    {
                        testBase.client.Api.Get(testBase.rgName, testBase.serviceName, newOpenApiId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    // delete api server
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiId,
                        "*");

                    testBase.client.AuthorizationServer.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newApiAuthorizationServerId,
                        "*");

                    // delete api server
                    testBase.client.Api.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newOpenApiId,
                        "*");

                    testBase.client.OpenIdConnectProvider.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        openIdNoSecret,
                        "*");
                }
            }
        }
        public void ApisCreateListUpdateDelete()
        {
            TestUtilities.StartTest("SmapiFunctionalTests", "ApisCreateListUpdateDelete");

            try
            {
                // list all the APIs
                var listResponse = ApiManagementClient.Apis.List(
                    ResourceGroupName,
                    ApiManagementServiceName,
                    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();
            }
        }