Click here to Skip to main content
Click here to Skip to main content

WPF Language Translator

, 4 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
A WPF application that translates text using the Bing Translation API.

Screenshot_1.png

Introduction

In this article I will describe how to go about using the Bing Translation API to develop a WPF application that provides text translation functionality.

Bing Translation API

The Bing Translation API is a service that provides instant text translation, language detection, collaborative translation[^] functionality, and text-to-speech in multiple languages. The API is currently used by some high profile websites like Facebook and eBay.

The Bing translation service is offered in various usage volume levels. High-volume usage of the service is offered at a price while it is free for low-volume usage and hobbyist use.

NB: While use of the Bing Translation API is free for low-volume usage, this is not a future guarantee. Item 14 in the Bing Web Service API Terms of Use states in part, "... We (Microsoft) may change (including by removing features or charging fees for features previously provided free), update, or enhance (collectively, "modify") the services at any time... ".

Using the Bing Translation API

In order to make use of the Translation API, you need to acquire a Bing AppID, which is free. To get a Bing AppID, go here[^], sign in with your Windows Live ID, fill out and save the application form to generate an AppID, and enable the ID.

The URL that you'll use to access the translation service should be in the following form:

http://api.microsofttranslator.com/v2/Http.svc/Translate?Parameters

The URL has four parameters which must be specified:

  • appId: The Bing AppID for your application
  • text: The text to be translated
  • from: The language to translate from, in the form of an ISO 639-1 Language Code
  • to: The language to translate to, in the form of an ISO 639-1 Language Code

The eventual URL should look something like the following:

http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=1A2345B6789C2345B6789&text=Translate Me&from=en&to=es

Supported Languages

The following table shows the languages currently (as of the time of writing) supported by the Translator API and their ISO 639-1 Language Codes:

Language Code
Arabic ar
Czech cs
Danish da
German de
English en
Estonian et
Finnish fi
Dutch nl
Greek el
Hebrew he
Haitian Creole ht
Hindi hi
Hungarian hu
Indonesian id
Italian it
Japanese ja
Korean ko
Lithuanian lt
Latvian lv
Norwegian no
Polish pl
Portuguese pt
Romanian ro
Spanish es
Russian ru
Slovak sk
Slovene sl
Swedish sv
Thai th
Turkish tr
Ukranian uk
Vietnamese vi
Simplified Chinese zh-CHS
Traditional Chinese zh-CHT

WPF Language Translator

Using the translator application is a simple affair. Just run the app, enter the text you want to translate, specify the languages, and click on the Translate button to display the translated text.

Screenshot_2.png

How it Works

The GetTranslatedText() method in class Translator makes a call to the Bing Translator service and returns a string containing the translated text.

VB.NET

