public async void GetBestBetForDisplay_TestAPIConnectionFailure()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <BestBetsCategoryDisplay> >((req, res) =>
            {
                res.StatusCode = 500;
            });

            //While this has a URI, it does not matter, an InMemoryConnection never requests
            //from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <CGBBIndexOptions> bbClientOptions = GetMockOptions();

            ESBestBetsDisplayService bbClient = new ESBestBetsDisplayService(client, bbClientOptions, new NullLogger <ESBestBetsDisplayService>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => bbClient.GetBestBetForDisplay("live", "431121"));

            Assert.Equal(500, ex.HttpStatusCode);
        }
Example #2
0
        /// <summary>
        /// Convert response to stream
        /// </summary>
        /// <param name="response">response object</param>
        /// <returns>Stream with response</returns>
        public async Task<Stream> BuildSendResponse(HttpResponseMessage response)
        {
            var stream = await response.Content.ReadAsStreamAsync();

            if (response.IsSuccessStatusCode)
                return stream;

            var content = await StreamToStringAsync(stream);

            APIErrorException apiError = null;
            try
            {
                apiError = JsonConvert.DeserializeObject<APIErrorException>(content);
            }
            catch (Exception)
            {
                throw new APIErrorException
                {
                    Code = (int)response.StatusCode,
                    Message = content,
                    Data = null
                };
            }

            throw apiError;
        }
Example #3
0
        internal static string GetMessageFromException(Exception ex)
        {
            string errorDetails = ex.Message;

            APIErrorException faceApiException = ex as APIErrorException;

            if (faceApiException?.Message != null)
            {
                errorDetails = faceApiException.Message;
            }

            var visionException = ex as Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.ComputerVisionErrorException;

            if (visionException?.Body?.Message != null)
            {
                errorDetails = visionException.Body.Message;
            }

            HttpOperationException httpException = ex as HttpOperationException;

            if (httpException?.Response?.ReasonPhrase != null)
            {
                errorDetails = string.Format("{0}. The error message was \"{1}\".", ex.Message, httpException?.Response?.ReasonPhrase);
            }

            return(errorDetails);
        }
Example #4
0
        public async void GetCount_InvalidResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.CountResponse>((req, res) =>
            {
                string partial   = @"{
                    ""count"": 8458,
                    ""_shards"": {";
                byte[] byteArray = Encoding.UTF8.GetBytes(partial);
                res.Stream       = new MemoryStream(byteArray);
                res.StatusCode   = 200;
            });

            // The URI does not matter, an InMemoryConnection never requests from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> clientOptions = GetMockOptions();

            ESTermsQueryService query = new ESTermsQueryService(client, clientOptions, new NullLogger <ESTermsQueryService>());

            // We don't care about the inputs, only in the error response.
            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => query.GetCount("Cancer.gov", AudienceType.HealthProfessional, "es")
                );

            Assert.Equal(500, ex.HttpStatusCode);
        }
        internal static string GetMessageFromException(Exception ex)
        {
            string errorDetails = ex.Message;

            APIErrorException faceApiException = ex as APIErrorException;

            if (faceApiException?.Message != null)
            {
                errorDetails = faceApiException.Message;
            }

            var visionException = ex as Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.ComputerVisionErrorException;

            if (!string.IsNullOrEmpty(visionException?.Body?.Message))
            {
                errorDetails = visionException.Body.Message;
            }

            HttpOperationException httpException = ex as HttpOperationException;

            if (httpException?.Response?.ReasonPhrase != null)
            {
                string errorReason = $"\"{httpException.Response.ReasonPhrase}\".";
                if (httpException?.Response?.Content != null)
                {
                    errorReason += $" Some more details: {httpException.Response.Content}";
                }

                errorDetails = $"{ex.Message}. The error was {errorReason}.";
            }

            return(errorDetails);
        }
        public async void Search_TestAPIConnectionFailure()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <GlossaryTerm> >((req, res) =>
            {
                res.StatusCode = 500;
            });

            // While this has a URI, it does not matter, an InMemoryConnection never requests
            // from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> gTermsClientOptions = GetMockOptions();

            ESTermsQueryService termsClient = new ESTermsQueryService(client, gTermsClientOptions, new NullLogger <ESTermsQueryService>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => termsClient.Search("Cancer.gov", AudienceType.Patient, "en", "chicken", MatchType.Begins, 10, 0, false));

            Assert.Equal(500, ex.HttpStatusCode);
        }
        public async void GetSuggestions_TestErrorResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.SearchResponse <Suggestion> >((req, res) =>
            {
                // Simulate an error.
                res.Stream     = null;
                res.StatusCode = 500;
            });

            // The URI does not matter, an InMemoryConnection never requests from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> clientOptions = GetMockOptions();

            ESAutosuggestQueryService query = new ESAutosuggestQueryService(client, clientOptions, new NullLogger <ESAutosuggestQueryService>());

            // We don't care about the inputs, only in the error response.
            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => query.GetSuggestions("Cancer.gov", AudienceType.HealthProfessional, "es", "chicken", MatchType.Contains, 200)
                );

            Assert.Equal(500, ex.HttpStatusCode);
        }
