Translate table data form one language to another

Hi Team,
I have a POC task to convert the table records from one language to other. I tried using Azure cognitive API translator service ,but I couldn’t able to invoke the storage key and url in x++ code. Can I get some reference to follow?

On the other hand I followed the below link,
https://community.dynamics.com/forums/thread/details/?threadid=3cd7602f-9ea8-4b90-8d8c-30684deae6bd
to do the translation,but I am getting error in the URL declaration. next to _sourceLang with the error message " ) is expected".

Please give us a more detail description of your problem than just “I couldn’t able to invoke the storage key”. For example, if you got an exception, share with us the exception type, the message and where the error was thrown from.

Also, show us your code demonstrating the problem.

JSon/ Winhttp classes are throwing error when I tried to use the api services. Instead of creating a console application / nugertuget packages any other options to use the URL and storage key in the x++ code

Hi Martin,
I am using the below code to access the Api service,
class AzureTranslator
{
///


/// Translates text from one language to another using Azure Cognitive Services Translator API.
///

/// The text to be translated.
/// Source language code (e.g., “en”).
/// Target language code (e.g., “fr”).
/// Translated text.
public static str translateText(str textToTranslate, str fromLanguage, str toLanguage)
{
str translatedText;
str azureEndpoint = “https://api.cognitive.microsofttranslator.com/translate?api-version=3.0”;
str subscriptionKey = “<Your_Azure_Subscription_Key>”;
str region = “<Your_Azure_Region>”; // Example: “eastus”
str fullUrl = azureEndpoint + “&from=” + fromLanguage + “&to=” + toLanguage;

    // Create JSON request body
    str jsonBody = strFmt("[{ \"Text\": \"%1\" }]", textToTranslate);

    // Create HTTP client
    System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
    System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(
        System.Net.Http.HttpMethod::Post,
        fullUrl
    );

    // Set headers
    request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
    request.Headers.Add("Ocp-Apim-Subscription-Region", region);
    request.Headers.Add("Content-Type", "application/json");

    // Set request body
    System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
    System.Byte[] byteArray = utf8.GetBytes(jsonBody);
    request.Content = new System.Net.Http.ByteArrayContent(byteArray);
    request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

    // Send the request
    System.Net.Http.HttpResponseMessage response = httpClient.SendAsync(request).Result;
    if (response.IsSuccessStatusCode)
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(response.Content.ReadAsStreamAsync().Result);
        str jsonResponse = reader.ReadToEnd();

        // Parse JSON response
        System.Text.Json.JsonArray jsonArray = System.Text.Json.JsonArray::Parse(jsonResponse);
        System.Text.Json.JsonObject jsonObject = jsonArray.Get(0).Get("translations").Get(0);
        translatedText = jsonObject.Get("text").GetString();
    }
    else
    {
        throw error(strFmt("Azure Translator API error: %1", response.ReasonPhrase));
    }

    return translatedText;
}

}

Getting header near request.headers.add with error “( expected”

Hi Martin,
could you please add your suggestion

First of all, let me re-post your code with correct formatting:

class AzureTranslator
{
    ///
    /// Translates text from one language to another using Azure Cognitive Services Translator API.
    ///

    /// The text to be translated.
    /// Source language code (e.g., "en").
    /// Target language code (e.g., "fr").
    /// Translated text.
    public static str translateText(str textToTranslate, str fromLanguage, str toLanguage)
    {
        str translatedText;
        str azureEndpoint = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0";
        str subscriptionKey = "<Your_Azure_Subscription_Key>";
        str region = "<Your_Azure_Region>"; // Example: "eastus"
        str fullUrl = azureEndpoint + "&from=" + fromLanguage + "&to=" + toLanguage;

        // Create JSON request body
        str jsonBody = strFmt("[{ \"Text\": \"%1\" }]", textToTranslate);

        // Create HTTP client
        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(
            System.Net.Http.HttpMethod::Post,
            fullUrl
        );

        // Set headers
        request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
        request.Headers.Add("Ocp-Apim-Subscription-Region", region);
        request.Headers.Add("Content-Type", "application/json");

        // Set request body
        System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
        System.Byte[] byteArray = utf8.GetBytes(jsonBody);
        request.Content = new System.Net.Http.ByteArrayContent(byteArray);
        request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

        // Send the request
        System.Net.Http.HttpResponseMessage response = httpClient.SendAsync(request).Result;
        if (response.IsSuccessStatusCode)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(response.Content.ReadAsStreamAsync().Result);
            str jsonResponse = reader.ReadToEnd();

            // Parse JSON response
            System.Text.Json.JsonArray jsonArray = System.Text.Json.JsonArray::Parse(jsonResponse);
            System.Text.Json.JsonObject jsonObject = jsonArray.Get(0).Get("translations").Get(0);
            translatedText = jsonObject.Get("text").GetString();
        }
        else
        {
            throw error(strFmt("Azure Translator API error: %1", response.ReasonPhrase));
        }

        return translatedText;
    }
}

