Google have released a lovely little API for their Google Translate service. It uses a RESTful interface and returns a JSON object in the HTTP Response. The usual way to use this would be AJAX-style in client side JavaScript. This might not always be what you want to do though. For example, if you have a server resource in English and you want to show it in the page as Spanish you wouldn't want to render it in English and then have some page load event client side to translate it. You really want to do it server side and render it on the page as Spanish straight away.

Of course, Google know this and so they have provided a couple of snippets on their Google code site for PHP and Java. It should probably be expected, but they decided not to provide a nice .NET snippet. Looking around on the web, I can't find any .NET snippets for it and so I did some digging myself to put together a solution.

Before I throw out the snippet, it's worth explaining briefly what JSON is and what libraries are available. JSON is an object definition 'language' similar conceptually to XML in that it is effectively name tags / value pairs but it has the added advantage that it is part of the JavaScript language definition and can be 'eval'ed in JavaScript to give you a client-side object. This is great for AJAX websites. Whilst you could cook your own JSON handler, there are a few JSON libraries out there for .NET. In fact, Windows Communication Foundation has some JSON support built-in. The only problem is that most of the libraries out there are to do with serializing and deserializing .NET objects as JSON objects. That's fine as far as it goes, but it relies on you already having a well-defined .NET type. With Google Translate, we are getting a JSON object as a string that has no well-known .NET type to deserialize to. It might be possibly in theory to map it to an object or even map it to XML but I explored those options and found them incredibly convoluted.

Thankfully you don't need to write your own little JSON parser though because I did find one library out there to do the job, LitJSON. It has a couple of the usual serializer/deserializer features but in addition it also has a feature to parse JSON into a simple hashtable/array. I tried to do something similar with JSON to XML with WCF but couldn't get it to work. One of my colleagues, Stephen Horsfield, did - and I've included his technique after mine.

And so to the code. The snippet below assumes that you are running this in a web form with the following four web controls:

  • txtSource - textbox for source text
  • txtTranslated - textbox for translated text
  • ddlFrom - drop down list with the 2-letter language values for the source language
  • ddlTo - drop down list with the 2-letter language values for the destination language