Example #8
0
        public async void GetAll_Error_LanguageBad()
        {
            Mock <ITermsQueryService> querySvc = new Mock <ITermsQueryService>();

            TermsController controller = new TermsController(querySvc.Object);

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => controller.getAll("glossary", AudienceType.HealthProfessional, "turducken"));
        }
Example #9
0
        public async void GetAll_Error_DictionaryMissing()
        {
            Mock <ITermsQueryService> querySvc = new Mock <ITermsQueryService>();

            TermsController controller = new TermsController(querySvc.Object);

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => controller.getAll("", AudienceType.HealthProfessional, "en"));
        }
        public async void Search_ErrorMessage_AudienceType()
        {
            Mock <ITermsQueryService> termsQueryService = new Mock <ITermsQueryService>();
            TermsController           controller        = new TermsController(NullLogger <TermsController> .Instance, termsQueryService.Object);
            APIErrorException         exception         = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.Search("Cancer.gov", (AudienceType)(-18), "en", "chicken", MatchType.Begins, 10, 0)
                );

            Assert.Equal("You must supply a valid dictionary, audience and language.", exception.Message);
        }
        public async void GetSuggestions_ErrorMessage_AudienceType()
        {
            Mock <IAutosuggestQueryService> querySvc   = new Mock <IAutosuggestQueryService>();
            AutosuggestController           controller = new AutosuggestController(querySvc.Object);
            APIErrorException exception = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.GetSuggestions("Dictionary", (AudienceType)(-20937), "EN", "Query", true, 20, 0)
                );

            Assert.Equal("You must supply a valid dictionary, audience and language.", exception.Message);
        }
Example #12
0
        public async void SearchForTerms_ErrorMessage_AudienceType()
        {
            Mock <ITermsQueryService> termsQueryService = new Mock <ITermsQueryService>();
            TermsController           controller        = new TermsController(termsQueryService.Object);
            APIErrorException         exception         = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.Search("Dictionary", (AudienceType)(-18), "EN", "Query", "contains", 0, 1, new string[] {})
                );

            Assert.Equal("You must supply a valid dictionary, audience and language.", exception.Message);
        }
