/// <summary>
        /// Read Json
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            BaseMessageResponse[] result = null;

            var jArray = JArray.Load(reader);

            if (jArray != null)
            {
                result = new BaseMessageResponse[jArray.Count];

                for (var i = 0; i < jArray.Count; i++)
                {
                    var messageType = EnumHelper.Parse <Enums.Type>(jArray[i]["type"].ToString());

                    switch (messageType)
                    {
                    case Enums.Type.Text:
                        result[i] = ApiAiJson <TextMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.Card:
                        result[i] = ApiAiJson <CardMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.QuickReply:
                        result[i] = ApiAiJson <QuickReplyMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.Image:
                        result[i] = ApiAiJson <ImageMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.Custom_Payload:
                        result[i] = ApiAiJson <PayloadMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.Simple_Response:
                        result[i] = ApiAiJson <SimpleResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Enums.Type.Suggestion_Chips:
                        result[i] = ApiAiJson <SuggestionChips> .Deserialize(jArray[i].ToString());

                        break;

                    default:
                        result[i] = null;
                        break;
                    }
                }
            }

            return(result);
        }
Esempio n. 2
0
        private static async Task ValidateResponse(HttpResponseMessage httpResponseMessage)
        {
            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                var errorDetails = string.Empty;

                if (httpResponseMessage.Content != null)
                {
                    var content = await httpResponseMessage.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(content))
                    {
                        try
                        {
                            var queryResponse = ApiAiJson <QueryResponse> .Deserialize(content);

                            if (queryResponse != null && queryResponse.Status != null && !string.IsNullOrEmpty(queryResponse.Status.ErrorDetails))
                            {
                                errorDetails = queryResponse.Status.ErrorDetails;
                            }
                        }
                        catch { }
                    }
                }

                throw new ApiAiException(httpResponseMessage.StatusCode, !string.IsNullOrEmpty(errorDetails) ? errorDetails : "Http response message error.");
            }

            if (httpResponseMessage.Content == null)
            {
                throw new ApiAiException(httpResponseMessage.StatusCode, "api.ai content returned is null.");
            }
        }
Esempio n. 3
0
        public async Task <List <EntityResponse> > GetAllAsync()
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.GetAsync(new Uri($"{BaseUrl}/entities"));

                var content = await httpResponseMessage.ToStringContentAsync();

                return(ApiAiJson <List <EntityResponse> > .Deserialize(content));
            }
        }
Esempio n. 4
0
        public async Task <Entity> GetByIdAsync(string id)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.GetAsync(new Uri($"{BaseUrl}/entities/{id}?v={ApiAiVersion.Default}"));

                var content = await httpResponseMessage.ToStringContentAsync();

                return(ApiAiJson <Entity> .Deserialize(content));
            }
        }
Esempio n. 5
0
        public void Serialize_Deserialize_QueryRequest()
        {
            var queryRequest = GetQueryRequest();

            var json = ApiAiJson <QueryRequest> .Serialize(queryRequest);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"lang\": \"en\""));
            var deserializeQueryRequest = ApiAiJson <QueryRequest> .Deserialize(json);

            Assert.IsTrue(queryRequest.Query[0] == deserializeQueryRequest.Query[0]);
        }
Esempio n. 6
0
        public void Serialize_Deserialize_WebhookResponse()
        {
            var webhookResponse = GetWebhookResponse();

            var json = ApiAiJson <WebhookResponse> .Serialize(webhookResponse);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"source\": \"unit-test\""));

            var deserializeWebhookResponse = ApiAiJson <WebhookResponse> .Deserialize(json);

            Assert.IsTrue(webhookResponse.Source == deserializeWebhookResponse.Source);
        }
Esempio n. 7
0
        public async Task <QueryResponse> GetQueryAsync(QueryRequest request)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var uri = new Uri($"{BaseUrl}/{request.ToHttpGetQueryString()}");

                var httpResponseMessage = await httpClient.GetAsync(uri);

                var content = await httpResponseMessage.ToStringContentAsync();

                return(ApiAiJson <QueryResponse> .Deserialize(content));
            }
        }
Esempio n. 8
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            BaseMessageResponse[] result = null;

            var jArray = JArray.Load(reader);

            if (jArray != null)
            {
                result = new BaseMessageResponse[jArray.Count];

                for (var i = 0; i < jArray.Count; i++)
                {
                    var messageType = (Domain.Enum.Type)System.Enum.Parse(typeof(Domain.Enum.Type), jArray[i]["type"].ToString());

                    switch (messageType)
                    {
                    case Domain.Enum.Type.Text:
                        result[i] = ApiAiJson <TextMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Domain.Enum.Type.Card:
                        result[i] = ApiAiJson <CardMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Domain.Enum.Type.QuickReply:
                        result[i] = ApiAiJson <QuickReplyMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Domain.Enum.Type.Image:
                        result[i] = ApiAiJson <ImageMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    case Domain.Enum.Type.Payload:
                        result[i] = ApiAiJson <PayloadMessageResponse> .Deserialize(jArray[i].ToString());

                        break;

                    default:
                        result[i] = null;
                        break;
                    }
                }
            }

            return(result);
        }