Then please give us the requested information about the error.

Getting error near request.headers.add(
"Invalid token ‘(’

I think you’re trying to say that you can’t even compile your code, because you’re getting a compilation error when you call Add() method. Accessing request.Headers works.

Have I managed to provide the correct problem description on your behalf?

If so, notice what description you could have provided. For example, it’s important to say that it’s a compilation error and not a runtime error. You can also do some basic analysis before asking for help.

You can fix that by splitting the line to two statements:

HttpRequestHeaders headers = request.Headers;
headers.Add(...);

getting error near
request.content.headers.contenttype = new System.Net.

Error:

invalid token ‘=’

system.net.http.httpresponsemessage response = httpClient

Error:
Invalid token response

Your code request.content.headers.contenttype has two problem:

  • You’re again chaining the .NET Interop property accessors, which doesn’t work. You need to split it to individual statements, as I showed in my last reply.
  • You have wrong letter case (e.g. it should be Headers instead of headers).

Regarding Invalid token response, it sounds like a runtime exception, but you again failed to provide necessary details. And there is no point trying to run your code if you can’t even compile it.

line 33. invalid token=
line 36 invalid token response
line 37 qualifier response is not valid for field issuccessstatuscode.
line 39 qualifier response is not valid for the content
line 44 the name system.text.json.jsonobject doesn’t denote a class,a table

I’m sorry, but there is nothing I can do for you if you’re unable to share necessary information.

Sorry Martin,i didn’t get you point to capture the compiler error

Now I don’t know what you mean. Please elaborate.

I am getting so many build errors related to the .net interoperability classes,but I am not sure how to get rid of those .The one which you had explain to split, it worked for me and for others I tried to investigate but it’s not working. Can I get any references to follow this? the above code giving so many errors in X++ code editor.

First of all, apply the solution (that we discussed before) to other instance of the same problem. Your problem with request.content.headers.contenttype showed that you didn’t do it.

Simplify your code with using statement(s). For example, add using System.Net.Http; at the top of the file so you can than refer to - for instance - System.Net.Http.HttpResponseMessage type by mere HttpResponseMessage.

Then compile your code again and pay close attention to compiler errors.

If you need help, show us your code and tell us where exactly you get a compilation error and what the error message says. Saying that you have an error at line 33 is useless if you don’t tell us what code you have at line 33. Then no one can help you.

Don’t try to deal with all errors at once. Focus on one at a time, fix it, fix other instances of te same problem and then move to the next bug.

When sharing code, put ``` on the lines above and below the block of code.

using System.Net.Http;
using System.Text.Json;
using System.IO;
public class TranslatorService
{
/// The text to be translated.
/// Source language code (e.g., “en”).
/// Target language code (e.g., “fr”).
/// Translated text.
public static str translateText(str textToTranslate, str fromLanguage, str toLanguage)
{
str translatedText;
str azureEndpoint = “https://api.cognitive.microsofttranslator.com/”;
str subscriptionKey = “”;
str region = “eastus”; // Example: “eastus”
str fullUrl = azureEndpoint + “&from=” + fromLanguage + “&to=” + toLanguage;

// Create JSON request body
str jsonBody = strFmt("[{ \"Text\": \"%1\" }]", textToTranslate);

// Create HTTP client

HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod::Post,
fullUrl
);
Headers.HttpRequestHeaders headers = request.Headers;
// Set headers
headers.Add(“Ocp-Apim-Subscription-Key”, subscriptionKey);
headers.Add(“Ocp-Apim-Subscription-Region”, region);
headers.Add(“Content-Type”, “application/json”);
// Set request body
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
System.Byte byteArray = utf8.GetBytes(jsonBody);
request.Content = new ByteArrayContent(byteArray);
////// Blocking the below code - Error near “=” & response
“” request.Content.Headers.ContentType =new MediaTypeHeaderValue(“application/json”);

// Send the request

HttpResponseMessage response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result);
str jsonResponse = reader.ReadToEnd();

/////
// Parse JSON response
JsonArray jsonArray = JsonArray::Parse(jsonResponse);
JsonObject jsonObject = jsonArray.Get(0).Get(“translations”).Get(0);
translatedText = jsonObject.Get(“text”).GetString();
}
else
{
throw error(strFmt(“Azure Translator API error: %1”, response.ReasonPhrase));
}

return translatedText;

}
}

Hi Martin,
I have pasted the code properly but somehow; it got overlapped sorry for the confusion.

Please follow my instruction. The first step should have been fixing the bug with property chaining that we discussed before. You didn’t fix it and that’s why your code is failing on request.Content.Headers.ContentType.

Let me re-post your code once again (when I already wasted time fixing the formatting). There are also a few code improvements that you should use.

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.IO;

public class TranslatorService
{
    /// The text to be translated.
    /// Source language code (e.g., "en").
    /// Target language code (e.g., "fr").
    /// Translated text.
    public static str translateText(str _textToTranslate, str _fromLanguage, str _toLanguage)
    {
        str translatedText;
        str azureEndpoint = 'https://api.cognitive.microsofttranslator.com/';
        str subscriptionKey = '';
        str region = 'eastus';
        str fullUrl = strFmt('%1&from=%2&to=%3', azureEndpoint, _fromLanguage, _toLanguage);

        // Create JSON request body
        str jsonBody = strFmt('[{ "Text": "%1" }]', _textToTranslate);

        // Create HTTP client
        HttpClient httpClient = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod::Post, fullUrl);
        
        Headers.HttpRequestHeaders headers = request.Headers;
        
        // Set headers
        headers.Add('Ocp-Apim-Subscription-Key', subscriptionKey);
        headers.Add('Ocp-Apim-Subscription-Region', region);
        headers.Add('Content-Type', 'application/json');
        
        // Set request body
        UTF8Encoding utf8 = Encoding::UTF8;
        System.Byte byteArray = utf8.GetBytes(jsonBody);
        request.Content = new ByteArrayContent(byteArray);
        
        ////// Blocking the below code - Error near "=" & response
        request.Content.Headers.ContentType =new MediaTypeHeaderValue('application/json');

        // Send the request
        HttpResponseMessage response = httpClient.SendAsync(request).Result;
        if (response.IsSuccessStatusCode)
        {
            StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result);
            str jsonResponse = reader.ReadToEnd();

            // Parse JSON response
            JsonArray jsonArray = JsonArray::Parse(jsonResponse);
            JsonObject jsonObject = jsonArray.Get(0).Get('translations').Get(0);
            translatedText = jsonObject.Get('text').GetString();
        }
        else
        {
            throw error(strFmt("Azure Translator API error: %1", response.ReasonPhrase));
        }

        return translatedText;

    }
}

Hi Martin,
Now the error got solved, after fixing the below code,
Headers.HttpContentHeaders content = request.Content.Headers;
content.ContentType = new MediaTypeHeaderValue(“application/json”);

Getting another error, near JSONArray (name doesnot denote a class/EDT/a table)
JsonArray jsonArray = JsonArray::Parse(jsonResponse);
JsonObject jsonObject = jsonArray.Get(0).Get(“translations”).Get(0);