Web design and hosting, database, cloud and social media solutions that deliver business results
  • Business Solutions
    • Robotic Process Automation
    • Software
    • Database Consultancy Services
      • Data Integration
      • Datawarehouse Services
      • Power BI
      • Server Upgrade and DBA Services
    • Web Site Design Services
      • Logo Design
      • Payment Gateways
      • Web Localisation and Translation
      • Web Site Optimisation
      • Web Site Security
      • Technical Tools
    • Cloud Services
      • Amazon Web Services
      • Google Cloud Services
      • Microsoft Azure
    • Microsoft Office
    • Social Media Management and Advice Services
  • Academy
    • Our Test Environment
    • Learning Databases
      • The Basics
      • Get Open Query
      • SQL Server Data
      • SQL Server Maintenance
      • Using SQL Server Dates
      • Using SQL Server Functions
      • Using SQL Server Pivot-Unpivot
      • Technical Tools
    • Learning Web Design
      • Building Ousia Content Management System
      • Using ASP-NET
      • Using CSS
      • Using JavaScript
    • Learning Cloud and IT Services
      • Task Scheduler Error 2147943645
      • Requesting SSL and Generation of PFX file in OpenSSL Simple Steps
    • Using Social Media
      • Asking for a Google Review
      • Changing a Facebook account from personal to business
      • Choosing where to focus Social Media effort
      • Social Media Image Sizes
      • Using Meta Data to set Social Media Images
  • About Us
    • Blog
      • Building an entry level gaming machine
      • Google Core Update Jan 2020
      • Hot Chilli Internet Closure
      • How To Choose Content For Your Website Adverts Leaflets
      • Preventing Online Scam
      • Skimmers of the gig economy
      • The most annoying things about websites on the Internet
      • Top 5 websites for free Vector Graphics
    • Careers
      • Translator English-Portuguese
      • Translator English-Spanish
    • Portfolio
    • Team
      • Adrian Anandan
      • Ali Al Amine
      • Ayse Hur
      • Chester Copperpot
      • Deepika Bandaru
      • Gavin Clayton
      • Sai Gangu
      • Suneel Kumar
      • Surya Mukkamala
čeština (CS)Deutsch (DE)English (EN-US)English (EN-GB)Español (ES)Français (FR)हिंदी (HI)italiano (IT)日本語 (JA)polski (PL)Português (PT)русский (RU)Türk (TR)中国的 (ZH)

Calling Google Translate From ASP.NET

Walkthrough: Calling Google Translate from ASP.NET using POST for longer documents from your code behind.

If you want to run through this walkthrough, please follow the guide on setting up our test environment.

Experience Level - Intermediate

Introduction

The Google Translate API is good for performing fairly complex translations, and while it is not perfect, it will at least give your readers a basic understanding of what you are trying to convey.

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.

View Documentation: View the Google Translate API code

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 declare a return string, create a request URL string which is quickly parsed into a new web request (Req).

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.

Author

Helpful?

Please note, this commenting system is still in final testing.
Copyright Claytabase Ltd 2020

Registered in England and Wales 08985867

Site Links

RSSLoginLink Cookie PolicySitemap

Social Media

facebook.com/Claytabaseinstagram.com/claytabase/twitter.com/Claytabaselinkedin.com/company/claytabase-ltd

Get in Touch

+15125961417info@claytabase.comClaytabase USA, 501 Congress Avenue, Suite 150, Austin, Texas, 78701, United States

Partnered With

The settings on this site are set to allow all cookies. These can be changed on our Cookie Policy & Settings page.
By continuing to use this site you agree to the use of cookies.
Ousia Logo
Logout
Ousia CMS Loader