private async Task <HttpResponseMessage> PostResquestToAzureTextAnalytics(string message, string action)
        {
            var uri    = $"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/{action}";
            var client = new HttpClient();

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["TextAnalyticsKey"]);
            client.DefaultRequestHeaders.Add("Accept", "application/json");

            var input = new BatchInput
            {
                Documents = new List <DocumentInput>
                {
                    new DocumentInput
                    {
                        Id   = 1,
                        Text = message,
                    }
                }
            };
            var json       = JsonConvert.SerializeObject(input);
            var postResult = await client.PostAsync(uri, new StringContent(json, Encoding.UTF8, "application/json"));

            return(postResult);
        }
Esempio n. 2
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity.Type == ActivityTypes.Message)
            {
                const string apiKey = "efdaf8bbe1c84341b6e996ec76eae285";
                // const string queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
                const string queryUri = "https://southeastasia.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
                var          client   = new HttpClient
                {
                    DefaultRequestHeaders =
                    {
                        { "Ocp-Apim-Subscription-Key", apiKey             },
                        { "Accept",                    "application/json" }
                    }
                };
                var sentimentInput = new BatchInput
                {
                    Documents = new List <DocumentInput> {
                        new DocumentInput {
                            Id   = 1,
                            Text = activity.Text,
                        }
                    }
                };
                var json          = JsonConvert.SerializeObject(sentimentInput);
                var sentimentPost = await client.PostAsync(queryUri, new StringContent(json, Encoding.UTF8, "application/json"));

                var sentimentRawResponse = await sentimentPost.Content.ReadAsStringAsync();

                var sentimentJsonResponse = JsonConvert.DeserializeObject <BatchResult>(sentimentRawResponse);
                var sentimentScore        = sentimentJsonResponse?.documents?.FirstOrDefault()?.Score ?? 0;

                string message;
                if (sentimentScore > 0.7)
                {
                    message = $"That's great to hear!";
                }
                else if (sentimentScore < 0.3)
                {
                    message = $"I'm sorry to hear that...";
                }
                else
                {
                    message = $"I see...";
                }
                var reply = activity.CreateReply(message);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                //add code to handle errors, or non-messaging activities
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Esempio n. 3
0
        public virtual async Task DeleteDailyStatistic(BatchInput <int> input)
        {
            if (input.Ids == null || input.Ids.Count() <= 0)
            {
                return;
            }

            foreach (var id in input.Ids)
            {
                await _advertDailyStatisticManager.DeleteAsync(id);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 删除租户物流
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task DeleteTenantLogistics(BatchInput <int> input)
        {
            if (input.Ids == null || input.Ids.Count() <= 0)
            {
                return;
            }

            foreach (var id in input.Ids)
            {
                await _logisticsManager.DeleteTenantLogisticsAsync(id);
            }
        }
        public async Task <IActionResult> PerformeCalculation1()
        {
            BatchInput input = new BatchInput
            {
                BatchSize     = 5,
                ItemsPerBatch = 7
            };

            await _processorService.PerformeCalculation(input);

            return(NoContent());
        }
Esempio n. 6
0
        public async Task DeleteAsync(BatchInput <long> input)
        {
            foreach (var id in input.Ids)
            {
                var picture = await _pictureManager.GetByIdAsync(id);

                //删除云存储资源文件
                await _storageProvider.DeleteAsync(picture.Key);

                await _pictureManager.DeleteAsync(picture);
            }
        }
Esempio n. 7
0
        public async Task DeleteProduct(BatchInput <long> input)
        {
            if (input.Ids == null || input.Ids.Count() <= 0)
            {
                return;
            }

            foreach (var id in input.Ids)
            {
                await _productManager.DeleteAsync(id);
            }
        }
Esempio n. 8
0
        public async Task DeleteStore(BatchInput <int> input)
        {
            if (input.Ids == null || input.Ids.Count() <= 0)
            {
                return;
            }

            foreach (var id in input.Ids)
            {
                await _storeManager.DeleteAsync(id);
            }
        }
Esempio n. 9
0
        public async Task DeleteCategory(BatchInput <int> input)
        {
            if (input.Ids == null || input.Ids.Count() <= 0)
            {
                return;
            }

            foreach (var id in input.Ids)
            {
                await _catalogyManager.DeleteAsync(id);
            }
        }
Esempio n. 10
0
        public BatchInput getBatchInput()
        {
            BatchInput bi = new BatchInput();

            bi.Documents = new List <Input>();
            int i = 1;

            foreach (string s in text)
            {
                bi.Documents.Add(new Input(i.ToString(), s));
                i++;
            }
            return(bi);
        }
Esempio n. 11
0
        private static async Task <double> GetSentimentScore(string message)
        {
            var docs = new List <DocumentInput>
            {
                new DocumentInput {
                    Id = 1, Text = message
                }
            };
            var sentimentInput = new BatchInput {
                Documents = docs
            };
            var jsonSentimentInput = JsonConvert.SerializeObject(sentimentInput);
            var sentimentInfo      = await GetSentiment(_textAnalyticsApiKey, jsonSentimentInput);

            return(sentimentInfo.Documents[0].Score);
        }
Esempio n. 12
0
        public async Task PerformeCalculation(BatchInput input)
        {
            ItemsPerBatch      = input.ItemsPerBatch;
            IsProcessCompleted = false;

            IEnumerable <int> integerList = Enumerable.Range(1, input.BatchSize).ToList();

            GroupId++;
            var myTask = new List <Task>();

            Parallel.ForEach(integerList, i =>
            {
                myTask.Add(_generatorManager.Generate(i, input.ItemsPerBatch));
            });

            await Task.WhenAll(myTask).ContinueWith(res => IsProcessCompleted = true);
        }
Esempio n. 13
0
 protected UnitTestData()
 {
     BatchItems = new List <Batch>()
     {
         Batch1, Batch2, Batch3, Batch4, Batch5, Batch6
     };
     BatchOutput = new BatchOutput()
     {
         BatchList          = BatchItems,
         CurrentGroupId     = 1,
         IsProcessCompleted = true
     };
     BatchInput = new BatchInput()
     {
         BatchSize = 2, ItemsPerBatch = 2
     };
 }
Esempio n. 14
0
    public static async Task <double> SentimentScore(string message)
    {
        var ret = 0d;

        const string apiKey   = "d8c5644161084c948780ee1d69338f6f";
        string       queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";

        using (HttpClient client = new HttpClient())
        {
            //Ajustamos el cliente para llamar a cognitive services
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
            client.DefaultRequestHeaders.Add("Accept", "application/json");

            //Ajustamos el mensaje:
            BatchInput sentimentInput = new BatchInput();
            sentimentInput.documents = new List <DocumentInput>();
            sentimentInput.documents.Add(new DocumentInput()
            {
                id   = 1,
                text = message
            });

            //Serializamos el mensaje y lo enviamos usando el cliente, a través de un post
            //Primero a JSON
            var sentimentJsonInput = JsonConvert.SerializeObject(sentimentInput);
            //De JSON a bytes
            byte[] byteData = Encoding.UTF8.GetBytes(sentimentJsonInput);
            //Creamos contenido
            var content = new ByteArrayContent(byteData);
            //Le añadimos el header
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            //Enviamos post y obtenemos resultado
            var responseBytesFromAnalytics = await client.PostAsync(queryUri, content);

            var responseJsonString = await responseBytesFromAnalytics.Content.ReadAsStringAsync();

            var responseBatchResultObject = JsonConvert.DeserializeObject <BatchResult>(responseJsonString);
            ret = responseBatchResultObject.documents[0].score;
        }
        return(ret);
    }
Esempio n. 15
0
        private static void RunExperiment1(ITextAnalyticsClient client)
        {
            Console.WriteLine("\n\n ===== Experiment 1. - analyse language =====");

            var input = new BatchInput(
                new List <Input>()
            {
                new Input("1", "Das ist ein Text zum Testen. Sie können hier auch ihren eigenen Text in verschiedenen Sprachen hinzufügen."),
                new Input("2", "This is a text for testing. You can also add your own text in different languages here."),
                new Input("3", "Ceci est un texte à tester. Vous pouvez également ajouter votre propre texte dans différentes langues ici."),
                new Input("4", "這是一個測試文本。 您也可以在此處添加不同語言的文本。")
            });
            var result = client.DetectLanguageAsync(input).Result;

            // Printing language results.
            foreach (var document in result.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}");
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> PerformeCalculation([FromBody] BatchInput input)
        {
            try
            {
                if (input == null)
                {
                    _logger.LogError("input sent from client is null.");
                    return(BadRequest("input object is null"));
                }

                await _processorService.PerformeCalculation(input);

                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside PerformeCalculation action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Esempio n. 17
0
        public static async Task <string> obtainLanguage(string key, AzureRegions region, string text)
        {
            TextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials());

            client.AzureRegion = region;

            BatchInput input = new BatchInput(new List <Input>()
            {
                new Input("1", text)
            });
            var result = await client.DetectLanguageAsync(input);

            var languages = result.Documents.FirstOrDefault()?.DetectedLanguages;

            if (languages.Count > 0)
            {
                return("Language: " + string.Join(", ", languages.Select(x => x.Name)));
            }
            else
            {
                return("Unable to detect language!");
            }
        }
        public async Task <DetectedLanguage> Execute(ITextAnalyticsAPI client)
        {
            var id        = Guid.NewGuid().ToString();
            var input     = new Input(id, text);
            var documents = new List <Input> {
                input
            };
            var batchInput = new BatchInput(documents);
            var result     = await client.DetectLanguageAsync(batchInput);

            // More than one language could be matched at the same max score...
            // this can cause some confusion

            var detectedLanguages = result.Documents.First()
                                    .DetectedLanguages;

            var detectedLanguage = detectedLanguages.Where(dl => dl.Score.HasValue &&
                                                           new[] { "en", "fr" }.Contains(dl.Iso6391Name))
                                   .OrderByDescending(dl => dl.Score)
                                   .FirstOrDefault();

            return(detectedLanguage);
        }
Esempio n. 19
0
        /// <summary>
        /// Computes the loss error gradient w.r.t the output.
        /// </summary>
        /// <param name="colTop">top output blob vector,
        /// providing the error gradient with respect to the outputs.
        /// </param>
        /// <param name="rgbPropagateDown">see Layer::Backward.  propagate_down[1] must be false as
        /// we can't compute gradients with respect to the labels.</param>
        /// <param name="colBottom">bottom input blob vector
        /// </param>
        protected override void backward(BlobCollection <T> colTop, List <bool> rgbPropagateDown, BlobCollection <T> colBottom)
        {
            if (!rgbPropagateDown[0])
            {
                return;
            }

            // Get input which should be a list of int's where
            //  each entry is the input image index for each
            //  batch item input.
            BatchInput bi          = m_fnGetInput();
            List <int> rgLastInput = bi.InputData as List <int>;

            m_log.CHECK(rgLastInput != null, "The last input should be of type List<int> and should not be null!");
            m_log.CHECK_EQ(colTop[0].num, rgLastInput.Count, "The last input should have the same number of items in top[0].");

            int nBatchSize = colTop[0].num;
            int nNumOutput = colTop[0].channels;

            T[] rgTop    = colTop[0].update_cpu_data();
            T[] rgBottom = new T[rgTop.Length];

            for (int i = 0; i < nBatchSize; i++)
            {
                // Get the maximum output
                float fPreQ    = -float.MaxValue;
                int   nPreQIdx = -1;

                for (int j = 0; j < nNumOutput; j++)
                {
                    int   nIdx    = (i * nNumOutput) + j;
                    float fOutput = (float)Convert.ChangeType(rgTop[nIdx], typeof(float));

                    if (fOutput > fPreQ)
                    {
                        nPreQIdx = nIdx;
                        fPreQ    = fOutput;
                    }
                }

                // Get the reinforcement info.
                BatchInformationCollection col = m_param.reinforcement_loss_param.BatchInfoCollection;

                // Set the maximum output to: maxout = (terminal) ? R : R + lambda * qmax1
                // Set all other outputs to zero.

                float fTarget = (float)Convert.ChangeType(rgTop[nPreQIdx], typeof(float));

                if (col != null)
                {
                    BatchInformation batchInfo = col[bi.BatchIndex];
                    BatchItem        batchItem = batchInfo[i];

                    // clip to range of -1,1
                    fTarget = clip((float)batchItem.Reward, -0.9f, 0.9f);

                    if (!batchItem.Terminal)
                    {
                        fTarget += (float)(m_param.reinforcement_loss_param.discount_rate * batchItem.QMax1);
                    }
                }

                float fDiff  = fTarget - fPreQ;
                float fDelta = clip(fDiff, -0.9f, 0.9f);
                rgBottom[nPreQIdx] = (T)Convert.ChangeType(fDelta, typeof(T));
            }

            colBottom[0].mutable_cpu_diff = rgBottom;
        }
 /// <summary>
 /// The API returns the detected language and a numeric score between 0 and 1.
 /// </summary>
 /// <remarks>
 /// Scores close to 1 indicate 100% certainty that the identified language is
 /// true. A total of 120 languages are supported.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='input'>
 /// Collection of documents to analyze.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <LanguageBatchResult> DetectLanguageAsync(this ITextAnalyticsClient operations, BatchInput input, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(input, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 21
0
        /// <summary>
        /// The API returns the detected language and a numeric score between 0 and 1.
        /// </summary>
        /// <remarks>
        /// Scores close to 1 indicate 100% certainty that the identified language is
        /// true. A total of 120 languages are supported.
        /// </remarks>
        /// <param name='input'>
        /// Collection of documents to analyze.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// 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 <LanguageBatchResult> > DetectLanguageWithHttpMessagesAsync(BatchInput input, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
            }
            if (input == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "input");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("input", input);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "DetectLanguage", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "languages";

            _url = _url.Replace("{Endpoint}", 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 (input != null)
            {
                _requestContent      = SafeJsonConvert.SerializeObject(input, 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 (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, 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 <LanguageBatchResult>();

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

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <LanguageBatchResult>(_responseContent, 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);
        }
Esempio n. 22
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity == null || activity.GetActivityType() != ActivityTypes.Message)
            {
                //add code to handle errors, or non-messaging activities
            }

            const string apiKey   = "674880b753de4d16b4ce1af12790392b";
            string       queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            BatchInput phraseInput = new BatchInput();

            phraseInput.documents = new List <DocumentInput>();
            phraseInput.documents.Add(new DocumentInput()
            {
                id   = 1,
                text = activity.Text
            });

            var phraseJsonInput = JsonConvert.SerializeObject(phraseInput);

            byte[] byteData = Encoding.UTF8.GetBytes(phraseJsonInput);
            var    content  = new ByteArrayContent(byteData);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var phrasePost = await client.PostAsync(queryUri, content);

            var phraseRawResponse = await phrasePost.Content.ReadAsStringAsync();

            var phraseJsonResponse = JsonConvert.DeserializeObject <BatchResult>(phraseRawResponse);

            string[] keyPhrases = phraseJsonResponse.documents[0].keyPhrases;

            var diseases = GetDiseases(keyPhrases);


            var replyMessage = activity.CreateReply();

            replyMessage.Recipient = activity.From;
            replyMessage.Type      = ActivityTypes.Message;

            if (diseases.Count > 0)
            {
                replyMessage.Text = "I think you might have ";
                foreach (var disease in diseases)
                {
                    if (replyMessage.Text != "I think you might have ")
                    {
                        replyMessage.Text += " or ";
                    }
                    replyMessage.Text += disease.Issue.Name;
                }
            }
            else
            {
                replyMessage.Text = "Your symptoms don't match any known diseases.";
            }

            //if (sentimentScore > 0.9)
            //{
            //    replyMessage.Text = $"This appears quite positive to me.";
            //}
            //else if (sentimentScore < 0.1)
            //{
            //    replyMessage.Text = $"This appears quite negative to me.";
            //}
            //else
            //{
            //    replyMessage.Text = $"I can not decipher the sentiment here.  Please try again or add more information.";
            //}

            await connector.Conversations.ReplyToActivityAsync(replyMessage);

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Esempio n. 23
0
        /* Code controlling the Bot */

        //function which is called whenever an "activity" is encountered
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity.Type == ActivityTypes.Message)
            {
                StateClient sc                  = activity.GetStateClient();
                BotData     userData            = sc.BotState.GetPrivateConversationData(activity.ChannelId, activity.Conversation.Id, activity.From.Id);
                var         boolProfileComplete = userData.GetProperty <bool>("is_done");
                if (!boolProfileComplete)
                {
                    await Conversation.SendAsync(activity, MakeRootDialog);
                }
                else
                {
                    var reply = new Activity();

                    //configuring the API's components - key, url
                    const string apiKey   = "0299fdb1d6d84142a31908ad1b2a45e3";
                    const string queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
                    var          client   = new HttpClient
                    {
                        DefaultRequestHeaders =
                        {
                            { "Ocp-Apim-Subscription-Key", apiKey             },
                            { "Accept",                    "application/json" }
                        }
                    };

                    //detecting the sentiment in user's answer
                    var sentimentInput = new BatchInput
                    {
                        documents = new List <DocumentInput> {
                            new DocumentInput {
                                id = 1, text = activity.Text,
                            }
                        }
                    };
                    var json          = JsonConvert.SerializeObject(sentimentInput);
                    var sentimentPost = await client.PostAsync(queryUri, new StringContent(json, Encoding.UTF8, "application/json"));

                    var sentimentRawResponse = await sentimentPost.Content.ReadAsStringAsync();

                    var sentimentJsonResponse = JsonConvert.DeserializeObject <BatchResult>(sentimentRawResponse);
                    var sentimentScore        = sentimentJsonResponse?.documents?.FirstOrDefault()?.score ?? 0;

                    //updating the sentimentScore depending upon the expected sentiment
                    sentimentScore = Global.updateSentiment(sentimentScore);

                    //sending the bot's response depending on the detected sentiment
                    Global.total_score += sentimentScore;
                    string message = Global.GetBotResponse(sentimentScore);
                    reply = activity.CreateReply(message);
                    await connector.Conversations.ReplyToActivityAsync(reply);

                    // DETECTING KEYPHRASES IF SENTIMENT-SCORE IS LOWER THAN NORMAL //

                    if (sentimentScore < 0.3)
                    {
                        //configuring keyPhrase Detection API's components - key, url
                        const string kpd_queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";
                        var          kpd_client   = new HttpClient
                        {
                            DefaultRequestHeaders =
                            {
                                { "Ocp-Apim-Subscription-Key", apiKey             },
                                { "Accept",                    "application/json" }
                            }
                        };

                        var keyphraseInput = new KPD_Input
                        {
                            documents = new List <KPD_DocumentInput> {
                                new KPD_DocumentInput {
                                    language = "en", id = 1, text = activity.Text,
                                }
                            }
                        };

                        // sending activity.Text for analysis
                        var kpd_json = JsonConvert.SerializeObject(keyphraseInput);
                        var kpd_Post = await kpd_client.PostAsync(kpd_queryUri, new StringContent(kpd_json, Encoding.UTF8, "application/json"));

                        var kpd_RawResponse = await kpd_Post.Content.ReadAsStringAsync();

                        KPD_Result kpd_res = JsonConvert.DeserializeObject <KPD_Result>(kpd_RawResponse);

                        // storing keyPhrases of a given activity in a List
                        List <string> phrases = new List <string>();
                        for (int i = 0; i < kpd_res.documents.Count; i++)
                        {
                            for (int j = 0; j < kpd_res.documents[i].keyPhrases.Count; j++)
                            {
                                phrases.Add(kpd_res.documents[i].keyPhrases[j]);
                            }
                        }

                        // search for jokes and one-liners based on detected keyphrases
                        if (phrases[0] != "")
                        {
                            // storing above List in the Global List
                            Global.KeyPhrases.Add(phrases);

                            reply = activity.CreateReply(string.Format("I perceive that you are sad due to \'{0}\'.", string.Join("\', \'", phrases.ToArray())));
                            await connector.Conversations.ReplyToActivityAsync(reply);

                            reply = activity.CreateReply("Time to cheer up! :)");
                            await connector.Conversations.ReplyToActivityAsync(reply);

                            //configuring BingWebSearch and BingImageSearch API - key, url, url_parameters
                            const string  Key     = "0cd4df3677d64499b05eda5a4912510a";
                            List <string> web_url = new List <string>();
                            List <string> surl    = new List <string>();

                            // DISPLAYING JOKES (MAX. 5)

                            List <Value> websearchResult = new List <Value>();
                            for (int i = 0; i < Math.Min(5, phrases.Count); i++)
                            {
                                web_url.Add("https://api.cognitive.microsoft.com/bing/v5.0/search?q=jokes+on+" + phrases.ToArray()[i] + "&count=" + ((int)Math.Floor(5.0 / Math.Min(5, phrases.Count))).ToString() + "&safeSearch=Strict");
                            }
                            for (int i = 0; i < Math.Min(3, phrases.Count); i++)
                            {
                                HttpClient client1 = new HttpClient();
                                client1.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Key); //authentication header to pass the API key
                                client1.DefaultRequestHeaders.Add("Accept", "application/json");
                                string     bingRawResponse  = null;
                                RootObject bingJsonResponse = null;
                                bingRawResponse = await client1.GetStringAsync(web_url.ToArray()[i]);

                                bingJsonResponse = JsonConvert.DeserializeObject <RootObject>(bingRawResponse);
                                websearchResult.AddRange(bingJsonResponse.webPages.value);
                            }
                            if (websearchResult.Count == 0)
                            {
                                //added code to handle the case where results are null or zero
                                reply = activity.CreateReply("Sorry, no jokes today.");
                                await connector.Conversations.ReplyToActivityAsync(reply);
                            }
                            else
                            {
                                // create replies with joke_links
                                string[] number_response = { "The first link to some hilarious jokes -", "Here's the second one -", "Have some more - the third link -", "I think the fourth one would be better -", "And finally, the last one -" };

                                reply = activity.CreateReply("Read these jokes to lighten a bit.");
                                await connector.Conversations.ReplyToActivityAsync(reply);

                                for (int i = 0; i < websearchResult.Count; i++)
                                {
                                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(number_response[i]));

                                    string joke_link = "";
                                    if (websearchResult[i].displayUrl.Contains("http") == false)
                                    {
                                        joke_link = websearchResult[i].name + "\n\n" + "http://" + websearchResult[i].displayUrl + "\n\n" + websearchResult[i].snippet;
                                    }
                                    else
                                    {
                                        joke_link = websearchResult[i].name + "\n\n" + websearchResult[i].displayUrl + "\n\n" + websearchResult[i].snippet;
                                    }
                                    //Reply to user message with image attachment
                                    await connector.Conversations.ReplyToActivityAsync(activity.CreateReply(joke_link));
                                }
                            }


                            // DISPLAYING ONE-LINERS/MEMES aka SORROW-BUSTERS AS IMAGES (MAX. 3)


                            List <ImageResult> imageResult = new List <ImageResult>();
                            for (int i = 0; i < Math.Min(3, phrases.Count); i++)
                            {
                                surl.Add("https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=" + phrases.ToArray()[i] + "+funny+memes&offset=5&count=1&safeSearch=Strict");
                            }
                            for (int i = 0; i < Math.Min(3, phrases.Count); i++)
                            {
                                HttpClient client1 = new HttpClient();
                                client1.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Key); //authentication header to pass the API key
                                client1.DefaultRequestHeaders.Add("Accept", "application/json");
                                string bingRawResponse = null;
                                BingImageSearchResponse bingJsonResponse = null;
                                bingRawResponse = await client1.GetStringAsync(surl.ToArray()[i]);

                                bingJsonResponse = JsonConvert.DeserializeObject <BingImageSearchResponse>(bingRawResponse);
                                imageResult.AddRange(bingJsonResponse.value);
                            }
                            if (imageResult.Count == 0)
                            {
                                //added code to handle the case where results are null or zero
                                reply = activity.CreateReply("It seems that I have run out of sorrow-busters...");
                                await connector.Conversations.ReplyToActivityAsync(reply);
                            }
                            else
                            {
                                // create a reply with one-liner images as attachments
                                string[] number_response = { "Here's the first one", "Then the second...", "And finally the third." };

                                reply = activity.CreateReply("Some sorrow-busters.");
                                await connector.Conversations.ReplyToActivityAsync(reply);

                                for (int i = 0; i < imageResult.Count; i++)
                                {
                                    string Result       = imageResult.ToArray()[i].contentUrl;
                                    var    replyMessage = activity.CreateReply();
                                    replyMessage.Recipient   = activity.From;
                                    replyMessage.Type        = ActivityTypes.Message;
                                    replyMessage.Text        = number_response[i];
                                    replyMessage.Attachments = new List <Attachment>();
                                    replyMessage.Attachments.Add(new Attachment()
                                    {
                                        ContentUrl  = Result,
                                        ContentType = "image/png"
                                    });
                                    //Reply to user message with image attachment
                                    await connector.Conversations.ReplyToActivityAsync(replyMessage);
                                }
                            }
                        }
                    }

                    //////////////////////////////////////////////////////////////////////////////////////////////

                    //asking a random question from the database to the user
                    reply = activity.CreateReply(Global.PopQuestion());
                    await connector.Conversations.ReplyToActivityAsync(reply);

                    //terminating case - when all questions have been asked
                    if (Global.questions[0] == "done")
                    {
                        //averaging the total score
                        Global.total_score = Global.total_score / Global.q_length;

                        //assigning "number of responses" value based on final score
                        int n_response = Global.GetNResponse(Global.total_score);
                        reply = activity.CreateReply("Here's something to cheer you up..." + "\nPlease do have a look!");
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        // DISPLAYING INSPIRATIONAL QUOTES, NUMBER DEPENDING UPON THE RESPONSE

                        //configuring BingImageSearch API - key, url, url_parameters
                        const string Key  = "0cd4df3677d64499b05eda5a4912510a";
                        string       surl = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
                                            + "?q=motivational quotes&offset=" + ((n_response + 1) * 5).ToString() + "&count=" + (n_response * 2).ToString() + "&safeSearch=Moderate";

                        HttpClient client1 = new HttpClient();
                        client1.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Key); //authentication header to pass the API key
                        client1.DefaultRequestHeaders.Add("Accept", "application/json");
                        string bingRawResponse = null;
                        BingImageSearchResponse bingJsonResponse = null;

                        bingRawResponse = await client1.GetStringAsync(surl);

                        bingJsonResponse = JsonConvert.DeserializeObject <BingImageSearchResponse>(bingRawResponse);

                        ImageResult[] imageResult = bingJsonResponse.value;
                        if (imageResult == null || imageResult.Length == 0)
                        {
                            //added code to handle the case where results are null or zero
                            reply = activity.CreateReply("Sorry...could not find any image-quote.");
                            await connector.Conversations.ReplyToActivityAsync(reply);
                        }
                        else
                        {
                            reply = activity.CreateReply("Have a look at some motivational quotes!");
                            await connector.Conversations.ReplyToActivityAsync(reply);

                            // create a reply with image-quotes as attachments
                            var replyMessage = activity.CreateReply();
                            replyMessage.Recipient   = activity.From;
                            replyMessage.Type        = ActivityTypes.Message;
                            replyMessage.Text        = "Hope you like them! Remain motivated!";
                            replyMessage.Attachments = new List <Attachment>();

                            for (int i = 0; i < n_response * 2; i++)
                            {
                                string Result = imageResult[i].contentUrl;
                                replyMessage.Attachments.Add(new Attachment()
                                {
                                    ContentUrl  = Result,
                                    ContentType = "image/png"
                                });
                            }
                            //Reply to user message with image attachment
                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }

                        reply = activity.CreateReply("Keep sharing your experiences :) !!!");
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        reply = activity.CreateReply("Bye! Meet you later!");
                        await connector.Conversations.ReplyToActivityAsync(reply);

                        Environment.Exit(0);
                    }
                }
            }
            else
            {
                //to handle events other than messages
                await connector.Conversations.ReplyToActivityAsync(HandleSystemMessage(activity));
            }

            var response1 = Request.CreateResponse(HttpStatusCode.OK);

            return(response1);
        }