In this tutorial, we use a translation service.
The text to be translated is sent as an API request.
The translation result is returned in JSON format,
then parsed as a string and passed back to GuiXT.
For the input, we use a text box and later access its content via a long text variable.
The push button calls a .NET (VB/C#) function via an InputScript, which later places the translation result into the long text variable of the second text box.
Inputscript "translate_text.txt":
|
Implementation of the .NET (VB/C#) function:
Change the project type to a class library (DLL):

Also add a reference to System.Text.Json and System.Memory.

Then copy all created DLLs into the directory specified in your GuiXT profile.
The .NET (VB/C#) Coding looks as follows:
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class DeepLClient
{
private readonly HttpClient _httpClient;
private string _apiKey;
private bool apiKeySet = false;
public DeepLClient()
{
_httpClient = new HttpClient();
}
public void SetAPIKey(string apiKey)
{
_apiKey = apiKey;
}
public async Task<string> TranslateAsync(
string text,
string targetLang,
string sourceLang = null)
{
System.Net.ServicePointManager.SecurityProtocol =
System.Net.SecurityProtocolType.Tls12;
var url = "https://api-free.deepl.com/v2/translate";
var content = new StringContent(
BuildRequestBody(text, targetLang, sourceLang),
Encoding.UTF8,
"application/x-www-form-urlencoded"
);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Add("Authorization",
$"DeepL-Auth-Key {_apiKey}");
request.Content = content;
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using (var doc = JsonDocument.Parse(json))
{
return doc.RootElement
.GetProperty("translations")[0]
.GetProperty("text")
.GetString();
}
}
public string Translate(
string text,
string targetLang,
string sourceLang = null)
{
return TranslateAsync(text, targetLang, sourceLang)
.GetAwaiter()
.GetResult();
}
private string BuildRequestBody(
string text,
string targetLang,
string sourceLang)
{
var sb = new StringBuilder();
sb.Append($"text={Uri.EscapeDataString(text)}");
sb.Append($"⌖_lang={targetLang}");
if (!string.IsNullOrEmpty(sourceLang))
{
sb.Append($"&source_lang={sourceLang}");
}
return sb.ToString();
}
}