''' <summary>
''' Get translated text from Bing Translator service.
''' </summary>
''' <param name="textToTranslate">Text to translate.</param>
''' <param name="fromLang">Language to translate from.</param>
''' <param name="toLang">Language to translate to.</param>
''' <returns>Translated text</returns>
Public Function GetTranslatedText(ByVal textToTranslate As String, ByVal fromLang As String, _
                               ByVal toLang As String) As String
    Dim translation As String

    ' Translate only if specified languages are different.
    If (fromLang <> toLang) Then
        Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" & _
                        appID & "&text=" & textToTranslate & "&from=" & fromLang & "&to=" & toLang

        Dim request As HttpWebRequest = CType(WebRequest.Create(uri), HttpWebRequest)

        Try
            Using response As WebResponse = request.GetResponse
                Dim strm As Stream = response.GetResponseStream
                Using sr As New StreamReader(strm)
                    translation = sr.ReadToEnd
                End Using
            End Using
        Catch ex As WebException
            MessageBox.Show("Ensure that you are connected to the internet.", _
                            "Translator", MessageBoxButton.OK, MessageBoxImage.Stop)
            Exit Function
        End Try
    Else
        MessageBox.Show("Will not translate to the same language.", "Translator", _
                        MessageBoxButton.OK, MessageBoxImage.Exclamation)
        Exit Function
    End If

    ' Parse string into an XElement and get the XElement Value
    ' which is returned as the translated text.
    Return (XElement.Parse(translation).Value)
End Function

C#

/// <summary>
/// Get translated text from Bing Translator service.
/// </summary>
/// <param name="textToTranslate">Text to translate.</param>
/// <param name="fromLang">Language to translate from.</param>
/// <param name="toLang">Language to translate to.</param>
/// <returns>Translated text.</returns>
public string GetTranslatedText(string textToTranslate, string fromLang, string toLang)
{
    string translation;

    if (fromLang != toLang)
    {
        string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" +
                    appID + "&text=" + textToTranslate + "&from=" + 
                    fromLang + "&to=" + toLang;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

        try
        {
            WebResponse response = request.GetResponse();
            Stream strm = response.GetResponseStream();
            StreamReader sr = new StreamReader(strm);
            translation = sr.ReadToEnd();

            response.Close();
            sr.Close();
        }
        catch (WebException)
        {
            MessageBox.Show("Ensure that you are connected to the internet.",
                        "Translator", MessageBoxButton.OK, MessageBoxImage.Stop);
            return (string.Empty);
        }
    }
    else
    {
        MessageBox.Show("Will not translate to the same language.", 
                        "Translator", MessageBoxButton.OK, 
                        MessageBoxImage.Exclamation);
        return (string.Empty);
    }

    // Parse string into an XElement and get the XElement Value
    // which is returned as the translated text.
    return (XElement.Parse(translation).Value);
}

After setting the value of the string variable, translation, we will end up with an XML string that looks something like the following:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Translated Text</string>

I then use the XElement.Parse() method to parse the XML string into an XElement object and return the translated text, using the XElement Value property.

NB: You will first need to set the value of the appID field in the class Translator before running the project available from the downloadable source.

VB.NET

' Specify your Bing AppId
Private appID As String = ""

C#

// Specify your Bing appId
private string appID = "";

The Translator class also contains a property that returns a List(Of Language) / List<Language> object that is used to set the ItemsSource property of the language combo boxes.

VB.NET

''' <summary>
''' Returns a List(Of Language)
''' </summary>    
Public ReadOnly Property LanguageList() As List(Of Language)
    Get
        Return (langList.OrderBy(Function(l) l.lang).ToList)
    End Get
End Property

C#

/// <summary>
/// Returns a List<Language>
/// </summary>
public List<language> LanguageList
{
    get
    {
        return (langList.OrderBy(l => l.lang).ToList());
    }
}

The class Language contains two fields and overrides ToString().

VB.NET

Public Class Language
    Public lang As String
    Public langCode As String

    Public Overrides Function ToString() As String
        Return (lang)
    End Function
End Class

C#

class Language
{
    public string lang;
    public string langCode;

    public override string ToString()
    {
        return (lang);
    }
}

The List(Of Language) / List<Language> object in the class Translator is populated by the PopulateLanguageList() method that is called by the class' constructor.

VB.NET

Private Sub PopulateLanguageList()
    langList.Add(New Language With {.lang = "Arabic", .langCode = "ar"})
    langList.Add(New Language With {.lang = "Czech", .langCode = "cs"})
    langList.Add(New Language With {.lang = "Danish", .langCode = "da"})
    langList.Add(New Language With {.lang = "German", .langCode = "de"})        
    ...
End Sub

C#

private void PopulateLanguageList()
{
    langList.Add(new Language {lang = "Arabic", langCode = "ar"});
    langList.Add(new Language {lang = "Czech", langCode = "cs"});
    langList.Add(new Language {lang = "Danish", langCode = "da"});
    langList.Add(new Language {lang = "German", langCode = "de"});
    ...
}

I use this approach to make it easier to get the ISO Language Codes based on the languages specified in the combo boxes.

VB.NET

fromLang = CType(FromLanguageCmbBox.SelectedValue, Language).langCode
toLang = CType(ToLanguageCmbBox.SelectedValue, Language).langCode

C#

fromLang = ((Language)FromLanguageCmbBox.SelectedValue).langCode;
toLang = ((Language)ToLanguageCmbBox.SelectedValue).langCode;

Conclusion

That's it, I hope that you have picked up something useful from this article.

History

  • 2nd Jan, 2012: Initial post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Meshack Musundi
Software Developer
Kenya Kenya
Meshack is an avid programmer with a bias towards WPF and VB.NET. He has about 5 years of programming experience initially starting off with Java before shifting to .NET, thanks to the allure of WPF. He currently resides in a small town in Kiambu county, Kenya.
 