Example #13
0
        public async void SearchForTerms_ErrorMessage_MatchType()
        {
            Mock <ITermsQueryService> termsQueryService = new Mock <ITermsQueryService>();
            TermsController           controller        = new TermsController(termsQueryService.Object);
            APIErrorException         exception         = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.Search("Dictionary", AudienceType.Patient, "EN", "Query", "doesnotcontain", 1, 1, new string[] {})
                );

            Assert.Equal("'matchType' can only be 'begins' or 'contains'", exception.Message);
        }
        public async void GetSuggestions_ErrorMessage_LanguageBad()
        {
            Mock <IAutosuggestQueryService> querySvc   = new Mock <IAutosuggestQueryService>();
            AutosuggestController           controller = new AutosuggestController(querySvc.Object);
            APIErrorException exception = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.GetSuggestions("glossary", AudienceType.Patient, "invalid", "suggest", true, 20, 0)
                );

            Assert.Equal("Unsupported Language. Valid values are 'en' and 'es'.", exception.Message);
        }
        public async void GetSuggestions_ErrorMessage_LanguageMissing()
        {
            Mock <IAutosuggestQueryService> querySvc   = new Mock <IAutosuggestQueryService>();
            AutosuggestController           controller = new AutosuggestController(querySvc.Object);
            APIErrorException exception = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.GetSuggestions("glossary", AudienceType.HealthProfessional, "", "suggest", false, 20, 0)
                );

            Assert.Equal("You must supply a valid dictionary, audience and language.", exception.Message);
        }
Example #16
0
        [InlineData(new object[] { "" })]  // Empty string.
        public async void Count_ErrorMessage_Dictionary(string dictionary)
        {
            Mock <ITermsQueryService> querySvc   = new Mock <ITermsQueryService>();
            TermsController           controller = new TermsController(NullLogger <TermsController> .Instance, querySvc.Object);

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.GetCount(dictionary, AudienceType.HealthProfessional, "en")
                );

            Assert.Equal(400, ex.HttpStatusCode);
        }
Example #17
0
        [InlineData(new object[] { "" })]  // Empty string.
        public async void Count_ErrorMessage_Language(string badLanguage)
        {
            Mock <ITermsQueryService> querySvc   = new Mock <ITermsQueryService>();
            TermsController           controller = new TermsController(NullLogger <TermsController> .Instance, querySvc.Object);

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(
                () => controller.GetCount("Cancer.gov", AudienceType.Patient, badLanguage)
                );

            Assert.Equal(400, ex.HttpStatusCode);
        }
        public async void GetBestBetForDisplay_InvalidIDError(BaseDisplayTestData data)
        {
            IElasticClient client = GetElasticClientWithData(data);

            // Setup the mocked Options
            IOptions <CGBBIndexOptions> bbClientOptions = GetMockOptions();

            ESBestBetsDisplayService bbClient = new ESBestBetsDisplayService(client, bbClientOptions, new NullLogger <ESBestBetsDisplayService>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => bbClient.GetBestBetForDisplay("live", "chicken"));

            Assert.Equal(400, ex.HttpStatusCode);
        }
Example #19
0
        [InlineData("ESHealthData/unexpected.json")]   // i.e. "Unexpected color"
        public void GetStatus_Unhealthy(string datafile)
        {
            IOptions <AutosuggestIndexOptions> config = GetMockedAutosuggestIndexOptions();
            AutosuggestController ctrl = new AutosuggestController(
                ElasticTools.GetInMemoryElasticClient(datafile),
                config,
                NullLogger <AutosuggestController> .Instance
                );

            APIErrorException ex = Assert.Throws <APIErrorException>(() => ctrl.GetStatus());

            Assert.Equal(500, ex.HttpStatusCode);
        }
        public async void GetByName_TestNoOrIncorrectResults(string file, int expectedStatusCode, string expectedMessage)
        {
            IElasticClient client = GetByName_GetElasticClientWithData(file);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> gTermsClientOptions = GetMockOptions();

            ESTermsQueryService termsClient = new ESTermsQueryService(client, gTermsClientOptions, new NullLogger <ESTermsQueryService>());

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => termsClient.GetByName("Cancer.gov", AudienceType.Patient, "en", "s-1"));

            Assert.Equal(expectedStatusCode, ex.HttpStatusCode);
            Assert.Equal(expectedMessage, ex.Message);
        }
        public void Get_Error_SearchTermBad()
        {
            Mock <IBestBetsDisplayService> displayService = new Mock <IBestBetsDisplayService>();
            Mock <IBestBetsMatchService>   matchService   = new Mock <IBestBetsMatchService>();

            // Create instance of controller
            BestBetsController controller = new BestBetsController(
                matchService.Object,
                displayService.Object,
                NullLogger <BestBetsController> .Instance
                );

            APIErrorException ex = Assert.Throws <APIErrorException>(() => controller.Get("en", null));
        }
