Exemplo n.º 1
0
        /// <summary> Pack Actions to Messages </summary>
        private static void PackActionsToMessages(List <Task> asyncTransactionsInProcess, DataContext db, Table <ActionSentiment> actionSentimentTable, ActionToAnalyze[] actions)
        {
            // Pack Actions into Messages
            WatsonMessage message = new WatsonMessage();

            foreach (ActionToAnalyze actionToAnalyze in actions)
            {
                // ActionSentiment already exists or emtpy?
                bool duplicateActionSentiment = actionSentimentTable.Where(u => u.ActionID == actionToAnalyze.ActionID).Any();
                if (duplicateActionSentiment)
                {
                    WatsonEventLog.WriteEntry("duplicate ActionID in ActionSentiment table " + actionToAnalyze.ActionID, EventLogEntryType.Error);
                }
                if (duplicateActionSentiment || (actionToAnalyze.WatsonText().Length == 0))
                {
                    actionToAnalyze.DeleteOnSubmit(db);
                    db.SubmitChanges();
                    continue;
                }

                // add action to message?
                Task task = PackActionToMessage(actionToAnalyze, ref message);
                if (task != null)
                {
                    asyncTransactionsInProcess.Add(task);   // wait for watson results
                    //break;    // uncomment to test with a single HTTP post
                }
            }

            // Send the remainder message if mostly full
            if (message.UtteranceCount > 40)
            {
                SendMessage(ref message);
            }
        }
Exemplo n.º 2
0
        /// <summary> Pack Action to Message </summary>
        private static Task PackActionToMessage(ActionToAnalyze actionToAnalyze, ref WatsonMessage message)
        {
            Task result = null;

            // Action fit into a single utterance?
            Utterance utterance;

            if (actionToAnalyze.TryGetUtterance(out utterance))
            {
                // Utterance fit into message?
                if (!message.TryAdd(actionToAnalyze, utterance))
                {
                    result = SendMessage(ref message);               // send this one
                    if (!message.TryAdd(actionToAnalyze, utterance)) // start a new message
                    {
                        Debugger.Break();
                    }
                }
            }
            else
            {
                // multiple utterances
                List <Utterance> utterances = actionToAnalyze.PackActionToUtterances();
                if (!message.TryAdd(actionToAnalyze, utterances))
                {
                    result = SendMessage(ref message);                // send this one
                    if (!message.TryAdd(actionToAnalyze, utterances)) // start a new message
                    {
                        Debugger.Break();
                    }
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        static Task SendMessage(ref WatsonMessage message)
        {
            ++MessageCount;
            //Debug.WriteLine(String.Format("HTTP_POST {0} {1}", MessageCount, message.ToString()));
            WatsonMessage tmp    = message;
            Task          result = HTTP_POST(tmp);

            message = new WatsonMessage();
            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Post to IBM watson with Authorization and JSON formatted utterances to process
        /// </summary>
        static async Task HTTP_POST(WatsonMessage message)
        {
            if (message.Empty)
            {
                return;
            }

            //Create Json Readable String with user input:
            string result      = String.Empty;
            string jsonContent = String.Empty;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // credentials
                    var Auth      = WatsonUsername + ":" + WatsonPassword;
                    var byteArray = Encoding.ASCII.GetBytes(Auth);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                    // JSON content
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // Make Post call and await response
                    jsonContent = message.ToJSON();
                    using (var response = await client.PostAsJsonAsync(WatsonGatewayUrl, JObject.Parse(jsonContent)))
                    {
                        HttpContent content = response.Content;
                        result = await content.ReadAsStringAsync() ?? " ";

                        UtteranceToneList watsonResponse = JsonConvert.DeserializeObject <UtteranceToneList>(result);

                        // publish results to DB
                        message.PublishWatsonResponse(watsonResponse);
                        _actionsAnalyzed += message.ActionCount;
                    }
                }
            }
            catch (Exception ex)
            {
                WatsonEventLog.WriteEntry("********************: Error during watson analysis:", ex);
                if (!String.IsNullOrEmpty(jsonContent))
                {
                    WatsonEventLog.WriteEntry(jsonContent);
                }
                if (!String.IsNullOrEmpty(result))
                {
                    WatsonEventLog.WriteEntry(result);
                }
                Console.WriteLine(ex.ToString());
            }
        }