0

I want to translate a given string to a specific language and print the translation to console , but my console prints nothing , I am also trying to catch some error , but my console still prints nothing, anyone know why ? Here are my headers:

using Newtonsoft.Json;
using System.Net.Http;
using NPOI.SS.Formula.Functions;

I have defined the necessary key and region and url attribute inside class block , but it just won't work like this :

public const string subscriptionKey = "mykey";
public const string region = "myregion";
public const string endpoint="https://api.cognitive.microsofttranslator.com/";

mykey consists of my subscription key and myregion consists of my region

Here is my main:

TranslateString();

Here is my implementation of method TranslateString

public static async void TranslateString()
        {
            string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
            string xmlString = "Hello , welcome";
            try
            {
                object[] body = new object[] { new { Text = xmlString } };
                var requestBody = JsonConvert.SerializeObject(body);
                using (var client = new HttpClient())
                using (var request = new HttpRequestMessage())
                {

                    request.Method = HttpMethod.Post;
                    request.RequestUri = new Uri(endpoint + route);
                    request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

                    request.Headers.Add("Ocp-Apim-Subscription-Region", region);


                    HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Success , translated text:");
                        string result = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(result);
                    }
                    else
                    {
                        Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.Message);
            }
Jacobfs
  • 9
  • 4
  • You need to set the `Culture` of the console before printing the translated (non-English) characters. See this [SO answer](https://stackoverflow.com/a/17317921/14973743) – Anand Sowmithiran Dec 18 '22 at 15:45
  • Also, there is a property named as `OutputEncoding` for Console, that you need to set. see this [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.console.outputencoding?view=net-7.0), also check which Font is configured. – Anand Sowmithiran Dec 18 '22 at 15:56
  • Well I figured out something , isn't the problem that I am calling the TranslateString() inside a nonasync method main ? – Jacobfs Dec 18 '22 at 16:05
  • you could make your main to be `async` that returns a Task, then you can use the `await` when you call the TranslateString() method. – Anand Sowmithiran Dec 18 '22 at 16:12
  • Well I would like to do that but I can't my main is configured , is there some another way to do this ? Something like , I would store the translated text (result from the method TranslateString()) to some lets say constructor and I would easily access it everywhere in my code using that method or constructor ? – Jacobfs Dec 18 '22 at 16:13
  • You can change the TranslateString method to return Task, refer this [SO answer](https://stackoverflow.com/a/54349784/14973743) to use the safe way to call your async method and wait on it, since you cannot change your Main method. – Anand Sowmithiran Dec 18 '22 at 16:22
  • I tried the `var result = Task.Run(() => TranslateString().Result` but my console prints this `System.Threading.Tasks.Task1[System.String]` instead of the translated text. – Jacobfs Dec 18 '22 at 16:47
  • Did you try printing `result.ToString()` ? as per your code snippet, did you notice if this text `"Success , translated text:")` was printed in output window? – Anand Sowmithiran Dec 19 '22 at 11:22
  • `"Success , translated text:"` wasn't printed for some reason and the printed result still is `System.Threading.Tasks.Task1[System.String]` – Jacobfs Dec 19 '22 at 17:03
  • I might have fixed it a bit I searched and added this `var result = TranslateString(); result.Wait();` now it prints `"Success , translated text:"` but it still prints `System.Threading.Tasks.Task1[System.String]` – Jacobfs Dec 19 '22 at 17:47
  • Remove the .ToString() after result. The result is a JSON object. – Chris Wendt Dec 19 '22 at 18:05
  • The problem with your original was that main() terminated before TranslateString() could do or deliver anything. – Chris Wendt Dec 19 '22 at 18:06
  • I have come up to some lets say solution , do you think its good to save the result to a txt file and print it to console and then delete the file after the printing the content of the txt file rightaway ? – Jacobfs Dec 19 '22 at 18:26
  • Have TranslateString() deliver the translated string as a result. In main(), await and print that string. Also, pass the string to translate and the target language as parameters to TranslateString(). – Chris Wendt Dec 19 '22 at 18:41
  • Could you demonstrate it on a code please I dont think I follow. – Jacobfs Dec 19 '22 at 18:49

1 Answers1

0

Here is your code with minimal changes to make it produce an output. The relevant change is for TranslateString() to return a Task, so that the main thread waits for the async call to complete. Another option would have been to make this a synchronous call.

This uses the .Net built-in Json serializer instead of Newtonsoft for simplicity.

This compiles as is using .Net7 with C#10, and your key and region filled in.

using System.Net;
using System.Text;
using System.Text.Json;

const string subscriptionKey = "mykey";
const string region = "myregion";
const string endpoint = "https://api.cognitive.microsofttranslator.com/";


Console.WriteLine("Program Start");
await TranslateString();



static async Task TranslateString()
{
    string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
    string xmlString = "Hello , welcome";
    try
    {
        object[] body = new object[] { new { Text = xmlString } };
        var requestBody = JsonSerializer.Serialize(body);
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {

            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            request.Headers.Add("Ocp-Apim-Subscription-Region", region);


            HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Success , translated text:");
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error:" + ex.Message);
    }
}

The output is:

Program Start
Success , translated text:
[{"translations":[{"text":"Bonjour , bienvenue","to":"fr"},{"text":"Sawu , wamukelekile","to":"zu"}]}]

You will need to add deserializing the output.

Chris Wendt
  • 539
  • 3
  • 6