Example #22
0
        public async void Get_Error_LanguageEmpty()
        {
            Mock <IBestBetsDisplayService> displayService = new Mock <IBestBetsDisplayService>();
            Mock <IBestBetsMatchService>   matchService   = new Mock <IBestBetsMatchService>();
            Mock <IHealthCheckService>     healthService  = new Mock <IHealthCheckService>();

            // Create instance of controller
            BestBetsController controller = new BestBetsController(
                matchService.Object,
                displayService.Object,
                healthService.Object,
                NullLogger <BestBetsController> .Instance
                );

            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => controller.Get("live", null, null));
        }
Example #23
0
        internal static string GetMessageFromException(Exception ex)
        {
            string errorDetails = ex.Message;

            APIErrorException faceApiException = ex as APIErrorException;

            if (faceApiException?.Message != null)
            {
                errorDetails = faceApiException.Message;
            }

            HttpOperationException httpException = ex as HttpOperationException;

            if (httpException?.Response?.ReasonPhrase != null)
            {
                errorDetails = string.Format("{0}. The error message was \"{1}\".", ex.Message, httpException?.Response?.ReasonPhrase);
            }

            return(errorDetails);
        }
Example #24
0
        public async void IsHealthy_Unhealthy()
        {
            IBestBetsDisplayService displayService = null;
            IBestBetsMatchService   matchService   = null;
            IHealthCheckService     healthService  = GetMockedHealthSvc <IHealthCheckService>(false);

            // Create instance of controller
            BestBetsController controller = new BestBetsController(
                matchService,
                displayService,
                healthService,
                NullLogger <BestBetsController> .Instance
                );

            // If the health check service is unhealthy, verify that GetStatus() throws APIErrorException
            // with a status of 500.
            APIErrorException ex = await Assert.ThrowsAsync <APIErrorException>(() => controller.GetStatus());

            Assert.Equal(500, ex.HttpStatusCode);
        }
