Azure Microsoft Translation in Windows Phone (The Easy Way)

There are few things more awesome than the Microsoft Translate service available on the Azure Marketplace. Unfortunately, the vast majority of examples of how to use it are not written for Windows Phone, which is missing some key components available in other .NET solutions.

(Note: Yes, I know you this should be easier with the Azure toolkit for Windows Phone, etc, etc, etc. I didn’t find the classes I needed in there and this blog post is for people like me who got stuck like me.)

So lets get started and we can see exactly how easily we can integrate this awesome translation service into a application.

Step 1: Sign Up For Microsoft Translation in the Azure Marketplace

We’ll go through a pretty typical registration process (name, rank and serial number) and then we’re signed in for an account. Now we need to sign up specifically for the Microsoft Translation service. Click on “Data”.

Do a search for “translation’” and Microsoft Translator will pop right up.

If we click on it, we’ll see some details as well as all of our pricing options.

Helpfully, at the bottom of that, there is an option for 2 million characters for the low, low price of free. This should be enough for us to get a fun little project started.

Now that we’re signed up for our free service, we need to register our specific app and get a Client ID and Client Secret to identify our app to this service. To do so, we will not click on “My Applications” or “My Data” or “Account Keys”, but down on the “Developers” link at the bottom.

Once you’re in there, Azure Marketplace will generate a client secret for you. All you need to do is give your application a client ID, some identifying name and a redirect URI. Don’t worry about the redirect URI, we won’t use it with this service.

Write down the ClientID and the Client Secret, we’ll need those for our app.

After we hit “Create”, we’ll see our application in the Registered Applications section.

And if we like we can click on “My Data” option in the “My Account” menu and try out our brand new service using a web interface.

We’re going to build our requests based on these queries, so go ahead and grab the “Service Root URL” at the top (should look like http://api.datamarket.azure.com/Data.ashx/Bing/MicrosoftTranslator/v1/ ). Play around with the query building and then we’ll work on our app.

Step 2: Get And Save Our Token

First, so we don’t run into problems later, lets add some references. Right click on the references folder, “Add Reference…” and add System.Servicemodel.Web (which we’ll need to read JSON) and System.Xml.Linq (which we’ll need to read XML).

The way this service works is to go out and get an access token for the client. This token will come back as our AdmAccessToken, which is valid for 10 minutes. We’ll use that token to authenticate our app with the service. We’re going to assume that we need a new token every time we open the app, but try to use the same token during each app session. (If you want to know more about the access tokens, head over here.)

The first 4 properties in AdmAccessToken.cs are required for proper serialization. The rest of the class is there for determining when the token has expired.

1:publicclass AdmAccessToken

2: {

3:// required for deserialization

4:publicstring access_token { get; set; }

5:publicstring token_type { get; set; }

6:publicstring expires_in { get; set; }

7:publicstring scope { get; set; }

8:

9:// properties and methods for determining expired tokens

10:private DateTime tokenEndTime { get; set; }

11:

12:publicbool IsExpired()

13: {

14: DateTime now = DateTime.Now;

15:double secondsLeft = tokenEndTime.Subtract(now).TotalSeconds;

16:if(secondsLeft < 30)

17:returntrue;

18:else

19:returnfalse;

20: }

21:

22:publicvoid Initalize()

23: {

24: tokenEndTime = DateTime.Now.Add(new TimeSpan(0, 0, 600));

25: }

26: }

Now we’ll write our token service in TokenService.cs. We’ll send an event once we get our token, so we need to define some event args for sending the token in the event. I usually add these to the bottom of my service class file.

And then add our call for the token. Our process here is 1) check to see if we have a valid token. 2) If we have a valid token, return it. 3) If we don’t have a valid token, start our Http POST request to get a token.

Then when we move to start the translation, we’ll run the token service, which will check to see if we have a valid token and, if we do, return it. (If we’ don’t, it will go and get one for us. When it is done with either task, it will raise the AccessTokenComplete event, which we’ll use to kick off the translation service.

15: RaiseTranslationFailed("There was a problem securing an access token");

16: }

The http service work is done in the StartTranslationWithToken method. We’ll set up the service uri we need to do the translation, create a WebRequest and set the Authorization header of our request to use “Bearer “ plus our access token. When the response comes back, we should have our XML with the data in it. We can read this using the XDocument utility (make sure to add System.XML.Linq to your project resources to get access to XDocument). Finally, we’ll raise an event that says everything went according to plan and returns our translation, as well as the original input data.

Now our translation is ready to rock and roll, so the only thing we have left to do is put together a simple user interface for interacting with our translator.

Step 3: Using Our Translator

Now lets build the UI that we’ll use to execute a translation and then (finally) translate something. Because this post is already running absurdly long We’re going to create UI for translating from English to Spanish rather than build up all the infrastructure for selecting multiple languages.

Open your project using Blend (you should be using Blend to create your Windows Phone UI) and go to the MainPage.xaml. Change the top text to the name of your app and the text beneath it to “translate”.

Beneath that, get rid of anything inside the ContentPanel and the hover your mouse along the left edge of the ContentPanel. you should see an orange line show up.

Click it and you’ll see that you’ve created a separation in your Grid layout. You’ll see numbers that indicate the status of the Grid.Row that you’ve made. Hover over those numbers and you’ll see an editing system pop up (note, this is for Blend 5 and up). Click in that pop-up to edit the size of the row.

I’m editing mine to be: 1*, 1*, which will look in the XAML like

1: <Grid.RowDefinitions>

2: <RowDefinition Height="1*"/>

3: <RowDefinition Height="1*"/>

