Calling Google Translate From ASP.NET
If you want to run through this walkthrough, please follow the guide on setting up our test environment.
Experience Level - Intermediate
Introduction
While the document is very good at explaining what happens when you use Java Script which can translate about 500 characters, there is very little for when you need to translate bigger documents.
When using POST you can increase this to 5000 characters, so we developed our own code to send a post request to the Google API and then receive the translation.
First step, we need to add a class to our App_Code folder and call it Translate, remember with the walkthrough to set the Build Action to Compile.
VB
Imports System.IOImports System.NetImports System.Web.Script.SerializationPublic Class Translate Shared Function GetTranslation(ByVal key As String, ByVal source As String, ByVal target As String, ByVal Text As String) As String ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Dim TranslatedString As String = "" Text = "q=" + Text Dim TranslateRequest As New Uri(String.Format("https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&format=html", key, source, target)) Dim Req As WebRequest = WebRequest.Create(TranslateRequest) Req.Method = "POST" Req.Headers.Add("X-https-Method-Override", "GET") Req.ContentType = "application/x-www-form-urlencoded" Using ReqStr As Stream = Req.GetRequestStream() Dim encoding As New UTF8Encoding() Dim bytes As Byte() = encoding.GetBytes(Text) ReqStr.Write(bytes, 0, bytes.Length) End Using Dim ReturnStr As String Using sr = New StreamReader(Req.GetResponse.GetResponseStream) ReturnStr = sr.ReadToEnd() End Using Dim Reader As New JavaScriptSerializer Dim TranslateJSON As Dictionary(Of String, Object) = Reader.DeserializeObject(ReturnStr) Dim TranslateData As Dictionary(Of String, Object) If TranslateJSON.ContainsKey("data") Then TranslateData = TranslateJSON("data") If TranslateData.ContainsKey("translations") Then For Each pair In TranslateData.Item("translations")(0) TranslatedString = pair.Value.ToString() Next End If End If Return TranslatedString End FunctionEnd Class
Add a page
Within the Pages Section, Add a new page called GoogleTranslate, and then the HTML and code below.
HTML
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title> <script> function UpdateHiddenField(el, id) { nextElSibling(el).value = el.innerHTML; } function nextElSibling(el) { if (el.nextSibling) do { el = el.nextSibling } while (el && el.nodeType !== 1); return el; } </script></head><body> <form id="form1" runat="server"> <div style="max-width:1000px;margin:auto;"> <div style="clear:both;"> <asp:Label ID="KeyLabel" runat="server" AssociatedControlID="LgTo" Text="API Key"></asp:Label> <asp:TextBox ID="KeyValue" runat="server"></asp:TextBox> </div> <div style="float:left;width:50%;background-color:#ddd;"> <div> <asp:Label ID="LgFromLabel" runat="server" AssociatedControlID="LgFrom" Text="From"></asp:Label> <asp:DropDownList runat="server" ID="LgFrom"> <asp:ListItem Text="English" Value="en"></asp:ListItem> <asp:ListItem Text="Français" Value="fr"></asp:ListItem> <asp:ListItem Text="Deutsch" Value="de"></asp:ListItem> </asp:DropDownList> </div> <div style="min-height:400px;border:1px solid #ccc;" contenteditable="true" onkeyup="UpdateHiddenField(this)" id="ContentTextInput" runat="server"></div> <asp:HiddenField ID="ContentText" runat="server"/> </div> <div style="float:left;width:50%;background-color:#ccc;"> <div> <asp:Label ID="LgToLabel" runat="server" AssociatedControlID="LgTo" Text="To"></asp:Label> <asp:DropDownList runat="server" ID="LgTo"> <asp:ListItem Text="English" Value="en"></asp:ListItem> <asp:ListItem Text="Français" Value="fr"></asp:ListItem> <asp:ListItem Text="Deutsch" Value="de" Selected="True"></asp:ListItem> </asp:DropDownList> </div> <div style="min-height:400px;border:1px solid #bbb;" runat="server" id="ContentTrans"></div> </div> <div style="clear:both;text-align:center;"> <asp:Button runat="server" ID="Translation" Text="Translate"/> </div> </div> </form></body></html>
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Protected Sub GetTranslation_Click(sender As Object, e As EventArgs) Handles Translation.Click Dim Key As String = "Your Key" Dim source As String = LgTo.SelectedItem.Text.ToString Dim target As String = LgFrom.SelectedItem.Text.ToString Dim PageText As String = HttpUtility.HtmlDecode(ContentText.InnerHtml) Try ContentTrans.InnerHtml = HttpUtility.HtmlDecode(Translate.GetTranslation(Key, source, target, PageText)) Catch End Try End Sub
What it does
The function requires four inputs, these are your key, language from, language to and the text you want to translate.
We then set the request type, content type, and most importantly add a header to override the get method.
Once this is done, we then send the data as a stream to Google (ReqStr).Now we declare a return string (ReturnStr) to hold the returned JSON from Google, and read the response string into it.
Next step is creating a JavaScriptSerializer, this bit was probably the most confusing, as this was the weakest area of my development skills at the time. What this last section does is pull out each section of text until it gets to the area we want, and the sets our return text as the value returned by Google. This may not be the most elaborate code in the world, so if you work out a way of tidying it up then let me know.
The example populates DIV contents the another. Please note the double decoding (from the editor and Google), and has two text boxes denoting the language to and from.