Of course you could easily swap these with command line args or whatever you like. I have put the snippet in C# and the .NET 2.0 framework, but of course you could rework it for VB.NET or even for .NET 1.0.

   1: // do a check to make sure that we aren't making Google unhappy
   2: if (txtSource.Text.Length > 500)
   3: {
   4:     throw new Exception("Google Translation license forbids more than 500 characters to be translated at once!");
   5: }
   6:  
   7: // create the web request to the Google Translate REST interface
   8: WebRequest oRequest = WebRequest.Create("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + HttpUtility.UrlEncode(txtSource.Text) + "&langpair=" + ddlFrom.SelectedValue + "%7C" + ddlTo.SelectedValue);
   9:  
  10: // make the web call
  11: WebResponse oResponse = oRequest.GetResponse();
  12:  
  13: // grab the response stream
  14: StreamReader oReader = new StreamReader(oResponse.GetResponseStream());
  15:  
  16: // put the whole response in a string
  17: string sContent = oReader.ReadToEnd();
  18:  
  19: // parse the string into the litJSON simple object model
  20: JsonData oData = JsonMapper.ToObject(sContent);
  21:  
  22: // write out the translated text
  23: txtTranslated.Text = oData["responseData"]["translatedText"].ToString();

You could enhance this by using the Google Translate API call to auto-detect the source language, but for simplicity I haven't bothered with that extra step.

So lets see what it would look like with WCF. You'll need to include a using statement for System.IO, System.Xml and System.Runtime.Serialization.Json (and reference the appropriate DLLs):

   1: XmlDocument doc = new XmlDocument();
   2: XmlDictionaryReader xr = JsonReaderWriterFactory.CreateJsonReader(s,
   3: XmlDictionaryReaderQuotas.Max);
   4: doc.Load(xr);
   5: xr.Close();
   6: s.Close();

For more details see the complete post on Steve's blog.

And that is how easy it is to call Google Translate from .NET! I'm currently thinking of some funky ways that I could integrate it with the EPiServer Edit mode. There are all sorts of possibilities. Suggestions on a postcard of how you might want it to look. Maybe a right-click option on the navigation tree? Maybe an extra button in the editor? Maybe something that catches the event when a language for a page is created?

Lastly, a tip on the 2-letter languages. I used the System.Globalization feature of .NET to create the drop down lists with their names. Snippet below:

   1: CultureInfo [] aCultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
   2:  
   3: foreach (CultureInfo oCulture in aCultures)
   4: {
   5:     if (ConfigurationManager.AppSettings["SupportedLanguages"].IndexOf(oCulture.TwoLetterISOLanguageName) >= 0)
   6:     {
   7:         ListItem oItem = new ListItem(oCulture.EnglishName, oCulture.TwoLetterISOLanguageName);
   8:  
   9:         ddlFrom.Items.Add(oItem);
  10:         ddlTo.Items.Add(oItem);
  11:     }
  12: }

All that is needed after that is a line in the web.config like so:

   1: <appSettings>
   2:   <add key="SupportedLanguages" value="ar,bg,zh,hr,cs,da,nl,en,fi,fr,de,el,hi,it,ja,ko,no,pl,pt,ro,ru,es,sv"/>
   3: </appSettings>

Hope this is useful to someone. There's a whole load more that could be done such as error checking and catching but that is for a later post once I work out how far I can take this.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Tuesday, May 20, 2008 4:20 PM | in .NET/C# Techie EPiServer

Comments

Gravatar
# re: Google Translate and .NET
Posted by bzlm
on 5/20/2008 7:30 PM
Dude, what's with the "oRequest" notation? Aren't you afraid 1997 will call and want it back?
Gravatar
# re: Google Translate and .NET
Posted by F
on 5/21/2008 7:28 AM
Great work as always!

You mentioned "Maybe a right-click option on the navigation tree" as a plugin to EPiServer.

Is it possible to extend the right-click menu on the edit-tree with plugin-areas or do you have to make changes to episervers controls?
Gravatar
# re: Google Translate and .NET
on 5/22/2008 3:55 PM
You might prefer to use the .NET 3.5 libraries (in particular Windows Communication Foundation) which offers native JSON support.

The code to construct an XML document from a JSON stream looks like the following. You'll need to reference a couple of assemblies, too:

System.Runtime.Serialization (3.0)
System.ServiceModel.Web (3.5)

using System.IO;
using System.Xml;
using System.Runtime.Serialization.Json;

The following code assumes an input stream 's':

XmlDocument doc = new XmlDocument();
XmlDictionaryReader xr = JsonReaderWriterFactory.CreateJsonReader(s,
XmlDictionaryReaderQuotas.Max);
doc.Load(xr);
xr.Close();
s.Close();

You can find a full example on my blog, also on this site.
Gravatar
# Google Translate API for .NET 0.1
Posted by iron9light
on 6/3/2008 11:30 AM
Google Translate API for .NET
http://code.google.com/p/google-language-api-for-dotnet/

Support all the translate and detect functions.

Download here:
http://google-language-api-for-dotnet.googlecode.com/files/GoogleTranslateAPI_0.1.zip
Gravatar
# re: Google Translate and .NET
Posted by rashmi
on 7/23/2008 9:32 AM
this is rashmi, from mumbai asp.net developer, i got ur reference from codeproject.com ..

we are developing website name: www.discareuropa.com this has to develop in asp.net & 2 diff. language English & Español

we have converted english to Español..through google translator (java script) and html pages are working fine..


Problem:-
but if we use server side control..then we are getting problem

How you can see the problem:-
1st Translator language from English to Español, you will notice every thing change to Español....then put user name: admin password: admin (left side)

and page will redirected to lighterBrand.aspx ..and page is auto refreshing and converting into Espanol, (as we want) ..but auto refreshing it is not stoping, ..

so kindly help me how can i stop this...

thanks/rashmi
Gravatar
# re: Google Translate and .NET
Posted by liam
on 8/10/2008 7:31 AM
You can try a more complete .Net wrapper for Google Language API called GAPI.Net

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 8 and 2 and type the answer here: