Using Microsoft Translator API with Windows Store App HTML 5 & Javascript

180px-MS-Translator-logo

is a translation portal by Microsoft as part of Bing services that can provide a machine-translation of texts or entire web pages. Microsoft Translator also provides a set of web service APIs (that can be called via an HTTP REST service, an AJAX callable service, or a SOAP service) for developers who wish to use Microsoft Translator in their applications.

In this article we will develop a Windows Store application that uses the AJAX callable service of Microsoft Translator to translate text between languages.

First you have subscribe to the Microsoft Translator API on windows azure from here. Follow this link will help you to subscribe. Then register your application on Azure Data Market to get the clientId and clientSecret that we will use to obtain the access token.
The access token is passed with each API call and is used to authenticate your access to the Microsoft Translator API. You must obtain an access token to use the Microsoft Translator API.

NOTE:  Bing AppID mechanism is deprecated and is no longer supported. As mentioned above, you must obtain an access token to use the Microsoft Translator API. The access token is more secure and more flexible.

Now we will create a Windows RunTime component (WinRT Component) project that will have two classes we will use to obtain our access token .

The first class is AdmAccessToken that will have Token Request Output Properties :


using System.Runtime.Serialization;

namespace MicrosoftTranslatorRT
{
  public sealed class AdmAccessToken
  {
    [DataMember]
    public string access_token { get; set; }
    [DataMember]
    public string token_type { get; set; }
    [DataMember]
    public string expires_in { get; set; }
    [DataMember]
    public string scope { get; set; }
  }
}

The second is AdmAuthentication Class that will contain the Token Request Input Parameters. and the function that will handle the HTTP POST request to the token service to obtain the access token.


using System;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using Windows.Foundation;
using System.Net.Http;

namespace MicrosoftTranslatorRT
{
  public sealed class AdmAuthentication
  {
    internal static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
    private string clientId;
    private string clientSecret;
    private string request;
    private AdmAccessToken token;

    public IAsyncOperation<AdmAuthentication> Initializer(string clientId, string clientSecret)
    {
      return Contractor(clientId, clientSecret).AsAsyncOperation();
    }

    private async Task<AdmAuthentication> Contractor(string clientId, string clientSecret)
    {
      AdmAuthentication obj = new AdmAuthentication();
      obj.clientId = clientId;
      obj.clientSecret = clientSecret;
      //If clientid or client secret has special characters, encode before sending request
      obj.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", WebUtility.UrlEncode(clientId), WebUtility.UrlEncode(clientSecret));
      obj.token = await HttpPost(DatamarketAccessUri, request);
      return obj;
    }

    public AdmAccessToken GetAccessToken()
    {
      return token;
    }

    private async Task<AdmAccessToken> HttpPost(string DatamarketAccessUri, string requestDetails)
    {
      //Prepare OAuth request
      string requestBody = "grant_type=client_credentials&client_id=MohamedAhmed&client_secret=bCGqd7PXvF3QcgSoL5QHRMuJ137xQsft1aRe%2bfs3Sh8&scope=http://api.microsofttranslator.com";
      byte[] bytes = Encoding.UTF8.GetBytes(requestBody);

      HttpResponseMessage response = null;
      try
      {
        HttpClient request = new HttpClient();
        request.DefaultRequestHeaders.Add("contentType", "application/x-www-form-urlencoded");
        response = await request.PostAsync(DatamarketAccessUri, new ByteArrayContent(bytes));
      }
      catch (Exception e)
     {
       throw;
     }

     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
     //Get deserialized object from JSON stream
     token = (AdmAccessToken)serializer.ReadObject(await response.Content.ReadAsStreamAsync());
     return token;
    }
  }
}

now our winRT component project is ready and we can add it as a reference to our windows store app. note: adding a class liberary project to windows store app isn’t supported.

in our windows store app simply I’ll use default.html file and default.js to implement the translator.  you can add your own code in the page you want.

this will be my simple User Interface ‘default.html’ :

24-8-2013 6-47-21 PM

<input type="text" id ="myTextField"/>
<button id="translateBtn">Translate</button>
<br/><br/>
result :<span id="reuslt"></span>

and in the javascript file ‘default.js’  the xhr request that will handle the translation must have some paramters (the access token, from, To, the text)

$('#translateBtn').click(function() {
var data = $('#myTextField').val();
if (navigator.onLine) {
var token = "";

var admAuth = new MicrosoftTranslatorRT.AdmAuthentication();
admAuth.initializer("", "").done(function() {

token = admAuth.getAccessToken();
var from = "en", to = "ar", // translation will be from english to arabic
text = data; // the text we want to translate

var resSpan = document.getElementById("reuslt"); // the span that will have the translated text

var AccsessToken = "Bearer+" + token.access_token;

WinJS.xhr({
   url: "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
   "?appId=" + encodeURIComponent(AccsessToken) +
   "&from=" + encodeURIComponent(from) +
   "&to=" + encodeURIComponent(to) +
   "&text=" + encodeURIComponent(text)
}).done(
     function(result) {
      if (result.status === 200) // the if the request status is correct
      {
        $(resSpan).text(result.responseText);
      }
     });
   });
  }
});

make sure the access token is will encoded if you have properly encoded the token, the token will start something like “Bearer+….” and not “Bearer%20”.

you can get the Source Code from here.

Advertisements

One thought on “Using Microsoft Translator API with Windows Store App HTML 5 & Javascript

  1. Pingback: How To Fix Javascript Microsoft Translator Favorite Errors - Windows Vista, Windows 7 & 8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s