Thursday, 20 June 2013

Microsoft Translator Hands-on-Lab

Microsoft Translator Hands-on-Lab
http://www.viawindowslive.com/Articles/Translator/MicrosoftTranslatorHandsonLab.aspx

Online translators enable instant communication between people of different language backgrounds. The amount and quality of worldwide education, collaboration, and purchasing options will surely grow exponentially now that these doors are opening, and your product or service can receive maximum exposure using Microsoft’s machine translation. This lab steps through incorporating the Microsoft Translator into a website or application using four different methods: Web widget, AJAX, HTTP, and SOAP.
WorldWorks is a fictional American company that makes various products including sunglasses. They take advantage of the Web Widget, AJAX, HTTP, and SOAP Translator APIs to make their products available to a worldwide audience on their website. Follow along as we build the WorldWorks translator capability.
This paper begins with a discussion of the web widget. The AJAX, HTTP and SOAP methods are each then demonstrated with sample solutions and corresponding code. The paper concludes with a summary and a section on Common Methods for API Reference.

Contents


Web Widget API

Use the web widget to allow users to translate an entire page on a website. The widget can be customized with different colors, then added to an existing page.

Adding the Web Widget to a Page

Easily add the widget to existing pages using the following steps.
1.       Go to http://microsofttranslator.com/Widget.
2.       Follow the directions on the page (specify the domain name and original language of your site).
3.       Select from the widget width and color options.
4.       Agree to the Microsoft policies and click the Generate Widget code button.
5.       Copy and paste the resulting code into your page where you would like the translation box to appear.

The widget appears like the following and includes a toolbar across the top of the page (toolbar appears after translation). The buttons on the widget allow users to view the Translator widget home page and email the translated material.


Customizing the Web Widget

The web widget can be customized when it is generated from the Microsoft Translator site as seen above, or you can further customize it by changing the below highlighted code behind the widget once it is inserted on your page.
<div id="MicrosoftTranslatorWidget" style="width: 200px; border-color: #000000; background-color: #AFADAE;"><noscript>

<a href="http://www.microsofttranslator.com/BV.aspx">Translate this page</a></noscript></div>

<script id="MicrosoftTranslatorWidgetScript" type="text/javascript"src="http://api.microsofttranslator.com/V1/Widget/.svc/Embed?appId=asdf&from=en"></script>

AJAX API

AJAX is a powerful tool useful for bringing the Microsoft Translator into applications. Since the code performs asynchronously, the translation of a block of text or an entire page appears quickly and seamlessly without a full page reload. With the Translator AJAX API, you can translate an entire page, translate elements of a web page, and/or suppress translation of elements when needed.
To begin, you must obtain an appId for your project to access the Translator. Generate the appId by going to http://www.microsofttranslator.com/Dev/Ajax.



Enter your site address (you can use localhost), click the checkbox to agree to Microsoft’s policies, and copy the generated code. Open an ASP.NET web application project in Visual Studio, and paste the appId snippet within the header code.
Note: If you use localhost as your web address, you will need to generate a new appId and replace the localhost appId when your application goes live.

Translating an Entire Page

You can program a page so that clicking a button to translates the entire page into a specified language. In the case that the selected language matches the current language, the request will be ignored. Use the following code to program this functionality.
1.       Within the HTML tags, add this code to your ASP.NET page to create a drop-down menu including English, French, and German, and a Translate All button.
<table style="width63%;">
      <tr>
                 <td align="right">Select My Language:
<asp:DropDownList runat="server" ID="dropdownlistLanguages">
                     <asp:ListItem Text="English" Value="en"></asp:ListItem>
<asp:ListItem Text="French" Value="fr"></asp:ListItem>
<asp:ListItem Text="German" Value="de"></asp:ListItem>
</asp:DropDownList>
   </td>
           <td align="left">
<asp:Button runat="server" ID="btnTranslate" Text="Translate All"OnClientClick="javascript:translateAll()" />
  </td>
        </tr>
     </table>