Esempio n. 9
0
        public async Task <QueryResponse> PostQueryAsync(QueryRequest request)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var uri = new Uri($"{BaseUrl}/{request.ToHttpPostQueryString()}");

                var queryRequestJson = ApiAiJson <QueryRequest> .Serialize(request);

                var httpResponseMessage = await httpClient.PostAsync(uri, new StringContent(queryRequestJson, Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                return(ApiAiJson <QueryResponse> .Deserialize(content));
            }
        }
Esempio n. 10
0
        private static void Query(Container container, IApiAiAppServiceFactory apiAiAppServiceFactory)
        {
            ///Create full contact app service
            var queryAppService = apiAiAppServiceFactory.CreateQueryAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN");

            ///Create query request
            var queryRequest = new QueryRequest
            {
                Query = new string[] { "Hello, I want a pizza" },
                Lang  = Domain.Enum.Language.English
            };

            /// Call api.ai query by get
            var queryResponse = queryAppService.PostQueryAsync(queryRequest).Result;

            System.Console.Write(ApiAiJson <QueryResponse> .Serialize(queryResponse));
        }
Esempio n. 11
0
        public void Serialize_Deserialize_QueryResponse()
        {
            var queryResponse = GetQueryResponse();

            var datePeriod = queryResponse.Result.GetParameterValueByKey("parameter-key-2");

            var json = ApiAiJson <QueryResponse> .Serialize(queryResponse);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"code\": 200"));

            var deserializeQueryResponse = ApiAiJson <QueryResponse> .Deserialize(json);

            json = ApiAiJson <QueryResponse> .Serialize(deserializeQueryResponse);

            Assert.IsTrue(deserializeQueryResponse.Result.Fulfillment.Messages.Length > 0);

            Assert.IsTrue(queryResponse.Id == deserializeQueryResponse.Id);
        }
Esempio n. 12
0
        public async Task DeleteAsync(string id)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.DeleteAsync(new Uri($"{BaseUrl}/entities/{id}?v={ApiAiVersion.Default}"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new Exception("Delete entity error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new Exception($"Delete entity error - Invalid http status code '{responseBase.Status.Code}'");
                }
            }
        }
Esempio n. 13
0
        public async Task UpdateAsync(Entity entity)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.PutAsync(new Uri($"{BaseUrl}/entities/{entity.Id}"),
                                                                    new StringContent(ApiAiJson <Entity> .Serialize(entity), Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new Exception("Update entity error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new Exception($"Update entity error - Invalid http status code '{responseBase.Status.Code}'");
                }
            }
        }
Esempio n. 14
0
        public async Task AddEntriesSpecifiedEntityAsync(string id, List <Entry> entries)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.PostAsync(new Uri($"{BaseUrl}/entities/{id}/entries"),
                                                                     new StringContent(ApiAiJson <List <Entry> > .Serialize(entries), Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new Exception("Add entries specified entity error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new Exception($"Add entries specified entity error  - Invalid http status code '{responseBase.Status.Code}'");
                }
            }
        }
        public async Task UpdatesEntityEntriesAsync(string id, List <Entry> entries)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.PutAsync(new Uri($"{BaseUrl}/entities/{id}/entries"),
                                                                    new StringContent(ApiAiJson <List <Entry> > .Serialize(entries), Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new ApiAiException(HttpStatusCode.Conflict, "Updates entity entries error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new ApiAiException(responseBase.Status.Code, "Updates entity entries error.");
                }
            }
        }
Esempio n. 16
0
        public async Task DeleteAsync(string sessionId)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.PostAsync(new Uri($"{BaseUrl}/contexts?sessionId={sessionId}"),
                                                                     new StringContent("", Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new Exception("Delete contexts error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new Exception($"Delete contexts error - Invalid http status code '{responseBase.Status.Code}'");
                }
            }
        }
        public async Task <string> CreateAsync(Entity entity)
        {
            using (var httpClient = HttpClientFactory.Create(AccessToken))
            {
                var httpResponseMessage = await httpClient.PostAsync(new Uri($"{BaseUrl}/entities?v={ApiAiVersion.Default}"),
                                                                     new StringContent(ApiAiJson <Entity> .Serialize(entity), Encoding.UTF8, "application/json"));

                var content = await httpResponseMessage.ToStringContentAsync();

                var responseBase = ApiAiJson <ResponseBase> .Deserialize(content);

                if (responseBase == null)
                {
                    throw new ApiAiException(HttpStatusCode.Conflict, "Create entity error - Deserialize content is null or empty.");
                }

                if (!responseBase.Status.IsSuccessStatusCode)
                {
                    throw new ApiAiException(responseBase.Status.Code, "Create entity error.");
                }

                return(responseBase.Id);
            }
        }