Walkthrough: Writing a Web App with Microsoft Translator

Creating a Web Application with Translation provided by Microsoft Translator.

In this Walkthrough you’ll learn how to create a Web application that uses the Microsoft Translator API to translate text that was input by the user, as well as the Microsoft Translator Widget to translate the pages of the application for you. You’ll build the page using ASP.NET and the free Visual Studio Express 2012 for Web. If you already have a Visual Studio installation, you’ll still be able to follow the tutorial, just skip step 1.

Before beginning, you’ll need to sign up for the Microsoft Translator API in the Windows Azure Marketplace. There are a number of different offerings, including a free one, and you can see how to sign up for the free service, register your app and get your credentials here:

http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx

The Client ID and Client Secret that you generate here will be used in Step 6, so keep a note of them.

Step 1. Getting Visual Studio Express 2012 for Web.

The best way to get started is to visit http://www.asp.net/downloads and select the ‘Install Now’ button in the ‘Get Everything with One Simple Install’ section.

clip_image001

This will launch the Web Platform Installer which will install Visual Studio, ASP.NET, MVC and a whole host of other goodies that you can use to build web sites.

Step 2. Create the Web Application

Run Visual Studio and from the File menu, select ‘New Project’. You’ll see a dialog containing a list of different projects that are available for you to build web sites with. Select ‘Visual C#’ on the left, and then select ‘ASP.NET Web Forms Application’ from the list.

clip_image003

Give your Web Application a name, such as ‘Translator’, and press ‘OK’. Visual Studio will now create everything you need to build and run the Web Application. Press F5 to build and run the application and you’ll see something like this:

clip_image005

In the next step(s), you’ll modify this page to provide machine based translation of the entire page using the Microsoft Translator Widget.

Step 3. Generate the Microsoft Translator Widget

The Microsoft Translator Widget provides Machine-based translation for your entire page or site, using a widget that your end users will select their desired language on. The widget will then translate all the text content of the page into the desired language.

The widget is completely free, and you can create one at http://www.microsofttranslator.com/widget.

There are some details you’ll need to fill out to get the widget.

In the first section, you’ll need to specify your web site. If you are running this on a development machine, simply specify http://localhost. If you know where you will deploy the site on the internet, use that address instead. You should also specify your site language.

clip_image007

In the next section, you have options about how the widget should be displayed, along with a preview. The most important thing to note here are the translation settings:

1. Manual means that the end-user must select the desired language and press the arrow button to trigger a translation. You’ll use that setting in this walkthrough.

2. Notify means that if the widget detects that the browser language is different from the page language, it will give the user a dialog asking if they want to translate the page

3. Auto means that if the widget detects that the browser language is different from the page language, it will translate it without giving the user a choice.

clip_image009

 

The next section, ‘Collaborative Translations’ is greyed out. Collaborative translations provides a framework that allows you to bring human translators into the system to improve the machine translations generated by Microsoft Translator. You will not use it in this walkthrough, but if you want to see it in action, and learn how to set it up, take a look at these tutorials:

http://blogs.msdn.com/b/translation/p/ctf1.aspx [Getting Started with the Widget]

http://blogs.msdn.com/b/translation/p/ctf2.aspx [Using the Widget with CTF on a WordPress site]

Finally, at the bottom of the page, you’ll see the ‘Generate Widget’ section. This has a checkbox that you have to check if you agree to the Microsoft Translator Terms of use. If you agree to these terms, check the box, and some HTML will be generated for you. This HTML will provide the widget to your end users.

clip_image011

Copy the HTML from the right hand side of the screen. You’ll need it in the next section where you will use it to add the widget to your site.

Step 4. Add the Widget to your Site

ASP.NET includes a concept called Master Pages. A master page is like a template that determines what every page looks like. If you played with the web application you created in step 2, you would have noticed that all of the pages have a common header and footer, as well as other common attributes like the navigation and logo across the top. Instead of building these for every page, you put them on the master page, and then every page will inherit them.

So, to add the widget to your entire site, just add it to the master page.

The master page is called ‘Site.master’. You can find it in your Solution Explorer here:

clip_image012

Open it up, and you’ll see HTML defining the common attributes for the pages. To place the widget into the body of every page, find the div with the id attribute set to “body”. It should look like this:

    <div id="body">
        <asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
        <section class="content-wrapper main-content clear-fix">
            <asp:ContentPlaceHolder runat="server" ID="MainContent" />
        </section>
    </div>

Then, above the <asp:ContentPlaceHolder> tag, paste the widget HTML you generated earlier. It should look something like this:

    <div id="body">
        <div id="MicrosoftTranslatorWidget" style="width: 200px; […] <asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
        <section class="content-wrapper main-content clear-fix">
            <asp:ContentPlaceHolder runat="server" ID="MainContent" />
        </section>
    </div>

Now press F5 to run your site, and you’ll see the widget on every page. It’s not the prettiest at the moment, because it isn’t integrated into the design of the page, but it will give you an idea for how it works. Here you can see the user has selected to translate the page into Spanish.

