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

Bing Translator service for Windows Phone 7

, 13 Dec 2010
Rate this:
Please Sign up or sign in to vote.
Time for a new Windows Phone tutorial! Today we'll create a simple mobile translator using Bing web services. Our program will load all the available languages and the user will select the desired ones. This tutorial is supposed to be an introduction to using SOAP services, too. I promise that the n

Time for a new Windows Phone tutorial! Today we'll create a simple mobile translator using Bing web services. Our program will load all the available languages and the user will select the desired ones. This tutorial is supposed to be an introduction to using SOAP services, too. I promise that the next one will be about REST services and Google API.

If you wanna try out the Translator immediately, just download the source code. Continue reading to understand what's going on...

Windows Phone 7 Translator in action

Step 1: The user interface

So, let's begin! Launch Visual Studio and create a new Windows Phone 7 portrait application. I named it "WindowsPhoneBingTranslate". The user interface is far from complicated. We only need two list boxes (for language selection), two text boxes (for input and output text) and a button (for translation). You may come up with way different ideas, but the following XAML will do the job:

<StackPanel Orientation="Vertical">
     <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
          <StackPanel Orientation="Vertical">
               <TextBlock>From</TextBlock>
               <ListBox Name="lbxFrom" Height="140"></ListBox>
          </StackPanel>
          <StackPanel Orientation="Vertical">
               <TextBlock>To</TextBlock>
               <ListBox Name="lbxTo" Height="140"></ListBox>
          </StackPanel>
     </StackPanel>
     <TextBox Name="txtInput" Text="" Height="180" />
     <Button Name="btnTranslate" Content="Translate"  
                 Click="btnTranslate_Click" />
     <TextBox Name="txtOutput" Text="" Height="180" />
</StackPanel>

Step 2: Creating the languages source

Each language has two properties: A name (such as "English", "French", "Greek", etc) and a unique code (such as "en", "fr", "el" respectively). An object containing both properties is necessary, so create the following class and place it in a Language.cs file:

public class Language   
{   
    public string Code { get; set; }   
    public string Name { get; set; }   
}

The user needs to see the language name only - and not the code. So, when retrieving the appropriate data, only the Name property will be displayed in the UI. Modify the DataTemplate of the list boxes to achieve this:

<ListBox Name="lbxFrom" Height="140">  
     <ListBox.ItemTemplate>  
          <DataTemplate>  
               <TextBlock Text="{Binding Name}" FontSize="25" />  
          </DataTemplate>  
     </ListBox.ItemTemplate>  
</ListBox>

Moving on to the code-behind .cs file, it's useful to create three placeholders:

private List<string> _codes = new List<string>();   
private List<string> _names = new List<string>();   
private List<Language> _languages = new List<Language>();

Step 3: Using Bing SOAP services

It's time to make some calls to Bing Translate API now. Navigate to Solution Explorer and right click the "References" folder. Select "Add service reference" and type http://api.microsofttranslator.com/V2/Soap.svc into the Address field. Press "Go" to add the reference and have a look at its methods. They seem pretty straightforward, but they are a little bit tricky to use:

Add service reference to Bing Translate

SOAP services, like the one we just imported, use XML to transfer their data. This XML is not directly visible because it is encapsulated (according to WSDL) and exposed to us as simple methods! That's the only thing you need to know about SOAP for now Wink | ;-) .

How do we access these methods? Well, firstly import the reference to the code-behind file: 

using WindowsPhoneBingTranslate.BingTranslateReference;

Importing the proper reference gives access to LanguageServiceClient class. LanguageServiceClient is a proxy which exposes all the supported Bing methods.  

private LanguageServiceClient _proxy = new LanguageServiceClient();

Silverlight uses asynchronous web method invocation. Consequently, the results of each method invocation will be handled separately. Here are the events defined:

_proxy.GetLanguagesForTranslateCompleted +=   
           new EventHandler<GetLanguagesForTranslateCompletedEventArgs>   
                                     (GetLanguagesForTranslateCompleted);   
_proxy.GetLanguageNamesCompleted +=   
           new EventHandler<GetLanguageNamesCompletedEventArgs>   
                                     (GetLanguageNamesCompleted);   
_proxy.TranslateCompleted +=   
           new EventHandler<TranslateCompletedEventArgs>   
                                     (TranslateCompleted);

You can define the above event handlers right in MainPage's constructor. GetLanguagesForTranslateCompleted method is called after MainPage finishes loading.

