Esempio n. 1
0
 public static bool Check(ApiContract contract, ushort majorVersion = 1, ushort minorVersion = 0)
 {
     if (contracts.ContainsKey(contract))
     {
         return(ApiInformation.IsApiContractPresent(contracts[contract], majorVersion, minorVersion));
     }
     return(false);
 }
Esempio n. 2
0
        public void ReadContractsElementNoContent()
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(@"<ContainedApiContracts/>");
            List <ApiContract> contracts = new List <ApiContract>();

            ApiContract.ReadContractsElement(document.FirstChild as XmlElement, contracts);
            Assert.AreEqual(0, contracts.Count);
        }
Esempio n. 3
0
        public void ReadContractsElementBasicRead()
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(@"<ContainedApiContracts><ApiContract name='UAP' version='1.0.0.0' /></ContainedApiContracts>");
            List <ApiContract> contracts = new List <ApiContract>();

            ApiContract.ReadContractsElement(document.FirstChild as XmlElement, contracts);
            Assert.AreEqual(1, contracts.Count);
            Assert.AreEqual("UAP", contracts[0].Name);
            Assert.AreEqual("1.0.0.0", contracts[0].Version);
        }
Esempio n. 4
0
 void loadContract()
 {
     if (_auth.Token != null)
     {
         var cred = new TokenCredentials(_auth.Token.AccesToken);
         contract = new ApiContract(cred);
     }
     else
     {
         contract = null;
     }
 }
Esempio n. 5
0
        public void ContractMissingVersion()
        {
            string contents = @"<ApplicationPlatform name=`UAP` friendlyName=`Universal Application Platform` version=`1.0.0.0`>
                                  <DependentPlatform name=`UAP` version=`1.0.2.3` />
                                  <ContainedApiContracts>
                                    <ApiContract name=`System` />
                                  </ContainedApiContracts>
                                </ApplicationPlatform>";

            using (TemporaryPlatformManifest manifest = new TemporaryPlatformManifest(contents))
            {
                manifest.Manifest.ReadError.ShouldBeFalse();

                manifest.Manifest.DependentPlatforms.Count.ShouldBe(1);
                PlatformManifest.DependentPlatform platform = manifest.Manifest.DependentPlatforms.First();
                platform.Name.ShouldBe("UAP");
                platform.Version.ShouldBe("1.0.2.3");

                manifest.Manifest.ApiContracts.Count.ShouldBe(1);
                ApiContract contract = manifest.Manifest.ApiContracts.First();
                contract.Name.ShouldBe("System");
                contract.Version.ShouldBe(string.Empty);
            }
        }
        public void ContractMissingVersion()
        {
            string contents = @"<ApplicationPlatform name=`UAP` friendlyName=`Universal Application Platform` version=`1.0.0.0`>
                                  <DependentPlatform name=`UAP` version=`1.0.2.3` />
                                  <ContainedApiContracts>
                                    <ApiContract name=`System` />
                                  </ContainedApiContracts>
                                </ApplicationPlatform>";

            using (TemporaryPlatformManifest manifest = new TemporaryPlatformManifest(contents))
            {
                Assert.IsFalse(manifest.Manifest.ReadError);

                Assert.AreEqual(1, manifest.Manifest.DependentPlatforms.Count);
                PlatformManifest.DependentPlatform platform = manifest.Manifest.DependentPlatforms.First();
                Assert.AreEqual("UAP", platform.Name);
                Assert.AreEqual("1.0.2.3", platform.Version);

                Assert.AreEqual(1, manifest.Manifest.ApiContracts.Count);
                ApiContract contract = manifest.Manifest.ApiContracts.First();
                Assert.AreEqual("System", contract.Name);
                Assert.AreEqual(String.Empty, contract.Version);
            }
        }
    public void Formatting_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <FormatContext>();

        this.Assent(contract, _configuration);
    }
    public void Interactive_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <Kernel>();

        this.Assent(contract, _configuration);
    }
    public void kql_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <KqlKernelConnector>();

        this.Assent(contract, _configuration);
    }
        /// <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();
                }
            }
        }
    public void fsharp_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <FSharpKernel>();

        this.Assent(contract, _configuration);
    }
Esempio n. 12
0
 public void ReadContractsElementHandlesNullElement()
 {
     ApiContract.ReadContractsElement(null, new List <ApiContract>());
 }
    public void Journey_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <Lesson>();

        this.Assent(contract, _configuration);
    }
    public void Document_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <InteractiveDocument>();

        this.Assent(contract, _configuration);
    }
Esempio n. 15
0
    public void System_CommandLine_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContractForAssembly(typeof(ParseResult).Assembly);

        Approvals.Verify(contract);
    }
Esempio n. 16
0
    public void System_CommandLine_NamingConventionBinder_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContractForAssembly(typeof(ModelBindingCommandHandler).Assembly);

        Approvals.Verify(contract);
    }