clip_image014

Now that you’ve used the widget to translate the content of your page, you can explore one other option for translation of web sites and applications – using the API to translate anything else, such as user input.

Step 5. Creating UI for Text Translation

In this section, you’ll add controls to the site that allow your end users to type in some text, press a translate button, and then see the translation of the text they entered. This type of functionality is useful for interacting with your customers when you speak different languages, for example.

From Solution explorer, find the ‘About.aspx’ page. Open it in the designer, and you’ll see something like this:

clip_image016

Delete the 3 <p> tags that say ‘Use this area to provide additional information’, and replace with some controls to provide a basic translation UI, like this:

clip_image018

For your convenience, here’s the source for this page:

<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="Translator.About" %>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <hgroup class="title">
        <h1><%: Title %>.</h1>
        <h2>Your app description page.</h2>
    </hgroup>

    <article>
        Enter the text you would like to translate:<br />
        <asp:TextBox ID="TextBox1" runat="server" Height="25px" Width="342px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Height="37px" OnClick="Button1_Click" Text="Translate" />
        <br />
        Your translated text is:<br />
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </article>

    <aside>
        <h3>Aside Title</h3>
        <p>        
            Use this area to provide additional information.
        </p>
        <ul>
            <li><a runat="server" href="~/">Home</a></li>
            <li><a runat="server" href="~/About.aspx">About</a></li>
            <li><a runat="server" href="~/Contact.aspx">Contact</a></li>
        </ul>
    </aside>
</asp:Content>

 

Note that in the designer you should double-click on the button to generate the “Button1_Click” code. You’ll write this code in the next step.

Step 6. Writing code to translate user text

In the previous section you created a basic UI for text translation. It would allow the user to write some text, and press a button. In this section you’ll write the code behind that button which will translate the user’s desired text into Spanish, and render it on the page.

First, you’ll need to add a new class to your solution. Call it AdmAccessToken and give it the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Translator
{
    public class AdmAccessToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string scope { get; set; }
    }
}

 

Note that the names of the 4 strings should match what is here exactly, or you will get errors in your code later.

Next, within Visual Studio, in Solution Explorer, right click on the ‘References’ folder and select ‘Add Reference’. Use this dialog that follows to add references to

- System.Runtime.Serialization

- System.XML.Linq

- System.ServiceModel.Web

At the top of your code for About.aspx.cs, you’ll see a number of ‘using’ statements. Add using System.Xml.Linq to these, so that it looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace Translator
{
    public partial class About : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }
    }
}

 

You’ll see that the Button1_Click code is empty. Add the following code to it. This code will get your access token for the translator service, using the Client ID and Client Secret that you created earlier on.

string clientID = "<Your ClientID>";
string clientSecret = "<Your Client Secret>";
String strTranslatorAccessURI = 
      "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
String strRequestDetails = 
      string.Format("grant_type=client_credentials&client_id={0}&client_secret={1} &scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID),  
          HttpUtility.UrlEncode(clientSecret));

System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
webRequest.ContentLength = bytes.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
  outputStream.Write(bytes, 0, bytes.Length);
}

System.Net.WebResponse webResponse = webRequest.GetResponse();
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new 
    System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));

AdmAccessToken token = 
    (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

string headerValue = "Bearer " + token.access_token;

 

This code forms a POST to the data market service, passing your ID and secret and getting a JSON object back. You then deserialize that object into an AdmAccessToken. You can then derive the access_token from this.

This token is then added to a string, prefixed with “Bearer “ (don’t forget the space) to create a header value that will be sent to the translator service.

To then call the translator service with this headerValue, and pass the user’s text, you’ll use code like this:

string txtToTranslate = TextBox1.Text;
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + 
     System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es";
System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
translationWebRequest.Headers.Add("Authorization", headerValue);

System.Net.WebResponse response = null;
response = translationWebRequest.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
xTranslation.LoadXml(translatedStream.ReadToEnd());

Literal1.Text = xTranslation.InnerText;

 

 

The text box was called ‘TextBox1’ so the text the user typed in can simply be derived from that. After that a URI to the translator HTTP service is created, and the text itself is UrlEncoded and added to the URI.

Note that the language ‘en’ is used for ‘From’ (i.e., I’m assuming you’re typing in English), and ‘es’ is used for ‘To’ (i.e. it will translate into Spanish). The full list of these codes for the supported languages is here: http://msdn.microsoft.com/en-us/library/hh456380.aspx

The translator service returns XML, so the code calls the service, gets the response as XML and then decodes it into text. It then loads the result into the Literal that you created on About.aspx called Literal1.

You can see it in action here:

clip_image019

And that’s it! You’ve now used the Microsoft Translator API to add machine translation to your ASP.NET application.

Summary

In this walkthrough you saw how to build a Web Application using ASP.NET and how to add machine translation to it. You used the Microsoft Translator Widget to provide translation of your page content, and you saw how to program the Microsoft Translator API using C# in order to translate user generated content.