Skip to main content
Translator

Microsoft Translator Blog

Creating a Web Application with Translation provided by 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. 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 Azure. 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 4, 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 websites.

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 websites 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

 

 

Step 3. 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 4. 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 the translation of your page content, and you saw how to program the Microsoft Translator API using C# in order to translate user-generated content.