CodePaste Logo
New Snippet New Recent Snippets Recent Snippets My Snippets My Snippets My Favorites Favorites Web Code Search Snippets Search
Sign inor Register
Language: csharp

Microsoft Translator Helper for WinRT

1516 Views   
using System; using System.Linq; using System.Text; using System.Threading.Tasks; // your web service reference using App3.TranService; /// <summary>Microsoft Translator Helper (on Azure Data Marketplace)</summary> /// <see cref="https://datamarket.azure.com/developer/applications/register">CLIENT_ID</see> /// <see cref="http://msdn.microsoft.com/en-us/library/hh454950.aspx">Obtain a Token</see> /// <see cref="http://datamarket.azure.com/dataset/bing/microsofttranslator">Service Subscription</see> /// <seealso cref="http://api.microsofttranslator.com">API Reference</seealso> /// <seealso cref="http://msdn.microsoft.com/en-us/library/ff512435.aspx">API Reference</seealso> public class TranslatorHelper { readonly string ClientId; readonly string ClientSecret; AzureDataMarket.Token m_Token; delegate Task<T> ServiceCommandDelegate<T>(LanguageServiceClient service); // http://msdn.microsoft.com/en-us/library/hh456380.aspx public enum Languages { ar, bg, ca, cs, da, nl, en, et, fa, fi, fr, de, el, ht, he, hi, hu, id, it, ja, ko, lv, lt, mww, no, pl, pt, ro, ru, sk, sl, es, sv, th, tr, uk, vi } public TranslatorHelper(string clientId, string clientSecret) { if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId"); if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret"); ClientId = clientId; ClientSecret = clientSecret; } private async Task<T> ServiceOperation<T>(ServiceCommandDelegate<T> operation) { if (m_Token == null || m_Token.IsExpired) { // update access token var _Authentication = new AzureDataMarket(ClientId, ClientSecret); m_Token = await _Authentication.GetTokenAsync(); } // build auth header var _RequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty() { Method = "POST" }; _RequestProperty.Headers["Authorization"] = m_Token.Header; // add header to operation var _Service = new LanguageServiceClient(); using (var _Scope = new System.ServiceModel.OperationContextScope(_Service.InnerChannel)) { System.ServiceModel.OperationContext.Current .OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = _RequestProperty; // execute operation return await operation(_Service); } } private Languages[] m_LanguagesForTranslate = null; /// <summary> /// Obtain a list of language codes representing languages that are supported by the Translation Service. Translate() and TranslateArray() can translate between any of these languages. /// </summary> /// <returns></returns> public async Task<Languages[]> LanguagesForTranslateAsync() { if (m_LanguagesForTranslate != null) return m_LanguagesForTranslate; var _Operation = new ServiceCommandDelegate<Languages[]>(async s => { try { var _Results = await s.GetLanguagesForTranslateAsync(string.Empty); var _Languages = new System.Collections.Generic.List<Languages>(); foreach (var item in _Results) { Languages _Value; if (Enum.TryParse<Languages>(item, out _Value)) _Languages.Add(_Value); } return _Languages.ToArray(); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<Languages[]>(_Operation); } /// <summary> /// Translates a text string from one language to another. /// </summary> /// <param name="text">A string representing the text to translate. The size of the text must not exceed 10000 characters.</param> /// <param name="fromLang">A string representing the language code of the translation text. If left empty the response will include the result of language auto-detection.</param> /// <param name="toLang">A string representing the language code to translate the text into.</param> /// <param name="contentType">The format of the text being translated. The supported formats are "text/plain" and "text/html". Any HTML needs to be well-formed.</param> /// <param name="category">A string containing the category (domain) of the translation. Defaults to "general".</param> /// <returns></returns> public async Task<string> TranslateAsync(string text, Languages fromLang, Languages toLang, string contentType = "text/plain", string category = "general") { if (!(await LanguagesForTranslateAsync()).Any(x => x.Equals(fromLang))) throw new Exception("Language not supported: " + fromLang.ToString()); if (!(await LanguagesForTranslateAsync()).Any(x => x.Equals(toLang))) throw new Exception("Language not supported: " + toLang.ToString()); var _Operation = new ServiceCommandDelegate<string>(async s => { try { return await s.TranslateAsync(string.Empty, text, fromLang.ToString(), toLang.ToString(), contentType, category); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<string>(_Operation); } /// <summary> /// Use the GetTranslationsArray method to retrieve multiple translation candidates for multiple source texts. /// </summary> /// <param name="texts">An array containing the texts for translation. All strings must be of the same language. The total of all texts to be translated must not exceed 10000 characters. The maximum number of array elements is 2000.</param> /// <param name="fromLang">A string representing the language code of the translation text.</param> /// <param name="toLang">A string representing the language code to translate the text into.</param> /// <returns></returns> public async Task<string[]> TranslateAsync(string[] texts, Languages fromLang, Languages toLang) { if (!(await LanguagesForTranslateAsync()).Any(x => x.Equals(fromLang))) throw new Exception("Language not supported: " + fromLang.ToString()); if (!(await LanguagesForTranslateAsync()).Any(x => x.Equals(toLang))) throw new Exception("Language not supported: " + toLang.ToString()); var _Operation = new ServiceCommandDelegate<string[]>(async s => { try { var _Inputs = new System.Collections.ObjectModel.ObservableCollection<string>(texts); var _Results = await s.TranslateArrayAsync(string.Empty, _Inputs, fromLang.ToString(), toLang.ToString(), new TranslateOptions()); return _Results.Select(x => string.IsNullOrEmpty(x.Error) ? x.TranslatedText : string.Empty).ToArray(); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<string[]>(_Operation); } /// <summary> /// Use the Detect Method to identify the language of a selected piece of text. /// </summary> /// <param name="text">A string representing the text whose language is to be identified. The size of the text must not exceed 10000 characters</param> /// <returns></returns> public async Task<Languages> DetectAsync(string text) { var _Operation = new ServiceCommandDelegate<Languages>(async s => { try { var _Result = await s.DetectAsync(string.Empty, text); return (Languages)Enum.Parse(typeof(Languages), _Result); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<Languages>(_Operation); } /// <summary> /// Use the DetectArray Method to identify the language of an array of string at once. Performs independent detection of each individual array element and returns a result for each row of the array /// </summary> /// <param name="text">A string array representing the text from an unknown language. The size of the text must not exceed 10000 characters</param> /// <returns></returns> public async Task<Languages[]> DetectAsync(string[] text) { var _Operation = new ServiceCommandDelegate<Languages[]>(async s => { try { var _Inputs = new System.Collections.ObjectModel.ObservableCollection<string>(text); var _Results = await s.DetectArrayAsync(string.Empty, _Inputs); return _Results.Select(x => (Languages)Enum.Parse(typeof(Languages), x)).ToArray(); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<Languages[]>(_Operation); } private Languages[] m_LanguagesForSpeak = null; /// <summary> /// Retrieves the languages available for speech synthesis /// </summary> /// <returns></returns> public async Task<Languages[]> LanguagesForSpeakAsync() { if (m_LanguagesForSpeak != null) return m_LanguagesForSpeak; var _Operation = new ServiceCommandDelegate<Languages[]>(async s => { try { var _Results = await s.GetLanguagesForSpeakAsync(string.Empty); var _Languages = new System.Collections.Generic.List<Languages>(); foreach (var item in _Results) { Languages _Value; if (Enum.TryParse<Languages>(item, out _Value)) _Languages.Add(_Value); } return _Languages.ToArray(); } catch { System.Diagnostics.Debugger.Break(); throw; } }); return await ServiceOperation<Languages[]>(_Operation); } /// <summary> /// Returns a string which is a URL to a wave or mp3 stream of the passed-in text being spoken in the desired language /// </summary> /// <param name="text">A string containing a sentence or sentences of the specified language to be spoken for the wave stream. The size of the text to speak must not exceed 2000 characters</param> /// <param name="lang">A string representing the supported language code to speak the text in. The code must be present in the list of codes returned from the method GetLanguagesForSpeak</param> /// <param name="format">A string specifying the content-type ID. Currently, “audio/wav” and “audio/mp3” are available. The default value is "audio/wav". </param> /// <param name="options">A string specifying the quality of the audio signals. Currently, “MaxQuality” and “MinSize” are available. With “MaxQuality”, you can get the voice(s) with the highest quality, and with “MinSize”, you can get the voices with the smallest size. If no value is provided, we default to “MinSize”. </param> /// <returns></returns> public async Task<Uri> SpeakAsync(string text, Languages lang, string format = "audio/wav", string options = "MinSize") { if (!(await LanguagesForSpeakAsync()).Any(x => x.Equals(lang))) throw new Exception("Language not supported: " + lang.ToString()); var _Operation = new ServiceCommandDelegate<Uri>(async s => { var _Url = await s.SpeakAsync(string.Empty, text, lang.ToString(), format, options); return new Uri(_Url, UriKind.Absolute); }); return await ServiceOperation<Uri>(_Operation); } private class AzureDataMarket { readonly string m_ClientId; readonly string m_ClientSecret; readonly string m_Request; readonly string DATAMARKET_ACCESS_URI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; public AzureDataMarket(string clientId, string clientSecret) { this.m_ClientId = Uri.EscapeDataString(clientId); this.m_ClientSecret = Uri.EscapeDataString(clientSecret); this.m_Request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", m_ClientId, m_ClientSecret); } public async Task<Token> GetTokenAsync() { // build request var _Request = System.Net.WebRequest.Create(DATAMARKET_ACCESS_URI); _Request.ContentType = "application/x-www-form-urlencoded"; _Request.Method = "POST"; // make request var _Bytes = Encoding.UTF8.GetBytes(this.m_Request); using (var _Stream = await _Request.GetRequestStreamAsync()) _Stream.Write(_Bytes, 0, _Bytes.Length); // deserialize response try { using (var _Response = await _Request.GetResponseAsync()) { var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Token)); var _Token = await Task.Run(() => (Token)_Serializer.ReadObject(_Response.GetResponseStream())); return _Token; } } catch (Exception) { System.Diagnostics.Debugger.Break(); throw; } } [System.Runtime.Serialization.DataContract] public class Token { [System.Runtime.Serialization.DataMember] public string access_token { get; set; } [System.Runtime.Serialization.DataMember] public string token_type { get; set; } private int m_expires_in; [System.Runtime.Serialization.DataMember] public int expires_in { get { return m_expires_in; } set { m_expires_in = value; ExpirationDate = DateTime.Now.AddSeconds(value); } } [System.Runtime.Serialization.DataMember] public string scope { get; set; } private DateTime ExpirationDate = DateTime.MinValue; public bool IsExpired { get { return ExpirationDate < DateTime.Now; } } public string Header { get { return string.Format("Bearer {0}", access_token); } } } } }
by Jerry Nixon
  October 09, 2012 @ 11:48pm
Tags:
Description:
// http://datamarket.azure.com/dataset/bing/microsofttranslator<br /> var _Helper = new TranslatorHelper(CLIENT_ID, CLIENT_SECRET);<br /> var _Result = await _Helper.TranslateAsync("Hello World", Languages.en, Languages.fr);
by Thomas Sebastian Jensen    October 28, 2012 @ 3:09am

Hello,<br /> I'm using your code with the service reference "http://api.microsofttranslator.com/v2", but I get an error, if I'm trying to translate something: The remote server returned an error: (400) Bad Request. What am I doing wrong?

by Sandeep Verma    May 29, 2013 @ 8:27am

Hi Jerry,<br /> <br /> i am also getting the error "The remote server returned an unexpected response: (417) Expectation Failed".

Add a comment


Report Abuse
brought to you by:
West Wind Techologies