Esempio n. 17
0
    public void System_CommandLine_Hosting_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContractForAssembly(typeof(HostingExtensions).Assembly);

        Approvals.Verify(contract);
    }
    public void PackageManagement_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <PackageRestoreContext>();

        this.Assent(contract, _configuration);
    }
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list all the APIs
                IPage <ApiContract> apiResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(apiResponse);
                Assert.Single(apiResponse);
                Assert.Null(apiResponse.NextPageLink);

                //api to use
                ApiContract apiToUse = apiResponse.First();

                // list diagnostics: there should be none for the Api currently
                var apiDiagnostics = testBase.client.ApiDiagnostic.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    apiToUse.Name);

                Assert.NotNull(apiDiagnostics);
                Assert.Empty(apiDiagnostics);

                // create new diagnostic, supported Ids are applicationinsights, azuremonitor
                string apiDiagnosticId = "applicationinsights";
                string loggerId        = TestUtilities.GenerateName("appInsights");

                try
                {
                    // create a logger
                    Guid applicationInsightsGuid = TestUtilities.GenerateGuid("appInsights");
                    var  credentials             = new Dictionary <string, string>();
                    credentials.Add("instrumentationKey", applicationInsightsGuid.ToString());

                    var loggerCreateParameters = new LoggerContract(LoggerType.ApplicationInsights, credentials);
                    var loggerContract         = await testBase.client.Logger.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId,
                        loggerCreateParameters);

                    Assert.NotNull(loggerContract);
                    Assert.Equal(loggerId, loggerContract.Name);
                    Assert.Equal(LoggerType.ApplicationInsights, loggerContract.LoggerType);
                    Assert.NotNull(loggerContract.Credentials);
                    Assert.Equal(1, loggerContract.Credentials.Keys.Count);

                    // create a diagnostic entity with just loggerId
                    var diagnosticContractParams = new DiagnosticContract()
                    {
                        LoggerId = loggerContract.Id
                    };
                    var apiDiagnosticContract = await testBase.client.ApiDiagnostic.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        apiToUse.Name,
                        apiDiagnosticId,
                        diagnosticContractParams);

                    Assert.NotNull(apiDiagnosticContract);
                    Assert.Equal(apiDiagnosticId, apiDiagnosticContract.Name);

                    // check the diagnostic entity etag
                    var apiDiagnosticTag = await testBase.client.ApiDiagnostic.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        apiToUse.Name,
                        apiDiagnosticId);

                    Assert.NotNull(apiDiagnosticTag);
                    Assert.NotNull(apiDiagnosticTag.ETag);

                    // now update the sampling and other settings of the diagnostic
                    diagnosticContractParams.AlwaysLog = "allErrors";
                    diagnosticContractParams.Sampling  = new SamplingSettings("fixed", 50);
                    var listOfHeaders = new List <string> {
                        "Content-type"
                    };
                    var bodyDiagnostic = new BodyDiagnosticSettings(512);
                    diagnosticContractParams.Frontend = new PipelineDiagnosticSettings
                    {
                        Request = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        },
                        Response = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        }
                    };
                    diagnosticContractParams.Backend = new PipelineDiagnosticSettings
                    {
                        Request = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        },
                        Response = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        }
                    };

                    var updatedApiDiagnostic = await testBase.client.ApiDiagnostic.CreateOrUpdateWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        apiToUse.Name,
                        apiDiagnosticId,
                        diagnosticContractParams,
                        apiDiagnosticTag.ETag);

                    Assert.NotNull(updatedApiDiagnostic);
                    Assert.Equal("allErrors", updatedApiDiagnostic.Body.AlwaysLog);
                    Assert.NotNull(updatedApiDiagnostic.Body.Sampling);
                    Assert.NotNull(updatedApiDiagnostic.Body.Frontend);
                    Assert.NotNull(updatedApiDiagnostic.Body.Backend);

                    // delete the diagnostic entity
                    await testBase.client.ApiDiagnostic.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        apiToUse.Name,
                        apiDiagnosticId,
                        updatedApiDiagnostic.Headers.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.ApiDiagnostic.GetEntityTag(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               apiToUse.Name,
                                                               apiDiagnosticId));

                    // check the logger entity etag
                    var loggerTag = await testBase.client.Logger.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId);

                    Assert.NotNull(loggerTag);
                    Assert.NotNull(loggerTag.ETag);

                    // delete the logger entity
                    await testBase.client.Logger.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId,
                        loggerTag.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Logger.GetEntityTag(testBase.rgName, testBase.serviceName, loggerId));
                }
                finally
                {
                    testBase.client.ApiDiagnostic.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        apiToUse.Name,
                        apiDiagnosticId,
                        "*");
                    testBase.client.Logger.Delete(testBase.rgName, testBase.serviceName, loggerId, "*");
                }
            }
        }
    public void csharpProject_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <CSharpProjectKernel>();

        this.Assent(contract, _configuration);
    }
        /// <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();
                }
            }
        }
    public void powershell_api_is_not_changed()
    {
        var contract = ApiContract.GenerateContract <PowerShellKernel>();

        this.Assent(contract, _configuration);
    }
Esempio n. 23
0
        public void ContainedElementHandlesNull()
        {
            bool value = ApiContract.IsContainedApiContractsElement(null);

            Assert.IsFalse(value, "should not be valid and not throw on null");
        }