2

I want to translate text in Indian languages. I have gone through many articles but can not understand clearly how to do so. I have also seen some articles on google translator but none of them provide guide to use it in code. Please guide me how can I do so. Do I need to add fonts for all languages in my application?

I have pasted the following code and now getting error. Can't understand what is that error. The error is "Index and length must refer to a location within the string. Parameter name: length".

Below is my code.

 public string TranslateText(string input, string languagePair)
 {
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = System.Text.Encoding.UTF8;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
    result = result.Substring(0, result.IndexOf("</div"));
    return result;
}
protected void btnTranslate_Click(object sender, EventArgs e)
{
    string convertTo="en|"+ddlLanguages.SelectedValue;
    txtTarget.Text = TranslateText(txtLanguage.Text, convertTo);
}

ID of both the textboxes are "txtLanguage" for source language and "txtTarget" for target language.

Microsoft Developer
  • 5,229
  • 22
  • 93
  • 142

2 Answers2

4

Why not try these?

google-language-api-for-dotnet

http://code.google.com/p/google-language-api-for-dotnet/

Translate text in C#, using Google Translate

http://dnknormark.net/post/Translate-text-in-C-using-Google-Translate.aspx

Google Translator

http://www.codeproject.com/KB/IP/GoogleTranslator.aspx

Translate your text using Google Api's

http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx

Calling Google Ajax Language API for Translation and Language Detection from C#

http://www.esotericdelights.com/post/2008/11/Calling-Google-Ajax-Language-API-for-Translation-and-Language-Detection-from-C.aspx

Translation Web Service in C#

http://www.codeproject.com/KB/cpp/translation.aspx

Using Google's Translation API from .NET

http://www.reimers.dk/blogs/jacob_reimers_weblog/archive/2008/06/18/using-google-s-translation-api-from-net.aspx

Link

Community
  • 1
  • 1
PraveenVenu
  • 8,217
  • 4
  • 30
  • 39
0

The application needs a XML FIle with words and keys. I created a folder "Globalization" to input XML files with dictionary list

enter image description here

The XML file scructure is bellow

enter image description here

enter image description here

enter image description here Class translate configurations

using System.IO;
using System.Threading;
public class TranslateConfigurations
{
    public string Extension { get; set; } = ".xml";
    public string Culture { get { return Thread.CurrentThread.CurrentUICulture.Name; } }
    public string Path { get; set; } = @$"{Directory.GetCurrentDirectory().Split("bin")[0]}\Globalization\";
}

This is a method to translate strings inside a XML dictionary in application path.

using domain.translate.Configurations;
using domain.translate.Contracts.Business;
using domain.translate.Utilities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;

public class TranslateBusiness : ITranslateBusiness
{
    private readonly ILogger<string> _logger;
    private readonly TranslateConfigurations _translateConfiguration;

    /// <summary>
    ///     
    /// </summary>
    /// <param name="logger"></param>
    public TranslateBusiness(ILogger<string> logger)
    {
        _logger = logger;
        _translateConfiguration = new TranslateConfigurations();
    }

    /// <summary>
    ///     Translate string with string culture
    /// </summary>
    /// <param name="wordKey"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Translate(string wordKey, string strCulture)
    {
        try
        {
            var culture = !string.IsNullOrEmpty(strCulture) ? new CultureInfo(strCulture) : throw new CultureNotFoundException();

            return Messages.GenerateGenericSuccessObjectMessage("Translate", GetXmlSection(wordKey, culture.Name), 200);
        }
        catch (FileNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o arquivo de tradução '{strCulture}'.", 404, wordKey);
        }
        catch (CultureNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a cultura '{strCulture}'.", 404, wordKey);
        }
        catch (KeyNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a chave '{wordKey}' no arquivo de tradução.", 404, wordKey);
        }
        catch (DirectoryNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o caminho do arquivo de tradução.", 404, wordKey);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return (e.Message != null && e?.InnerException?.Message != null) ? Messages.GenerateGenericErrorMessage(e.Message, e.InnerException.Message) : Messages.GenerateGenericErrorMessage(e.Message ?? e.InnerException.Message);
        }
    }

    /// <summary>
    ///     Translate string list with string culture
    /// </summary>
    /// <param name="wordKeys"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Translate(List<string> wordKeys, string strCulture)
    {
        try
        {
            var culture = !string.IsNullOrEmpty(strCulture) ? new CultureInfo(strCulture) : throw new CultureNotFoundException();

            return Messages.GenerateGenericSuccessObjectMessage("Translate", GetXmlSection(wordKeys, culture.Name), 200);
        }
        catch (FileNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o arquivo de tradução '{strCulture}'.", 404);
        }
        catch (CultureNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a cultura '{strCulture}'.", 404, wordKeys);
        }
        catch (KeyNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existem as chaves no arquivo de tradução.", 404, wordKeys);
        }
        catch (DirectoryNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o caminho do arquivo de tradução.", 404);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return (e.Message != null && e?.InnerException?.Message != null) ? Messages.GenerateGenericErrorMessage(e.Message, e.InnerException.Message) : Messages.GenerateGenericErrorMessage(e.Message ?? e.InnerException.Message);
        }
    }

    #region Private methods

    /// <summary>
    ///     Get 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    private string GetXmlSection(string key, string culture = null)
    {
        XDocument doc = XDocument.Load($"{_translateConfiguration.Path}{culture ??_translateConfiguration.Culture}{_translateConfiguration.Extension}");
        var section = doc.Descendants().ToList().Where(n => n.FirstAttribute.Value == key);
        return section.FirstOrDefault()?.Value ?? throw new KeyNotFoundException();
    }

    /// <summary>
    ///     
    /// </summary>
    /// <param name="keys"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    private Dictionary<string, string> GetXmlSection(List<string> keys, string culture = null)
    {
        var dictionary = new Dictionary<string, string>();

        XDocument doc = XDocument.Load($"{_translateConfiguration.Path}{culture ?? _translateConfiguration.Culture}{_translateConfiguration.Extension}");

        foreach (var key in keys)
        {
            var section = doc.Descendants().ToList().Where(n => n.FirstAttribute.Value == key);
            dictionary.Add(key, section.FirstOrDefault().Value);
        }

        return dictionary.Count > 0 ? dictionary : throw new KeyNotFoundException();
    }

    #endregion Private methods
}

Message class

public static class Messages
{
    public static object GenerateGenericSuccessObjectMessage(string propertyName, object objectResult, int statusCode)
    {
        var property = new ExpandoObject() as IDictionary<string, object>;
        property.Add("Code", statusCode);
        property.Add(propertyName, objectResult);

        return property;
    }

    public static object GenerateGenericErrorMessage(string message, int statusCode, object objectResult)
    {
        return new { Error = new { Code = statusCode, Translate = objectResult, Message = message } };
    }

    public static object GenerateGenericErrorMessage(string message, int statusCode)
    {
        return new { Error = new { Code = statusCode, Message = message } };
    }

    public static object GenerateGenericErrorMessage(string message)
    {
        return new { Error = new { Code = 400, Message = message } };
    }

}

Tasso Mello
  • 347
  • 2
  • 5