Dipset
Dipset

Reputation: 15

Microsoft Bot Framework Analytics API call not working

I'm trying to create a translator bot but when I send a message, the bot keeps telling me that the bot code is having an issue. For the moment, I'm just trying to detect the user language and print it in the the chat. Here's the code I've writen:

    async Task DetectLanguage(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;
        string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";

        // create request to Text Analytics API
        HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
        detectLanguageWebRequest.Method = "POST";

        // create and send body of request
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string jsonText = serializer.Serialize(activity);

        string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
        byte[] data = Encoding.UTF8.GetBytes(body);
        detectLanguageWebRequest.ContentLength = data.Length;

        using (var requestStream = detectLanguageWebRequest.GetRequestStream())
            requestStream.Write(data, 0, data.Length);

        HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

        // read and and parse JSON response
        var responseStream = response.GetResponseStream();
        var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
        dynamic jsonResponse = serializer.DeserializeObject(jsonString);

        // fish out the detected language code
        var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
        if (languageInfo["score"] > (decimal)0.5)
            await context.PostAsync(languageInfo["iso6391Name"]);
        else
            await context.PostAsync("No language detected");

        context.Wait(DetectLanguage);
    }

When I'm trying to debug, the line causing problem is this one :

    HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();

And here is the error I have in the console :

    iisexpress.exe Warning: 0 : Service url localhost:63556 is not trusted and JwtToken cannot be sent to it.

Exception thrown: 'System.Net.WebException' in mscorlib.dll

Has somebody ever seen this problem ?

Thanks forward for the help :)

Upvotes: 1

Views: 133

Answers (1)

Nicolas R
Nicolas R

Reputation: 14619

First, a few details about your implementation:

  • I would highly suggest using HttpClient instead of HttpWebRequest (you can read why here)
  • You have good samples of implementing the call of TextAnalytics in the API documentation provided by Microsoft (see at the end of this page)
  • Another option will be to use the Nuget package as indicated in their documentation here. Be careful, it's still in prerelease as the time of writing this answer.

Working answer without needing to define the classes corresponding to the objects used in the API:

private async Task DetectLanguage(IDialogContext context, IAwaitable<IMessageActivity> result)
{
    var msg = await result;
        
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "PUT YOU KEY HERE");

    // Request parameters
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString["numberOfLanguagesToDetect"] = "1";

    // HERE BE CAREFUL ABOUT THE REGION USED, IT MUST BE CONSISTENT WITH YOUR API KEY DECLARATION
    var uri = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/languages?" + queryString;

    // Request body
    var serializer = new JavaScriptSerializer();
    var body = "{ \"documents\": [ { \"id\": \"string\", \"text\": " + serializer.Serialize(msg.Text) + " } ]}";
    var byteData = Encoding.UTF8.GetBytes(body);
    var responseString = "";

    using (var content = new ByteArrayContent(byteData))
    {
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = await client.PostAsync(uri, content);
        responseString = await response.Content.ReadAsStringAsync();
    }

    // fish out the detected language code
    dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);
    var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
    var returnText = "No language detected";

    if (languageInfo["score"] > (decimal) 0.5)
    {
        returnText = languageInfo["iso6391Name"].ToString();
    }
    await context.PostAsync(returnText);

    context.Wait(DetectLanguage);
}

Upvotes: 1

Related Questions