2.       Add the following JavaScript code to program the dropdown functionality.
<script type="text/javascript">
function GetSelectedLanguage() {
// find dropdownlist element
var ddl = document.getElementById('<%= dropdownlistLanguages.ClientID %>');
var selected = null;
for (var i = 0; i < ddl.children.length; i++) {
// find 'selected' tag in item's markup
var index = ddl.children[i].outerHTML.indexOf('selected');
if (index > -1) {
// only one item in a dropdownlist can be selected
selected = ddl.children[i];
break;
}
}

// if not defined, return current language
if (!selected) return currentLanguage;

// otherwise select current language
return selected.value;
}
</script>

3.       Add the following code within the script tags to call out to the Translator.
var currentLanguage = "en";
function translateAll() {
// helper function to get value from dropdownlist
var lang = GetSelectedLanguage();
        if (currentLanguage != lang) {
              Microsoft.Translator.translate(document.body, currentLanguage, lang, null);
               // update currentLanguage value
               currentLanguage = lang;
}
}
Once you put some text on the page, with a click of the mouse, a visitor to your site can translate an entire page using the Translate All button.

 

Translating Elements of a Page

You can also allow translation of sections of a page instead of translation of an entire page. To set up the page so that visitors only need to translate the portion pertaining to them, use the following steps.
1.       Add the following code within the script tags.
function translateThis(id) {
var lang = GetSelectedLanguage();
        if (currentLanguage != lang) {  
              // use a callback function to set the translated text
               Microsoft.Translator.translate(
document.getElementById(id).innerText,
currentLanguage,
lang,
function(translation) {
document.getElementById(id).innerText = translation;
});

                // update currentLanguage value
                currentLanguage = lang;
            }
        }
Note that the final parameter of the translate call was replaced with a JavaScript function to update the element’s text with the returned translation.
2.       Use the following code to add a button for translation next to the text on the page. The button will make the call to the translateThis function when clicked.
<tr>
<td style="width384pxtext-aligncenter;">
          <span class="title" id="title2" >Jasmine</span>
<div class="details" id="details2">
The Jasmine sunglasses are perfect for wearing with business attire or casual clothing. The cat eye style never goes out of fashion.
        <div class="translate">
<input runat="server" type="image" id="Image1"onclick="javascript:translateThis('details2');return false;"
src="~/Images/translateItem.png" style="height16pxwidth16px"alt="Translate this Text" /></div>
</div>
<span class="price" >$200.00 USD</span>
</td>
<td>
<img alt="Jasmine Sunglasses" height="119" src="Jasmine.jpg" width="226" />
</td>
</tr>
In the WorldWorks website, the user simply clicks the world icon under each paragraph to translate just the relevant section.

Excluding Translation of Elements on a Page

Explicitly suppress elements on the page by adding an attribute translate=”no” to each element which contains text that should not be translated. In the below sample, the product title and price fields are excluded from the translation process.
<tr>
<td style="width384pxtext-aligncenter;">
   <span class="title" translate="no">Todd</span>
    <div class="details">
    Popular in countries around the world, our best selling Todd sunglasses
are appropriate for both professionals and perfect for the male who
prefers a relaxed look.
</div>
    <span class="price" translate="no">$200.00 USD</span>
</td>
<td>
<img alt="Todd Sunglasses" height="119" src="Todd.jpg" width="226" />
</td>
</tr>
In the following screen shot, the page has been translated to French by pressing the Translate Allbutton, but the title of the products and the prices are still expressed in English.


HTTP API

The HTTP request can be used to perform specialized translations of text. In the case of WorldWorks, a visitor to the site might want to send a message to the company. Since the owners of the company mostly speak English, the original form is in English, but it can be translated using the Microsoft Translator.
For the HTTP interface, you must obtain a Live Search API Application ID. Go tohttp://search.live.com/developers/appids.aspx and sign in with your Windows Live ID. Follow the instructions to generate the necessary code.

 
After clicking Agree to agree to Microsoft’s terms of use, you will be given the application ID for use with the project you indicated.


Use the generated appId in place of the highlighted yourappIdhere text in the code snippets below.
In the following section you will learn how to get a list of supported languages to view which languages are available for translation purposes. You will also see how the HTTP API identifies the language that was submitted through the form.

Getting Supported Languages

You can request to see the supported languages by creating a button and supplying the following code upon button-click.
1.       Start a new ASP.NET web application project in Visual Studio and add using statements for System.Net and System.IO in the aspx.cs file.
2.       Add a button in the aspx file.
3.       Add the following code within the public partial class of the aspx.cs file.  Be sure to generate the button click event by double clicking on the button in the design view of Visual Studio.
protected void Button1_Click(object sender, EventArgs e)
        {
            WebRequest req = System.Net.WebRequest.Create(@"http://api.microsofttranslator.com/V1/Http.svc/GetLanguages?appId=yourappIdhere");
            WebResponse resp = req.GetResponse();
            Stream strm = resp.GetResponseStream();
            StreamReader reader = new System.IO.StreamReader(strm);
            string locales = reader.ReadToEnd();

            lblOutput1.Text = locales;
        }
4.       Then create an output label for the language codes to appear with in the aspx file.
<asp:Label ID="lblOutput1" runat="server" Width="602px"></asp:Label>
5.       After adding some text, your page will resemble the following. Languages will show up in the form of two-digit culture codes upon button-click.

6.       Since not everyone recognizes what these culture codes stand for, it is possible to program the button to display the actual language name instead as demonstrated by the following code. Replace the code from step 1 with the following.
protected void Button1_Click(object sender, EventArgs e)
        {
            WebRequest req = System.Net.WebRequest.Create(@"http://api.microsofttranslator.com/V1/Http.svc/GetLanguageNames?appId=yourappIdhere");
            WebResponse resp = req.GetResponse();
            Stream strm = resp.GetResponseStream();
            StreamReader reader = new System.IO.StreamReader(strm);
            string languages = reader.ReadToEnd();
   
            lblOutput1.Text = languages;
        }
The resulting page and button will appear as follows. Language names are displayed in their own language.

 

Identifying the Message Language

When visitors submit a valid message in their native language to the WorldWorks site on the Contact Us form, the message language can be identified for later translation. This action is completed by making an HTTP request to the Translator service to identify the language code. The message can then be translated to the desired language before being sent as described in the SOAP API: Translating from Multiple Languages section that follows.

Create a Basic Form

To demonstrate the language identification, first create a basic form.
1.       Start a new ASP.NET web application project in Visual Studio and add using statements for System.Net, System.IO, and System.Net.Mail in the aspx.cs file.
2.       Create a text box for the sender’s email by adding the following code between the body tags in the aspx file.
<asp:TextBox ID="txtEmail" runat="server" Width="275px"></asp:TextBox>
3.       Create another text box for the message to send.
<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"
 Width="275px" Height="230px"></asp:TextBox>
4.       Create a label for the confirmation/error messages.
<asp:Label ID="lblError" runat="server" Width="400px"></asp:Label>
5.       Add a button to the form.
<asp:Button ID="Button1" runat="server" Text="Button" />
A basic form based on the code above will look similar to the following and will have the capability of displaying a message when sent.

 

Identify the Message Language

The following code extracts information from the form to send via email to the site administrator. It also generates a WebRequest to use the Detect function of the HTTP service, passing in the appId and the Text to input.
Note: You will need your SMTP host name to test the following sample.
1.       Generate the button click event by double clicking on the button in the design view of Visual Studio.
2.       Add the code from the event below to your own button-click event. Remember to replace the highlighted yourappIdhere code with your appId and change the highlighted email address to your own address so that you will receive the emailed message.

protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                WebRequest req = WebRequest.Create(@"http://api.microsofttranslator.com/V1/Http.svc/Detect?appId=yourappIdhere&text=" + txtInput.Text);
                WebResponse resp = req.GetResponse();
                Stream strm = resp.GetResponseStream();
                StreamReader reader = new System.IO.StreamReader(strm);
                string cultureCode = reader.ReadToEnd();


                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(txtEmail.Text);
                msg.Body = txtInput.Text;
                msg.Subject = "Enquiry, Language: " + cultureCode;
                msg.To.Add(new MailAddress("youremail@domain.com"));

                if (cultureCode != "")
                {
                    SendMessage(msg);
                    lblError.Text = "Message sent.";
                }
            }

            catch
            {
                lblError.Text = "Cannot identify language.";
            }
        }
Note that if the text input by the end user does not resemble valid words, the WebRequest will result in an HTTP error (Code 500). If the text is valid, the response contents will be a two-character culture code.
3.       For the above action to work, we need to set up the SendMessage() method which creates thesmptClient and sends the email. Paste the following method in the apsx.cs file. You will need to change the below highlighted code to represent your own SMTP host, and you may need to supply credentials if required by your SMTP (if so, uncomment the line below).
public void SendMessage(MailMessage msg)
        {
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = "yourSmtpHost";
//smtpClient.Credentials = new System.Net.NetworkCredential("SmtpUsername", "SmtpPassword");
            smtpClient.Send(msg);
        }

In the following screen shot, the page indicates that the message was sent successfully.


In the next section, we will discuss how the Translator can translate the foreign language messages before they are emailed.



SOAP API

The SOAP API is perfect for use when a number of translations of different kinds may need to occur, and since it uses managed code it is a simple solution.
For the SOAP interface, you must obtain a Live Search API App ID. Go tohttp://search.live.com/developers/appids.aspx, sign in with your Windows Live ID, and follow the instruction to generate the appId.


Use the generated text in place of the highlighted yourappIdhere in the following code snippets.

Adding a Service Reference

Before beginning, add a service reference to your project in Visual Studio to the following URL:http://api.microsofttranslator.com/V1/SOAP.svc . Set the Namespace to TranslatorService and clickOK.


Translating from Multiple Languages

Since visitors to the WorldWorks site speak different languages and we have given them the ability to submit queries in their own language, we must provide a way for the administrators of the WorldWorks website to understand the messages received.
Because the languages are currently sent in their native tongue (that’s how we set them up in theHTTP API section), we can create the ability to translate all the messages into the administrator’s language before they are sent.
To translate messages using the SOAP API, use the following code to be executed on the server.

Use the following code to replace the “if” statement that we created for the click event in theIdentifying the Message Language section of the HTTP API section in the aspx.cs file.
if (cultureCode != "en")
                {
                    try
                    {
                        TranslatorService.LanguageServiceClient client = newTranslatorService.LanguageServiceClient();
                        string result = client.Translate("yourappIdhere", txtInput.Text, cultureCode, "en");
                        msg.Body = result;
                    }

                    catch
                    {
                        lblError.Text = "Could not translate your text.";
                    }

                    SendMessage(msg);
                    lblError.Text = "Message sent.";
                }
The administrators of the WorldWorks site (or your site) will now receive a translated email when a user fills in the contact form in a foreign language that is recognized by the Translator. If the Translator does not recognize the text as a valid language, an error message will appear to the user and no email will be sent.

Summary

Microsoft has advanced the logic and technology behind machine translation to create a high-quality tool and made it available to developers wanting to expose information to a larger public.
This hands-on-lab introduced developers to the Microsoft Translator and demonstrated how to use the web widget, AJAX, HTTP, and SOAP APIs to integrate the Translator into a solution. In this case the Translator was used to enhance the American-based WorldWorks website carrying products for sale worldwide. Visitors were able to translate the home page with the web widget, translate the product pages, and read the Contact Us form in their own language. They were also able to send email messages in their native tongue to WorldWorks, and WorldWorks was able to read them in English.
The Microsoft Translator can be used in many scenarios such as in instant messaging translation, travel information sites, and educational activities. Make use of the Translator to enhance your applications and websites, and sell your products and services to an earth wide audience.


Common Methods for API Reference

The following four methods are common to the AJAX, HTTP, and SOAP styles of the Microsoft Translator APIs.
string[] GetLanguages(string appId)
Gets the list of supported languages for which translation may be invoked between any two. The languages listed display as two-character culture codes, such as “de” for German. A full list of culture codes can be found at http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(VS.80).aspx. The appId represents the application identifier used to call the Translator and must be generated specifically for each application.
string[] GetLanguageNames(string appId, string locale)
Gets the list of supported languages and displays them with their full names based on the culture codes. The names are displayed in the language specified by the locale. If no locale is designated, the list will be returned with each language name appearing in its own language.
string Detect(string appId, string text)
Detects the language of the text. There may be cases where the identified text is not supported by the Translator. The text portion represents the text to be identified.

string Translate(string appId, string text, string from, string to)
Translates text from one language to another. If the from portion is null or empty, the Translator will automatically detect the current language. The to portion indicates the output language.

No comments:

Post a Comment