Sunday, February 9, 2020

Google API Translation on Asp.net Controls (Lables,Butttons)

I have a task in which i have to translate a whole page. In this page most are labels and buttons So I used google translator API here is the reference.

You will only be allowed to translate about 100 words per hour using the free API. If you abuse this, Google API will return a 429 (Too many requests) error.

Google Translator API Implementation

Now the second task how i can search labels and button of my page so i need to translate so here is the function i made for labels and button.



For Button Translation :
public void UpdateButtonsforTranslation()
{
    foreach (Control c in Page.Form.Controls)
    {
        if (c is Button)
        {
            Button btn = ((Button)c);
            string text = btn.Text;
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
// make a function of that and passing paramters in which language i want to translate
                    string translatedText = objtranslate.TranslateText(text, "en", "es");
                    btn.Text = translatedText;
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}


For Labels Translation :
public void UpdateLabelsforTranslation()
{
    foreach (Control c in Page.Form.Controls)
    {
        if (c is Label)
        {
            Label lbl = ((Label)c);
            string text = lbl.Text;
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
// make a function of that and passing paramters in which language i want to translate
                    string translatedText = objtranslate.TranslateText(text, "en", "es");
                    lbl.Text = translatedText;
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}