QUESTION: Why would the following code work fine in a VS Pro, C# console app but fail in a VS Code Polyglot Notebook C# cell?
I am prototyping C# code in VS Code and Polyglot notebooks to translate text. I have successfully used Polyglot Notebooks to prototype non-Async
C# code in the past.
In a C# notebook cell I have placed Azure's translation endpoint example C# code (which works outside Polyglot Notebook in a console app). That code follows ...
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
private static readonly string translationEndpoint = "https://api.cognitive.microsofttranslator.com";
private static readonly string apiKey = "<API Key here>"; // Replace with your actual API key
public static async Task Main()
{
string sourceText = "Hello, world!";
string targetLanguage = "es-ES"; // Spanish
string translationResult = await TranslateTextAsync("en-US", targetLanguage, sourceText);
if (translationResult != null)
{
Console.WriteLine($"Source text: {sourceText}");
Console.WriteLine($"Target language: {targetLanguage}");
Console.WriteLine($"Translation: {translationResult}");
}
else
{
Console.WriteLine("Translation failed.");
}
}
public static async Task<string> TranslateTextAsync(string sourceLang, string targetLang, string text)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
string payload = $@"
{{
""text"": ""{text}"",
""to"": ""{targetLang}""
}}";
StringContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"{translationEndpoint}/translate?api-version=3.0", content);
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
string translation = responseContent.Substring(1, responseContent.Length - 3); // Extract translation from the JSON response
return translation;
}
else
{
return null;
}
}
}
}
... the only alteration I made was removing the args
parameter from Program.Main( string[] args)
.
Calling Program.Main()
results in the message...
==> Translation Failed
QUESTION: Why would this code work fine in a VS Pro, C# console app but fail in a VS Code Polyglot Notebook C# cell?