Example #25
0
        public async void GetByIdForGlossaryTerm_TestInvalidResponse()
        {
            ElasticsearchInterceptingConnection conn = new ElasticsearchInterceptingConnection();

            conn.RegisterRequestHandlerForType <Nest.GetResponse <GlossaryTerm> >((req, res) =>
            {
            });

            //While this has a URI, it does not matter, an InMemoryConnection never requests
            //from the server.
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var            connectionSettings = new ConnectionSettings(pool, conn);
            IElasticClient client             = new ElasticClient(connectionSettings);

            // Setup the mocked Options
            IOptions <GlossaryAPIOptions> gTermClientOptions = GetMockOptions();

            ESTermQueryService termClient = new ESTermQueryService(client, gTermClientOptions, new NullLogger <ESTermQueryService>());
            APIErrorException  ex         = await Assert.ThrowsAsync <APIErrorException>(() => termClient.GetById("cancer.gov", AudienceType.Patient, "en", 43966L, new string[] {}));

            Assert.Equal(500, ex.HttpStatusCode);
        }
        /// <summary>
        /// Add a term to the term list with list Id equal to list Id passed.
        /// </summary>
        /// <param name='listId'>
        /// List Id of the image list.
        /// </param>
        /// <param name='term'>
        /// Term to be deleted
        /// </param>
        /// <param name='language'>
        /// Language of the terms.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="APIErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <object> > AddTermWithHttpMessagesAsync(string listId, string term, string language, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (listId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "listId");
            }
            if (term == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "term");
            }
            if (language == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "language");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("listId", listId);
                tracingParameters.Add("term", term);
                tracingParameters.Add("language", language);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "AddTerm", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "contentmoderator/lists/v1.0/termlists/{listId}/terms/{term}";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            _url = _url.Replace("{listId}", System.Uri.EscapeDataString(listId));
            _url = _url.Replace("{term}", System.Uri.EscapeDataString(term));
            List <string> _queryParameters = new List <string>();

            if (language != null)
            {
                _queryParameters.Add(string.Format("language={0}", System.Uri.EscapeDataString(language)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <APIError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <object>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Creates an image list.
        /// </summary>
        /// <param name='contentType'>
        /// The content type.
        /// </param>
        /// <param name='body'>
        /// Schema of the body.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="APIErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <ImageList> > CreateWithHttpMessagesAsync(string contentType, Body body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (contentType == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "contentType");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("contentType", contentType);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "contentmoderator/lists/v1.0/imagelists";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <APIError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <ImageList>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <ImageList>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #28
0
        /// <summary>
        /// Gets predictions for a given utterance, in the form of intents and
        /// entities. The current maximum query size is 500 characters.
        /// </summary>
        /// <param name='appId'>
        /// The LUIS application ID (Guid).
        /// </param>
        /// <param name='query'>
        /// The utterance to predict.
        /// </param>
        /// <param name='timezoneOffset'>
        /// The timezone offset for the location of the request.
        /// </param>
        /// <param name='verbose'>
        /// If true, return all intents instead of just the top scoring intent.
        /// </param>
        /// <param name='staging'>
        /// Use the staging endpoint slot.
        /// </param>
        /// <param name='spellCheck'>
        /// Enable spell checking.
        /// </param>
        /// <param name='bingSpellCheckSubscriptionKey'>
        /// The subscription key to use when enabling bing spell check
        /// </param>
        /// <param name='log'>
        /// Log query (default is true)
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="APIErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <LuisResult> > ResolveWithHttpMessagesAsync(string appId, string query, double?timezoneOffset = default(double?), bool?verbose = default(bool?), bool?staging = default(bool?), bool?spellCheck = default(bool?), string bingSpellCheckSubscriptionKey = default(string), bool?log = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (appId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appId");
            }
            if (query == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "query");
            }
            if (query != null)
            {
                if (query.Length > 500)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "query", 500);
                }
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("appId", appId);
                tracingParameters.Add("query", query);
                tracingParameters.Add("timezoneOffset", timezoneOffset);
                tracingParameters.Add("verbose", verbose);
                tracingParameters.Add("staging", staging);
                tracingParameters.Add("spellCheck", spellCheck);
                tracingParameters.Add("bingSpellCheckSubscriptionKey", bingSpellCheckSubscriptionKey);
                tracingParameters.Add("log", log);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Resolve", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "apps/{appId}";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            _url = _url.Replace("{appId}", System.Uri.EscapeDataString(appId));
            List <string> _queryParameters = new List <string>();

            if (timezoneOffset != null)
            {
                _queryParameters.Add(string.Format("timezoneOffset={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(timezoneOffset, Client.SerializationSettings).Trim('"'))));
            }
            if (verbose != null)
            {
                _queryParameters.Add(string.Format("verbose={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(verbose, Client.SerializationSettings).Trim('"'))));
            }
            if (staging != null)
            {
                _queryParameters.Add(string.Format("staging={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(staging, Client.SerializationSettings).Trim('"'))));
            }
            if (spellCheck != null)
            {
                _queryParameters.Add(string.Format("spellCheck={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(spellCheck, Client.SerializationSettings).Trim('"'))));
            }
            if (bingSpellCheckSubscriptionKey != null)
            {
                _queryParameters.Add(string.Format("bing-spell-check-subscription-key={0}", System.Uri.EscapeDataString(bingSpellCheckSubscriptionKey)));
            }
            if (log != null)
            {
                _queryParameters.Add(string.Format("log={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(log, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (query != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <APIError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <LuisResult>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LuisResult>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }