Using Google Translator to Change Language in your Website

Raj.Trivedi
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 14318 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article we will be using Google Translator to change the Language Dynamically for the pages whose data are being generated from the database.

Introduction


Hello Friends,

Just recently had posted a question in the forum that I wanted to change the language of my website according to the user selection.I did get responses but unfortunately there was not much I get from ASP.NET globalization and localization.After searching through, we came across one blog where there was Google Translator that was powered by Google and was able to change the language of the Blog completely.

Bingo ! That was it, what we needed.

Let us see how we can change the language of the website globally without using Globalization and Localization.

To use Google translator you will have to visit :- https://translate.google.com/manager/website/

Objective


  1. Understanding Google Translator.
  2. Adding it to the website.

Understanding Google Translator and its Features

  1. Instantly translate your website into 60+ languages using Google's Translate
  2. Customize and improve the translation of your website
  3. Collect and use translation suggestions from your users
  4. Invite editors to manage translations and suggestions

Using the code


  1. First you need to go to https://translate.google.com/manager/website/
  2. Then Click on Add to Website, Once you click Add to Website it will ask you to login using your GMail Credentials.
  3. Once You Login it will ask you for you website URL and ask to choose your Default Language for website (Check Screen 1).
  4. Once you add the website URL.Click on Next for Further settings.
  5. The Further settings includes the Look of the Drop Down of selection of Languages, How many Languages you need, Do you want to add google analytics code for tracking traffic (Check Screen 2).
  6. Now we are done with the settings and we will now click on Get Code Button.
  7. Once we Click on the Get Code we get the piece of Code snippet.Now here is the trick to get a Global Conversion we will add the Code Snippet to the Master Page so that it affects all the pages with the content as well :) (Check Screen 3 for Code)




Screen 1




Screen 2







Screen 3





Lets start Implementation

  1. Create a New Empty Website -> Add a Master Page and 2 Web Forms and Include the Master Page to that web form.
  2. Now go to the Head section of the master page and paste the first piece of code snippet
  3. Now once you paste the Head section code. Now paste the second piece of Code snippet on the master page as per your display requirement.
  4. This piece of Code snippet should be inside a DIV Tag.
  5. Now Go to the Content Pages and Bind a Grid from database.(Check the Code for Binding In Code Section 3)
// Head Section of Master Page (Code Section 1)
<meta name="google-translate-customization" content="18e07a495bcfdebb-6e21f50c844b7cb0-g60562cca66703d3b-3b"></meta>
// Second Piece of Code Snippet (Code Section 2)
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, multilanguagePage: true}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
        

Explanation of the Code 

The code is nothing but a JavaScript function which connects to the Google Translator Service, gets the languages based on your selections made in the previous steps and gives the look and feel of the drop down as per selection.


// Code section 3 : Contains Code for 2 Web Forms (HTML Mark Up and Code Behind) with Tables and Stored Procedure.
//Tables and Stored Procedure
-- Countries Table
CREATE TABLE [dbo].[Countries](
	[CountryID] [int] IDENTITY(1,1) NOT NULL,
	[Countries] [varchar](25) NULL
) 

												-- Table for States
create table States
(
StateID int identity(1,1),
States varchar(25)
)


-- Proc to Get Countries
create proc GetCountriesList
as
begin
select * from Countries
end

-- Proc to Get States
create proc GetStates
as
begin
select * from States
end
//HTML Mark Up and Code Behind for Page 1
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="GoogleTranslator.aspx.cs" Inherits="GoogleTranslator" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="font-family: 'Cooper Black'; font-size: x-large; text-align: center;">
        Language Translating of WebSite<br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Countries" HeaderText="Countries" />
            </Columns>

        </asp:GridView><br /><br />
        <asp:HyperLink ID="HyperLink1" NavigateUrl="~/GoogleTranslator2.aspx" runat="server">Next</asp:HyperLink>
        

    </div>
</asp:Content>	
//Code Behind for Page 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class GoogleTranslator : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }

    private void BindGrid()
    {
        try
        {
            // Function to bind the data to Grid.
            SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
            con.Open();
            SqlCommand getcontent = new SqlCommand("GetCountriesList", con);
            getcontent.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(getcontent);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {

        }
    }
}
HTML Mark up and Code Behind for Page 2
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="GoogleTranslator2.aspx.cs" Inherits="GoogleTranslator2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="font-family: 'Cooper Black'; font-size: x-large; text-align: center;" align="center">
        Language Translating of WebSite<br />
        <br />
        <div align="center">
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="States" HeaderText="States" />
            </Columns>

        </asp:GridView>
        </div>
       

    </div>
</asp:Content>

Code Behind for Page 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class GoogleTranslator2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        try
        {
            // Function to bind the data to Grid.
            SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
            con.Open();
            SqlCommand getcontent = new SqlCommand("GetStates", con);
            getcontent.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(getcontent);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {

        }
    }
}

The reason for showing 2 pages is that once you navigate to another page you dont have to select the language again for translation Google does it automatically

OutPut for Page 1 : Showing Default Language English




Selecting Language for Translation : Hindi




Translated Page : Hindi Language




Moving to Next Page : Language Still same as per user preference





Note :- Please go through the Terms of Service of Google to know about more use age.

Link :- http://www.google.com/intl/en/policies/terms/


Conclusion


Note  :- To use this service while you are developing you need to be connected to internet and you will not see the drop down of languages in the design mode.It only shows up dynamically when you run the application.

Reference


https://translate.google.com/manager/website/

Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)