Getting Started with Microsoft Translator - Part 2: Writing an ASP.NET Application
In the first part of this series you saw how to sign up for Microsoft Translator in the Windows Azure Marketplace, and how to get your ClientID and Client Secret. In this article, you'll see how to make use of those to create a simple ASP.NET page that allows you to translate text entered into a text box on a web page.

Step 1. Creating an ASP.NET Web Application

If you don’t have Visual Studio, you can use the free Visual Web Developer Express from Microsoft to create ASP.NET pages. It can be downloaded from here: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-web-developer-express

The first step is to create a new Project, and in the project types dialog box, select ASP.NET Web Application and call it FirstTranslator. Make sure that you selected ‘.NET Framework 4’ as the version of .NET you are using.

Press OK and Visual Studio will create the project for you. The project will include ASP.NET Web Forms that define how your web pages will appear and code-behind these forms where you can write logic that executes on the server.

Take a look at the Default.aspx Web Form that has been created for you. It should look like this:

   1: <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
   2:     CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
   3: <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   4: </asp:Content>
   5: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   6: </asp:Content>

Take a look at the first line – which  defines the ‘code behind’ as Default.aspx.cs – that is, if you write any code that will execute on the server to process actions on this page, that’s where the code will live. You’ll be doing that in Step 3. The other sections define the HTML Header content (equivalent to <Head>) and the HTML Body Content (equivalent to <Body>).

Step 2. Editing your ASP.NET Web Form

In this step you’re going to create a very simple Web-based user interface within the Web Form that allows the user to type something in English, and have it translated into Spanish. If you aren’t familiar with ASP.NET already, take a close look at how the controls are defined – so, for example the <asp:TextBox> defines a server-side control, meaning that the server will process this tag and create HTML from it. It also knows to process any code associated with it. As you can imagine, the <asp:TextBox> control will ultimately render an HTML TextBox control (<input> control of type ‘text’) in the browser.

Here’s the code:

   1: <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
   2:     CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
   3:  
   4: <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   5: </asp:Content>
   6: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   7:     <h2>My Spanish Translator</h2>
   8:     <p>
   9:         Enter your text in English:&nbsp; </p>
  10:     <p>
  11:         <asp:TextBox ID="TextBox1" runat="server"  
  12:             Width="198px"></asp:TextBox>
  13:     </p>
  14:     <p>
  15:         <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
  16:             Text="Translate" />
  17:     </p>
  18:     <p>
  19:         Here is your translation:</p>
  20:     <p>
  21:         <asp:Literal ID="lbl1" runat="server"></asp:Literal>
  22:     </p>
  23: </asp:Content>

Take a look at the code-behind and you’ll see that this is just straight HTML – the <asp:TextBox> and other server side control definitions are gone.

In the next step, you’ll write the code that runs on the server and performs the translation.

Step 3. Writing the Code-Behind

Now that you have your user interface defined, it’s time to write the code to perform a translation.

First off, you’ll need to tell the server to perform the action of translation whenever the user presses the ‘Translate’ button. This is done using an event handler, and the name of the event handler for pressing a button is ‘Click’. Thus, in your code, when the page loads you can tell it that it should call a function called ‘Button1_Click’ whenever the user presses the button.

To do this, edit Default.aspx.cs so that it looks like this:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Web;
   4: using System.Web.UI;
   5: using System.Web.UI.WebControls;
   6:  
   7: namespace FirstTranslator
   8: {
   9:     public partial class _Default : System.Web.UI.Page
  10:     {
  11:         protected void Page_Load(object sender, EventArgs e)
  12:         {
  13:             Button1.Click += new EventHandler(Button1_Click);
  14:         }
  15:  
  16:         void Button1_Click(object sender, EventArgs e)
  17:         {
  18:             throw new NotImplementedException();
  19:         }
  20:     }
  21: }

Now, whenever the user presses the button, the code in Button1_Click will be called. We’ll need this code to perform a number of things in order to do a translation:

1. Use the Client ID and Client Secret to get the access token. Remember that you saw how to get these in part 1 of this tutorial series.

2. Call the Microsoft Translator service with the access token in order to translate the text the user entered.

3. Update the UI with the translated text.

Step 3.1 – Using the Client ID and Client Secret to get the Access Token

The first thing you need to do for this is to set up an AdmAccessToken class which stores the information returned from the Windows Azure Marketplace service. Make sure that you code this exactly as shown here. The names of the variables are important to have the same, or your later mappings won’t work.

The class should live in the same namespace as the rest of your code, so you should update Default.aspx.cs to look like this:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Web;
   4: using System.Web.UI;
   5: using System.Web.UI.WebControls;
   6:  
   7: namespace FirstTranslator
   8: {
   9:     public class AdmAccessToken
  10:     {
  11:  
  12:         public string access_token { get; set; }
  13:  
  14:         public string token_type { get; set; }
  15:  
  16:         public string expires_in { get; set; }
  17:  
  18:         public string scope { get; set; }
  19:     } 
  20:  
  21:     public partial class _Default : System.Web.UI.Page
  22:     {
  23:         protected void Page_Load(object sender, EventArgs e)
  24:         {
  25:             Button1.Click += new EventHandler(Button1_Click);
  26:         }
  27:  
  28:         void Button1_Click(object sender, EventArgs e)
  29:         {
  30:             throw new NotImplementedException();
  31:         }
  32:     }
  33: }

Now that you have an AdmAccessToken class defined, you can write the call to the Windows Azure Marketplace to pass it your ClientID and Client Secret and get an access token back. Before doing this, you’ll need to add a few References to your project in order to access some of the classes that are used to process this data.

In the Solution Explorer, right click on References, and select ‘Add Reference’. From the list of references, make sure that you add the following references:

  • System.Runtime.Serialization
  • System.Xml.Linq
  • System.ServiceModel.Web

Also, at the top of your code, make sure that you add ‘using System.Xml.Linq’.

To get your access token, add the following code to Button1_Click. Be sure to remove the ‘throw new NotImplementedException();’ first:

   1: string clientID = "<Your ClientID>";
   2: string clientSecret = "<Your Client Secret>";
   3:  
   4: String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
   5: 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));
   6:  
   7: System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
   8: webRequest.ContentType = "application/x-www-form-urlencoded";
   9: webRequest.Method = "POST";
  10:  
  11: byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
  12: webRequest.ContentLength = bytes.Length;
  13: using (System.IO.Stream outputStream = webRequest.GetRequestStream())
  14: {
  15:     outputStream.Write(bytes, 0, bytes.Length);
  16: }
  17: System.Net.WebResponse webResponse = webRequest.GetResponse();
  18:  
  19: System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
  20: //Get deserialized object from JSON stream 
  21: AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
  22:  
  23: 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:

   1: string txtToTranslate = TextBox1.Text;
   2: string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es";
   3: System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
   4: translationWebRequest.Headers.Add("Authorization", headerValue);
   5: System.Net.WebResponse response = null;
   6: response = translationWebRequest.GetResponse();
   7: System.IO.Stream stream = response.GetResponseStream();
   8: System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
   9: System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
  10: System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
  11: xTranslation.LoadXml(translatedStream.ReadToEnd());
  12: lbl1.Text = "Your Translation is: " + 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 lbl1.

And that’s it! Just like that you’ve created your first translator application in ASP.NET. In future tutorials we’ll look at using other parts of the API, including the SOAP service, as well as accessing alternative translations!