Pages

Thursday, August 22, 2013

Using Google Translator to Change Language in your Website in asp.net

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/

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=nayab;Initial Catalog=master;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=Nayab;Initial Catalog=master;Persist Security Info=True;User ID=sa;Password=sa");
            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.



1 comment: