/ C#

Translate text in C#, using Google Translate, revisited

A long time ago, I wrote a blog post about how to translate text in C# using Google Translate. Since then, an official AJAX API has been released, which is a much better solution. Reading the comments of the blog post indicates that the code was broken quite quickly!

Google’s AJAX Language API, also includes functionality to detect language from a given string. All you can do on translate.google.com you can do via the API. Reading the class reference for the Translation API, for Flash and other Non-Javascript environments gives us the information we need to perform translations from C#. Most important is the URL and the parameters required and accepted.

Another very important thing we can read in the documentation is this:

Applications MUST always include a valid and accurate http referer header in their requests

We must remember to add a valid referrer when making the actual call!

The response object

Google’s AJAX Language APIs uses JSON, and returns a JSON object containing 3 properties:

  • responseData
  • responseDetails
  • responseStatus

This means we need to have some C# objects that we can use to deserialize the JSON returned from Google. I’m using a generic class called GoogleAjaxResponse, with T being the specific class I want the JSON to be deserialized to.

using System.Runtime.Serialization; namespace Milkshake.Integration.Google { /// Defines a response from one of Google's AJAX APIs. /// The type of object, being returned. [DataContract] public class GoogleAjaxResponse { /// /// Gets or sets the response data. /// /// /// The responseData from Google AJAX API Call /// /// The response data. [DataMember(Name = "responseData", Order = 0)] public T ResponseData { get; set; } } }

To deserialize the Translation specific JSON, I use the TranslationResponse class:

using System.Net; using System.Runtime.Serialization; namespace Milkshake.Integration.Google.Translate { /// Defines a response from the Google AJAX Translate API. [DataContract] public class TranslationResponse { /// Initializes a new instance of the class. public TranslationResponse() { this.ResponseStatus = HttpStatusCode.OK; } /// Gets or sets the translated text. /// The translated text. [DataMember(Name = "translatedText", Order = 0)] public string TranslatedText { get; set; } /// Gets or sets the response details. /// The response details. [DataMember(Name = "responseDetails", Order = 1)] public object ResponseDetails { get; set; } /// Gets or sets the response status. /// The response status. [DataMember(Name = "responseStatus", Order = 2)] public HttpStatusCode ResponseStatus { get; set; } } }

Calling the Google AJAX Translate API

To make the actual call, we can use the HttpWebRequest and HttpWebResponse classes.

using System; using System.Globalization; using System.IO; using System.Net; using System.Web; using System.Web.Script.Serialization; namespace Milkshake.Integration.Google.Translate { /// An API Client for the Google AJAX Translate API. public class TranslateApi { /// The JavaScript serializer private JavaScriptSerializer _Serializer = new JavaScriptSerializer(); /// Translates the text. public string TranslateText(string inputText, string sourceLanguage, string destinationLanguage, string referrer, string apiKey) { string requestUrl = string.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}|{2}&key={3}", HttpUtility.UrlEncode(inputText), sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant(), apiKey); try { using (HttpClient http = new HttpClient(requestUrl)) { http.AddReferrer(referrer); http.ExecuteRequest(); string responseJson = http.GetResponseString(); GoogleAjaxResponse translation = this._Serializer.Deserialize<GoogleAjaxResponse>(responseJson); if (translation != null && translation.ResponseData != null && translation.ResponseData.ResponseStatus == HttpStatusCode.OK) { return translation.ResponseData.TranslatedText; } else { return String.Empty; } } } catch { return String.Empty; } } } }

The response JSON and translated text

Doing a simple test, I translate “Hello world” from English to Danish, and I can see that it works like a charm.

image

Professional translations – even via API!
translation agency