4: </Grid.RowDefinitions>

The top area will be for the source text (what we want to translate), the middle area will be for selection of the translation languages (which we won’t implement in this tutorial) and the bottom will be where we’ll place the translated text.

To this end, let’s add a TextBlock indicating the function of the top and bottom areas and a TextBox for adding or copying text. I’m going to add some text into our source TextBox just to give us something to work with.

Let’s also give our TextBoxes names so we can add and extract text from them in the code-behind. By clicking on the element in the Objects and Timeline tree, we can see the properties on the right hand side.

Just change the name at the top to make it accessible by that name in the code-behind.

When the user clicks on the ApplicationBar button, we’ll fire an event that starts up the translation service. To define this event, select your ApplicationBarIconButton in the Objects and Timeline panel.

‘
Then click the lightning icon in Properties panel. This will bring up a list of events that are available to that object. In the “Click” box, type the name of the event handler you’d like to use and Blend will insert the appropriate code into the code behind.

Now, to look at our code behind (MainPage.xaml.cs). Before we call the translation service, we need to initiate it. So at the top of our class, we’ll add our translation service, instantiate it and add some event handlers in our constructor.

Let’s start our translation service in our ApplicationBarIconButton event handler. We’ll hard code the language information for now from English to Spanish, but if you need a list of supported language codes, check out this… um… list of supported language codes.

1:privatevoid On_CheckClicked(object sender, System.EventArgs e)

2: {

3: _translator.GetTranslation(sourceTextBox.Text, "en", "es");

4: }

And all we need to do is handle the resulting events and we’re done. The TranslationService will return the information off the UI thread, so in order to pass the information along without throwing a thread exception, Deployment.Current.Dispatcher.BeginInvoke to the rescue!

We’re a bunch of volunteers and opening a new scheme in our community.
Your website provided us with helpful information to work on. You have
performed a formidable job and our whole group will likely be thankful to you.

I used to be recommended this website by means of my cousin.
I am now not sure whether this publish is written through him
as nobody else recognize such distinctive approximately my trouble.
You’re amazing! Thank you!

You do not need a physical store or office, so your financial commitment is a
lot less than you would have to pay for a traditional bricks-and-mortar business.
This mechanical energy moves pistons up and down inside piston chambers.
Take the time to figure out your total costs to produce your product.

Woah! I’m really enjoying the template/theme of this site.
It’s simple, yett effective. A lot of times it’s
hard to get that “perfect balance” between usability and visual appearance.
I must say that you’ve dopne a awesxome job with this.

Good day! I could have sworn I’ve been to this website before but after reading through some of the
post I realized it’s new to me. Anyways, I’m definitely glad I found it and I’ll be
book-marking and checking back often!

Good day! I know this is kind of off topic but I was wondering if
you knew where I could find a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having difficulty
finding one? Thanks a lot!

In Vista the process is similar and your goal is “Service Pack 1”.
I have had no problems at all with it so do not
worry about virus’. Your choice depends on the level of encryption needed for yourself (or to bypass)
and your budget.

One or more projectors are used to process programs. It would be a
dream come true, partying with the cartoon character voted the 2nd most influential in history.
Hence, the people are well educated and highly concerned about the development of the region and keenly look forward to make their
lives always easy.

There’s only a single strategy to grow to be a 2000+ rated participant
in League of Legends – get far better. An intern in a hospital is dispatched to the
morgue located in the basement of the building.
This portrayal of friars being the flatulence
of Satan, shows us something about the summoner’s view
of a friar in Chaucer’s time.

629100 213209Thank you for writing this tremendous top quality write-up. The details in this material confirms my point of view and you actually laid it out properly. I could never have written an write-up this excellent. 282277

118428 539481Thank you for the sensible critique. Me and my neighbor were just preparing to do some research on this. We got a grab a book from our location library but I feel I learned far more clear from this post. I

213925 676099Soon after study several with the weblog articles for your internet internet site now, and i also genuinely such as your strategy for blogging. I bookmarked it to my bookmark internet internet site list and are checking back soon. Pls take a appear at my internet page in addition and tell me what you believe. 750893

267925 275117This sort of in search of get the enhancements made on this special lifestyle and diet, begin your L . a . Shifting the pounds diet solution is really a huge procedure into accesing which generally hope. weight loss 416235

935208 781247Any person several opportune pieces, it comes surely, as properly as you bring in crave of various the several other types of hikers close to you with hard part your question. pre owned awnings 552873

I do not even know the way I finished up right here, but I thought
this post used to be good. I do not recognize who you
might be however certainly you’re going to a well-known blogger when you aren’t already.
Cheers!

Microsoft (MSFT) may be a bit behind Google (GOOG) and Apple (AAPL) when it comes to creating a voice-enabled personal assistant for its mobile devices, but it seems the company does have plans to add better speech recognition capabilities to its Bing mobile app in the near future. MSFTKitchen has posted a video demonstration of a new prototype for voice recognition software on Windows Phone devices that’s intended to show how Microsoft has worked to reduce latency and word recognition errors while improving phones’ ability to accurately hear you in crowded, noisy areas.*

Hi,
I really thank you for this article, I searched and searched on the web looking for a valid sample to use Azure Translation service on WP8! I got a big problem by the way… even running your code I encounter a strange Web Exception… always thrown executing this instruction:
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); in the TranslationService.cs

I Guess You Are Using VS12 for Windows Phone Development. As I Know there is no SDK that is supporting VS12 as new SDK for wp8 is not out and no templates available for VS12. Are you using leaked version of SDK or you grabbed Developer preview of wp8 SDk. 🙂