void MainPage_Loaded(object sender, RoutedEventArgs e)   
{   
    _proxy.GetLanguagesForTranslateAsync(APP_ID);   
}

The method retrieves a list of all the available language codes. It also calls GetLanguageNamesAsync, which returns all the corresponding language names! Here they are:

void GetLanguagesForTranslateCompleted(object sender,   
          GetLanguagesForTranslateCompletedEventArgs e)   
{   
    _codes = e.Result.ToList();   
  
    _proxy.GetLanguageNamesAsync(APP_ID, "en", e.Result);   
}   
  
void GetLanguageNamesCompleted(object sender,   
         GetLanguageNamesCompletedEventArgs e)   
{   
    _names = e.Result.ToList();   
  
    LoadLanguages();   
}

But wait! What is this APP_ID parameter??? Don't worry... It is just a string containing a required unique Bing application identifier. You have to download one from Bing Developer Center (it's free). After clarifying this, let's have a look at LoadLanguages method...

private void LoadLanguages()   
{   
    for (int index = 0; index < _codes.Count; index++)   
    {   
        _languages.Add(new Language   
        {   
            Code = _codes[index],   
            Name = _names[index]   
        });   
    }     lbxFrom.ItemsSource = _languages;   
    lbxTo.ItemsSource = _languages;   
}

Quite easy. It simply creates the proper Language objects and binds them to the list boxes.

Finally, the most important part: Translation! Double click on the UI's button and navigate to its event handler. Find the selected language names, get the corresponding language codes and call TranslateAsync.

private void btnTranslate_Click(object sender, RoutedEventArgs e)   
{   
    Language from = lbxFrom.SelectedItem as Language;   
    Language to = lbxTo.SelectedItem as Language;   
  
    _proxy.TranslateAsync(APP_ID, txtInput.Text, from.Code, to.Code);   
}

TranslateAsync calls Bing, translates the text and, when completed, assigns the translated text to the output text box:

void TranslateCompleted(object sender, TranslateCompletedEventArgs e)   
{   
    txtOutput.Text = e.Result;   
}

Here you are! Download the source code and enjoy.

Windows Phone 7 Translator in action

Resources

License

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

About the Author

Vangos Pterneas
Product Manager LightBuzz
United Kingdom United Kingdom
I'm a Software Engineer and Entrepreneur, passionate about motion technology and the way it can affect people’s lives.
 
I have been a Kinect enthusiast since the release of the very first unofficial hacks and have already published some innovative commercial Kinect applications. These applications include complex home automation systems, 3D body scanning programs and motion-enabled product browsers for businesses.
 
I worked as a Windows developer and consultant for Microsoft Innovation Center and I'm now running my own company, LightBuzz Software. LightBuzz has been awarded the first place in Microsoft’s worldwide innovation competition, held in New York, for effectively combining Kinect and smartphone functionality.
 
When I am not coding, I love writing books, speaking and blogging about my favorite technological aspects.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionInvalid appId Bing Translate PinmemberMaciej Rzepiński23-Oct-12 22:36 
GeneralMy vote of 5 PinmvpKanasz Robert21-Sep-12 0:45 
GeneralMy vote of 5 PinmemberMichael Haephrati27-Jan-12 8:37 
Questionexception problem! PinmemberKaroglan Nurfelak7-Jan-12 11:41 
AnswerRe: exception problem! PinmemberVangos Pterneas8-Jan-12 6:12 
GeneralRe: exception problem! PinmemberKaroglan Nurfelak20-Jan-12 7:21 
QuestionNeed Help Pinmemberirvieboy15-Nov-11 16:19 
AnswerRe: Need Help PinmemberVangos Pterneas15-Nov-11 17:00 
Hello. You cannot create or edit Windows Phone 7 projects from Visual Studio 2008. Download Visual Studio 2010 Express from http://create.msdn.com/en-US/[^] instead. It will be automatically installed when you download the SDK.
 
Regards,
Vangos
GeneralMy vote of 5 PinmemberGergo Bogdan29-May-11 18:03 
GeneralThank you PinmembergWin22-Feb-11 5:24 
GeneralRe: Thank you PinmemberVangos Pterneas22-Feb-11 8:07 

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 | Mobile
Web02 | 2.8.140721.1 | Last Updated 13 Dec 2010
Article Copyright 2010 by Vangos Pterneas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid