MadhuAcc12 / acc1234

0 stars 0 forks source link

Directline call to the Bot returns Bad Gateway error frequently for a particular time span #1

Open MadhuAcc12 opened 7 years ago

MadhuAcc12 commented 7 years ago

@dandriscoll @nwhitmont

I am having a directline code that calls the bot and returns responses. I am facing an issue where I am intermittently getting Bad Gateway error (502 error) response from the bot. Maximum number of times I receive a response properly but there is a particular time span when I get this error quite frequently and then after that time period everything starts working well again. Can someone help me with this?

`using DirectLineConsole; using DirectLineConsole.Models;

using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Diagnostics;

namespace DirectLineConsole { class RequestOrchestrator { Conversation objconversation = new Conversation();

public static string secret_key = "BotConnector botkey";

public static string Service_URL = "https://directline.botframework.com/api/conversations/";

private static TraceSource _source = new TraceSource("Logs");

static void Main(string[] args)
{

    RequestOrchestrator objprogram = new RequestOrchestrator();

        for (int i = 0; i < 100; i++)
        {
                Console.WriteLine( "*******************************Message Start*************************************");
                _source.TraceEvent(TraceEventType.Information, 0, DateTime.Now.ToString("h:mm:ss tt") + "*******************************Message Start*************************************");
            var task = objprogram.PostMessage("What is drivesafe?").GetAwaiter().GetResult();

        Console.WriteLine("The get static message is " + objprogram.PostMessage("Its 93091").GetAwaiter().GetResult());
                Console.WriteLine("*******************************Message End*************************************");
                _source.TraceEvent(TraceEventType.Information, 0, DateTime.Now.ToString("h:mm:ss tt") + "*******************************Message End*************************************");

        }

        Console.ReadKey();
    Console.ReadLine();

}

private async Task<bool> PostMessage(string message)
{

    bool IsReplyReceived = false;
        _source.TraceEvent(TraceEventType.Information, 0, DateTime.Now.ToString("h:mm:ss tt") + "The question is" + message);
        HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "botkey");
    HttpResponseMessage response = await client.GetAsync("/api/tokens/");
    if (response.IsSuccessStatusCode)
    {
        var conversation = new Conversation();
        response = await client.PostAsJsonAsync("/api/conversations/", conversation);
        if (response.IsSuccessStatusCode)
        {
            CathyDirectConversation ConversationInfo = response.Content.ReadAsAsync(typeof(CathyDirectConversation)).Result as CathyDirectConversation;
                string conversationUrl = ConversationInfo.conversationID + "/messages/";
                Console.WriteLine("The coversation id " + ConversationInfo.conversationID);
                _source.TraceEvent(TraceEventType.Information, 0, DateTime.Now.ToString("h:mm:ss tt") + "The coversation id " + ConversationInfo.conversationID);
                //  string conversationUrl = "Dmf7YaftuyI4fEM6uw9DfP/messages/";
                MessageNew msg = new MessageNew() { text = message };
            response = await client.PostAsJsonAsync(conversationUrl, msg);
            if (response.IsSuccessStatusCode)
            {
                response = await client.GetAsync(conversationUrl);
                    string str = null;
                    if (response.IsSuccessStatusCode)
                {

                    MessageSetNew BotMessage = response.Content.ReadAsAsync(typeof(MessageSetNew)).Result as MessageSetNew;
                    foreach (Message responseMessage in BotMessage.messages)
                    {
                        //MessageBox.Show(responseMessage.text);
                        Console.WriteLine("The response text " + responseMessage.text);
                            str = responseMessage.text;

                    }
                    IsReplyReceived = true;
                }
                    _source.TraceEvent(TraceEventType.Information, 0, DateTime.Now.ToString("h:mm:ss tt") + "The response text " + str);
                    Console.WriteLine("The response text " + str);
                }
        }

    }
    return IsReplyReceived;

}

public string PostStaticMessage(string url)
{
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    webrequest.Method = "POST";
    webrequest.ContentType = "application/json";
    webrequest.Headers.Add("authorization", "BotConnector key");
    string messagestring = "{\r\n  \"id\": \"CCPxkVSjNYx\",\r\n  \"conversationId\": \"CCPxkVSjNYx\",\r\n  \"created\": \"\",\r\n  \"from\": \"Bot1\",\r\n  \"text\": \"what are the policy?\",\r\n  \"channelData\": null\r\n}";
    Console.WriteLine("The mesage string is :" + messagestring);

    using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
    {

        streamWriter.Write(messagestring);
        streamWriter.Flush();
        streamWriter.Close();
    }
    string result = string.Empty;
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
    using (var streamReader = new StreamReader(webresponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    webresponse.Close();
    string strCathyResponseMessage = string.Empty;

    Console.WriteLine("ErrorCode: " + result);

    return strCathyResponseMessage;
}

public string PostMessage(string url, string conversationnewid, string token)
{
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    webrequest.Method = "POST";
    webrequest.ContentType = "application/json";
  webrequest.Headers.Add("authorization", "BotConnector " +token);
    Console.WriteLine("The webrequest header " +webrequest.Headers);

    using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
    {            
        streamWriter.Flush();
        streamWriter.Close();
    }
    string result = string.Empty;
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
    using (var streamReader = new StreamReader(webresponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    webresponse.Close();
    string strCathyResponseMessage = string.Empty;
    Console.WriteLine("ErrorCode: " + result);
    strCathyResponseMessage = GetMessage(Service_URL + conversationnewid + " /messages", conversationnewid, token);

    return strCathyResponseMessage;
}

public string RetrieveUserToken(string url)
{
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    webrequest.Method = "POST";
    webrequest.ContentType = "application/json";
    webrequest.ContentLength = 0;
    webrequest.Headers.Add("authorization", secret_key);
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
    Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
    string result = string.Empty;
    result = responseStream.ReadToEnd();
    Console.WriteLine(result);
    dynamic data = JObject.Parse(result);
    Console.WriteLine(data);

    var conversation = JsonConvert.DeserializeObject<RootObject>(result);
    Console.WriteLine(conversation.conversationId);
    objconversation.conversationId = conversation.conversationId;
    Console.WriteLine("The ConversationId is " + conversation.conversationId);
    objconversation.token = conversation.token;
    Console.WriteLine("The Token is " + conversation.token);
    webresponse.Close();
    return result;
}

public string SendMessages(string url, string conversationid, string token)
{
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    webrequest.Method = "POST";
    webrequest.ContentType = "application/json";
    webrequest.Headers.Add("cache-control", "no-cache");
    webrequest.Headers.Add("authorization", "BotConnector " + token);
    string messagestring = "  {\r\n      \"id\": \"" + conversationid + "|000000000000000001\",\r\n      \"conversationId\": \"" + conversationid + "\",\r\n      \"created\": \"2016-08-11T14:56:25.841238Z\",\r\n      \"from\": \"Bot1\",\r\n      \"text\": \"what are the policy?\",\r\n      \"channelData\": {},\r\n      \"images\": [],\r\n      \"attachments\": [\r\n        {\r\n          \"url\": \"/api/conversations/" + conversationid +"/messages/000000000000000001/attachments/0?t=" + token + "\",\r\n          \"contentType\": \"string\"\r\n        }\r\n      ],\r\n      \"eTag\": \"W/\\\"datetime'2016-08-11T14%3A56%3A25.983312Z'\\\"\"\r\n    \r\n             \r\n}";
    Console.WriteLine("The mesage string is :" + messagestring);
    webrequest.ContentLength = messagestring.Length;

    using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
    {
        streamWriter.Write(messagestring);
        streamWriter.Flush();
        streamWriter.Close();
    }
    string result = string.Empty;
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
    using (var streamReader = new StreamReader(webresponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    webresponse.Close();
    string strCathyResponseMessage = string.Empty;

    Console.WriteLine("ErrorCode: " + result);
    strCathyResponseMessage = GetMessage(Service_URL + conversationid + " /messages", conversationid, token);

    return strCathyResponseMessage;

}

public string GetStaticMessage()
{
    HttpWebRequest getwebrequest = (HttpWebRequest)WebRequest.Create("https://directline.botframework.com/api/conversations/7G4q3AefW67/messages");
    getwebrequest.Method = "GET";
    getwebrequest.ContentType = "application/json";

    getwebrequest.Headers.Add("authorization", secret_key);
    Console.WriteLine("The Get Message WebRequestHeader is " + getwebrequest.Headers);
    Message objmessage;
    try
    {
        HttpWebResponse webresponse = (HttpWebResponse)getwebrequest.GetResponse();
        Console.WriteLine("The Get Message WebrequestResponse is " + webresponse);
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        string result = string.Empty;
        result = responseStream.ReadToEnd();
        Console.WriteLine(result);
        dynamic data = JObject.Parse(result);
        Console.WriteLine(data);
        // Conversation objconversation = new Conversation();
        CathyMessageSet objCathyMessageSet = new CathyMessageSet();
        objmessage = new Message();
        var objMessageSet = JsonConvert.DeserializeObject<Message>(result);
        objmessage.text = objMessageSet.text;
        Console.WriteLine("The GetMessage text response is " + objmessage.text);
        webresponse.Close();
    }
    catch (Exception)
    {

        throw;
    }

    return objmessage.text;
}

public string GetMessage(string serviceurl, string conversationID, string usertoken)
{
    HttpWebRequest getwebrequest = (HttpWebRequest)WebRequest.Create("https://directline.botframework.com/api/conversations/IbMEaVwwJjr/messages");
    getwebrequest.Method = "GET";
    getwebrequest.ContentType = "application/json";
    getwebrequest.Headers.Add("authorization", "BotConnector  botkey");
    Console.WriteLine("The Get Message WebRequestHeader is " + getwebrequest.Headers);
    Message objmessage;
    try
    {
        HttpWebResponse webresponse = (HttpWebResponse)getwebrequest.GetResponse();
        Console.WriteLine("The Get Message WebrequestResponse is " + webresponse);
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        string result = string.Empty;
        result = responseStream.ReadToEnd();
        Console.WriteLine(result);
        dynamic data = JObject.Parse(result);
        Console.WriteLine(data);
        // Conversation objconversation = new Conversation();
        CathyMessageSet objCathyMessageSet = new CathyMessageSet();
        objmessage = new Message();
        var objMessageSet = JsonConvert.DeserializeObject<Message>(result);
        objmessage.text = objMessageSet.text;
        Console.WriteLine("The GetMessage text response is " + objmessage.text);
        webresponse.Close();
    }
    catch (Exception)
    {

        throw;
    }

    return objmessage.text;
}

} }

`

nwhitmont commented 7 years ago

@MadhuAcc12 Please post your question on https://github.com/Microsoft/BotBuilder