Awards;
  • CodeProject MVP 2013
  • CodeProject MVP 2012
  • Best VB.NET article of January 2015
  • Best VB.NET article of August 2013
  • Best VB.NET article of February 2013
  • Best VB.NET article of October 2012
  • Best VB.NET article of July 2012
  • Best VB.NET article of February 2012
  • Best VB.NET article of January 2012
  • Best VB.NET article of November 2011
  • Best VB.NET article of June 2011
  • Best VB.NET article of May 2011
  • Best VB.NET article of March 2011
  • Best VB.NET article of February 2011
  • Best VB.NET article of January 2011
  • Best VB.NET article of December 2010
  • Best VB.NET article of November 2010

Comments and Discussions

 
Questionfind solution for my problem PinmemberMember 1027248014-Sep-13 21:45 
Questionfind solution for my problem PinmemberMember 1027248014-Sep-13 21:41 
AnswerRe: find solution for my problem PinmvpMeshack Musundi15-Sep-13 6:46 
QuestionApp ID? PinmemberCaiser Mahmood14-Sep-13 0:50 
AnswerRe: App ID? PinmvpMeshack Musundi14-Sep-13 5:40 
SuggestionAPI change, project should be updated. PinprofessionalVictor Rene29-Jun-13 0:47 
GeneralRe: API change, project should be updated. PinmvpMeshack Musundi30-Jun-13 8:29 
GeneralRe: API change, project should be updated. PinprofessionalVictor Rene30-Jun-13 8:46 
GeneralRe: API change, project should be updated. PinmemberCaiser Mahmood14-Sep-13 8:56 
GeneralMy vote of 5 Pinmemberleiyangge26-Jun-13 20:53 
GeneralRe: My vote of 5 PinmvpMeshack Musundi27-Jun-13 0:26 
Questionhow can i get permanent solution for "Ensure that you are connected to the internet." problem Pinmemberashid das1120-Jun-13 2:50 
AnswerRe: how can i get permanent solution for "Ensure that you are connected to the internet." problem PinmvpMeshack Musundi20-Jun-13 9:28 
QuestionAwesome... PinmemberJαved14-Feb-13 21:51 
GeneralRe: Awesome... PinmvpMeshack Musundi17-Feb-13 8:01 
QuestionApp ID Problem [modified] PinmemberSatish Kumar Mishra30-Nov-12 20:28 
AnswerRe: App ID Problem PinmvpMeshack Musundi1-Dec-12 20:53 
QuestionMy Vote of 5 PinmemberAlirezaDehqani31-Oct-12 1:10 
GeneralRe: My Vote of 5 PinmvpMeshack Musundi31-Oct-12 7:51 
QuestionappID problem Pinmembermcjj2314-Sep-12 20:57 
Generalhlep me Pinmemberkamran598-Sep-12 11:46 
GeneralRe: hlep me Pinmembermcjj2313-Sep-12 22:34 
GeneralRe: hlep me PinmvpMeshack Musundi14-Sep-12 0:46 
GeneralMy vote of 5 Pinmember@k@ ?28-Feb-12 5:08 
GeneralRe: My vote of 5 PinmvpMeshack Musundi1-Mar-12 21:27 
GeneralMy vote of 5 PinmentorMd. Marufuzzaman7-Feb-12 20:52 
GeneralRe: My vote of 5 PinmvpMeshack Musundi9-Feb-12 20:49 
GeneralNice effort PinmemberLakamraju Raghuram6-Feb-12 17:40 
GeneralRe: Nice effort PinmvpMeshack Musundi6-Feb-12 21:35 
GeneralMy vote of 5 PinmemberJαved6-Feb-12 9:58 
GeneralRe: My vote of 5 PinmvpMeshack Musundi6-Feb-12 21:33 
GeneralMy vote of 5 PinmemberSteve Maier6-Feb-12 4:22 
GeneralRe: My vote of 5 PinmvpMeshack Musundi6-Feb-12 21:31 
GeneralMy vote of 5 PinmemberJan Zumwalt11-Jan-12 13:40 
GeneralRe: My vote of 5 PinmvpMeshack Musundi12-Jan-12 5:36 
QuestionNice article PinmemberRatish Philip4-Jan-12 1:17 
GeneralRe: Nice article PinmemberMeshack Musundi4-Jan-12 2:00 
QuestionGreat Article :) PinmemberKelvin Armstrong3-Jan-12 22:13 
GeneralRe: Great Article :) PinmemberMeshack Musundi4-Jan-12 0:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150326.1 | Last Updated 4 Jan 2012
Article Copyright 2012 by Meshack Musundi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid