Using Google Translate on Windows Phone
Article Metadata
Code Example
Tested with
Compatibility
Article
This article shows how to use the Google translate web service in Windows Phone applications.
Contents |
Introduction
I have been browsing the web to find a free translator service, that I can use. I have finally found a solution and implemented it in Windows Phone 8. (I haven't tested on WP7 devices). It uses Yahoo Query Language to access Google translate service . The limit of using this service is 20000 queries/IP address/hour. No registration is required, as it's a public service. See the google.translate table on http://www.datatables.org.
Implementation
You'll need to add two files to your project. The main class and an event argument class. Additionally, Json.NET is requied for the class to work. It's a free package.
Translator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using YourNameSpace;
public delegate void TranslatedString(TranslatedStringEventArgs e);
namespace YourNameSpace
{
class Translator
{
public event TranslatedString TranslatedString;
public string translatingString;
// Supporting function to make the URI generation simpler.
private Uri constructUri(string to, string text)
{
string url = @"http://query.yahooapis.com/v1/public/yql?q=" + Uri.EscapeDataString("select * from google.translate where q=\"" + text + "\" and target=\"" + to + "\";") + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
return new Uri(url, UriKind.Absolute);
}
public void TranslateString(string to, string text)
{
// getting the translation via YQL, setting up a WebClient for this
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(constructUri(to, text));
translatingString = text;
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// getting a new class to return and filling in the inital translate string
TranslatedStringEventArgs tsea = new TranslatedStringEventArgs();
tsea.initialString = translatingString;
// checking if the translation succeeded
if (e.Error == null)
{
// setting the return values
tsea.Error = false;
tsea.ErrorMessage = "";
//helper variables for converting
string resultString = "";
byte[] byteArrayForResultString = new byte[e.Result.Length];
//converting the returned value to string - that's what Json.NET eats
e.Result.Read(byteArrayForResultString, 0, Convert.ToInt32(e.Result.Length));
resultString = UTF8Encoding.UTF8.GetString(byteArrayForResultString, 0, byteArrayForResultString.Length);
// try to parse the results
try
{
// doing the actual work
Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(resultString);
// Since everything is called "json" in the json array (pretty straightforward, but not that practical if you ask me),
// we have to navigate to our string manually.
tsea.translatedString = ((((((((((((((((Newtonsoft.Json.Linq.JContainer)(obj)).First).First).Last).First).First).First).First).First).First).First).First).First).First).First).ToString();
}
// handle the exceptions if there are
catch (Exception serializer_exception)
{
tsea.Error = true;
tsea.ErrorMessage = "Error in JSON Serializing: " + serializer_exception.Message + Environment.NewLine + resultString;
}
}
else
{
tsea.Error = true;
tsea.ErrorMessage = "Error in WebClient: " + e.Error.Message;
}
TranslatedString(tsea);
}
}
}
TranslatedStringEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YourNameSpace
{
public class TranslatedStringEventArgs:EventArgs
{
public string initialString { get; set; }
public string translatedString {get; set; }
public bool Error { get; set; }
public string ErrorMessage { get; set; }
}
}
Usage
The usage is very simple. As shown below, instantiate the Translator object t and pass the language and string to be translated as arguments to TranslateString.
Translator t = new Translator();
t.TranslatedString += t_TranstlatedString;
t.TranslateString("de","How are you?");
Here is the translated event handler,
void t_TranstlatedString(TranslatedStringEventArgs e)
{
if (e.Error == false)
{
MessageBox.Show(e.translatedString);
}
else
{
MessageBox.Show(e.ErrorMessage, ":(", MessageBoxButton.OK);
}
}
Source code
You can download the source code for the example here: File:TranslatorExample.zip


Contents
Croozeus - Some comments
Hi molbal
Thanks for the article. I've tidied up the article and sub-edited it.
As a comment in general, I think it's worth a mention why YQL was used here, and Google translate APIs weren't used directly - perhaps because the Google translate APIs doesn't support both JSON and XML output? If there's no reason in particular, we can mention the possibility of using directly google APIs too! I think the introduction is the right place to mention this.
I did couple of edits, please check if OK and here are few comments:
PankajRegards
croozeus 07:48, 12 February 2013 (EET)
Molbal - Thanks for tidying it up
Hi,
Thank you for making the article more professional. I'm going to check the code on WP7, too. I'l also add, that "Newtonsoft.Json" is requied.
I choosed YQL, because it provides free access too the Google translate service, while Google's own APIs are paid only. Of course I'm going to pack it up and upload an example.
Thanks, Regards,
Balintmolbal 16:07, 12 February 2013 (EET)
Croozeus - Cool!
Hi Balint,
Thanks for the explanation re Google translate vs YQL APIs. I've added a note to the introduction to reflect this. Please check if OK.
Let me know after you've tested it on WP7, I'll rename the article. And would be great to have the buildable example uploaded for others to try.
Regards
Pankajcroozeus 11:05, 13 February 2013 (EET)
Molbal - Added requied changes
Hi,
I have added an exmaple, that shows the usage on Windows Phone 7. It has a minor modification, "System.Threading.Tasks" is no longer used, since it's only supported in WP8. I've also uploaded a WP7 project, and it works well. I forgot I used Json.Net (A free package available), so I placed a similar note block as You did with the YQL explanation. Could you please move the download link in an appropriate place and rename the article?
Thank you! Regards,
Bálintmolbal 12:00, 13 February 2013 (EET)
Croozeus - Thank you!
Thanks for checking it for WP7. The Json.Net information is useful, thanks for adding. Just moved it to implementation section where we mention what files are required. I renamed the article to "Using Google Translate on Windows Phone".
Regarding the source code, I checked your Skydrive link - it has only a Speech Example. Did you upload the sample code there yet?
You can directly upload the zip to our wiki, so that you don't have to maintain it on your skydrive forever. Here's the upload link, http://www.developer.nokia.com/Community/Wiki/Special:Upload
Regards
Pankaj.croozeus 12:20, 13 February 2013 (EET)
Molbal - My bad!
I screwed it up. I am working on a speech-to-speech translation and made this class for that project. It was a reflex I gave that name insted of Translation example. That's the corrent file, I'll rename everything in it and then upload it to the wiki. (I didn't know about it yet)
Thanks for the link and taking care of my clumsiness. Regards,
Bálintmolbal 12:27, 13 February 2013 (EET)
Molbal - Fixed
Hi Pankaj,
I have fixed the errors :) Regards,
Bálintmolbal 16:43, 13 February 2013 (EET)
Croozeus - Awesome!
Hi Bálint,
That's great. Thanks very much for adding it. I added source-code link it to the ArticleMetaData as well.
Looking forward to your other contributions to the Wiki!
Regards
Pankajcroozeus 08:26, 14 February 2013 (EET)