Exemplo n.º 1
0
        async Task <string> _init(string subsKey)
        {
            var bearer = _checkCache(subsKey);

            if (bearer == null)
            {
                var authTokenSource = new AzureAuthToken(subsKey);

                try
                {
                    bearer = await authTokenSource.GetAccessTokenAsync();

                    _setCache(subsKey, bearer);
                }

                catch (HttpRequestException)
                {
                    switch (authTokenSource.RequestStatusCode)
                    {
                    case HttpStatusCode.Unauthorized:
                        Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
                        break;

                    case HttpStatusCode.Forbidden:
                        Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
                        break;
                    }
                    throw;
                }
            }

            return(bearer);
        }
Exemplo n.º 2
0
        public static async Task <string> TranslateText(string Text, string sourceLanguage, string destinationLanguage)
        {
            string         text           = Text;
            string         from           = sourceLanguage;
            string         to             = destinationLanguage;
            string         uri            = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;
            string         translation    = "";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            string         subKey         = System.Configuration.ConfigurationManager.AppSettings["TranslatorKey"];

            var    authTokenSource = new AzureAuthToken(subKey);
            string authToken;

            authToken = await authTokenSource.GetAccessTokenAsync();

            httpWebRequest.Headers.Add("Authorization", authToken);
            using (WebResponse response = await httpWebRequest.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                {
                    DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
                    translation = (string)dcs.ReadObject(stream);
                }

            return(translation);
        }
Exemplo n.º 3
0
        public static async Task <string> TranslateAsync(String input)
        {
            var translatorService = new MSTranslator.LanguageServiceClient();

            var authTokenSource = new AzureAuthToken(SubscriptionKey);
            var token           = string.Empty;

            //TODO: Try catch here
            token = await authTokenSource.GetAccessTokenAsync();

            //return "hello baby";
            return(translatorService.Translate(token, input, "zh-CHT", "zh-CHS", "text/plain", "general", string.Empty));
        }
        /// <summary>
        /// Connect to the server before sending audio
        /// It will get the authentication credentials and add it to the header
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task Connect(string from, string to, string voice, OnSpeechTranslateResult onSpeechTranslateResult, OnTextToSpeechData onTextToSpeechData)
        {
            this.webSocket               = new MessageWebSocket();
            this.onTextToSpeechData      = onTextToSpeechData;
            this.onSpeechTranslateResult = onSpeechTranslateResult;

            // Get Azure authentication token
            var tokenProvider = new AzureAuthToken(this.clientSecret);
            var bearerToken   = await tokenProvider.GetAccessTokenAsync();

            this.webSocket.SetRequestHeader("Authorization", bearerToken);

            var url = String.Format(SpeechTranslateUrl, from, to, voice == null ? String.Empty : "&features=texttospeech&voice=" + voice);

            this.webSocket.MessageReceived += WebSocket_MessageReceived;

            // setup the data writer
            this.dataWriter           = new DataWriter(this.webSocket.OutputStream);
            this.dataWriter.ByteOrder = ByteOrder.LittleEndian;
            this.dataWriter.WriteBytes(GetWaveHeader());

            // connect to the service
            await this.webSocket.ConnectAsync(new Uri(url));

            // flush the dataWriter periodically
            this.timer = new Timer(async(s) =>
            {
                if (this.dataWriter.UnstoredBufferLength > 0)
                {
                    try
                    {
                        await this.dataWriter.StoreAsync();
                    }
                    catch (Exception e)
                    {
                        this.onSpeechTranslateResult(new Result()
                        {
                            Status = "DataWriter Failed: " + e.Message
                        });
                    }
                }

                // reset the timer
                this.timer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
            },
                                   null, TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
        }
Exemplo n.º 5
0
        public async Task <string> TranslatorDetect(string content)
        {
            string returnContentType = string.Empty;
            var    authTokenSource   = new AzureAuthToken(strAzureAuthToken);
            string authToken;

            authToken = await authTokenSource.GetAccessTokenAsync();

            string         uri            = "https://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + content;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            using (WebResponse response = httpWebRequest.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
                    returnContentType = (string)dcs.ReadObject(stream);
                }
            return(returnContentType);
        }
Exemplo n.º 6
0
        public async Task <string> TranslatorExecute(string from, string to, string content)
        {
            string returnContent   = string.Empty;
            var    authTokenSource = new AzureAuthToken(strAzureAuthToken);
            string authToken;

            authToken = await authTokenSource.GetAccessTokenAsync();

            string         uri            = "https://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + HttpUtility.UrlEncode(content) + "&from=" + from + "&to=" + to;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.Headers.Add("Authorization", authToken);
            using (WebResponse res = httpWebRequest.GetResponse())
                using (Stream stream = res.GetResponseStream())
                {
                    DataContractSerializer dcs = new DataContractSerializer(Type.GetType("System.String"));
                    returnContent = (string)dcs.ReadObject(stream);
                }
            return(returnContent);
        }
Exemplo n.º 7
0
 private async Task <string> GetToken()
 {
     try
     {
         return(await authTokenSource.GetAccessTokenAsync());
     }
     catch (HttpRequestException)
     {
         if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
         {
             Console.WriteLine($"[{DateTime.UtcNow}]: Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
             return(string.Empty);
         }
         if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
         {
             Console.WriteLine($"[{DateTime.UtcNow}]: Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
             return(string.Empty);
         }
         throw;
     }
 }
Exemplo n.º 8
0
        private static async Task <string> Translate(string text, TranslationSetting activeSetting)
        {
            var    authTokenSource = new AzureAuthToken(activeSetting.SubscriptionKey.Trim());
            string authToken;

            try
            {
                authToken = await authTokenSource.GetAccessTokenAsync();
            }
            catch (HttpRequestException)
            {
                if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new ApplicationException("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
                }
                if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
                {
                    throw new ApplicationException("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
                }
                throw;
            }

            return(TranslateApi.Translate(authToken, text, activeSetting.From, activeSetting.To, activeSetting.Category));
        }
Exemplo n.º 9
0
        private async Task <string> AuthoizeService(string key)
        {
            var    authTokenSource = new AzureAuthToken(key.Trim());
            string authToken;

            try
            {
                authToken = await authTokenSource.GetAccessTokenAsync();
            }
            catch (HttpRequestException)
            {
                if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
                {
                    return("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
                }
                if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
                {
                    return("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
                }
                throw;
            }

            return(authToken);
        }
Exemplo n.º 10
0
        private static async Task MainAsync()
        {
            string key = "ad4ad4c1cf0640b68a518a34b31c29a5";

            try
            {
                if (string.IsNullOrWhiteSpace(key))
                {
                    throw new ArgumentException("The subscription key has not been provided.");
                }

                var authTokenSource = new AzureAuthToken(key.Trim());
                try
                {
                    authTokenTranslate = await authTokenSource.GetAccessTokenAsync();
                }
                catch (HttpRequestException)
                {
                    if (authTokenSource.RequestStatusCode == HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
                        return;
                    }
                    if (authTokenSource.RequestStatusCode == HttpStatusCode.Forbidden)
                    {
                        Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
                        return;
                    }
                    throw;
                }
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Error:\n  {0}\n", ex.Message);
            }
        }
Exemplo n.º 11
0
        public static async Task TranslateTexts(List <string> texts, string sourceLanguage, string destinationLanguage)
        {
            string subKey = System.Configuration.ConfigurationManager.AppSettings["TranslatorKey"];
            var    from   = sourceLanguage;
            var    to     = destinationLanguage;

            var uri  = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
            var body = "<TranslateArrayRequest>" +
                       "<AppId />" +
                       "<From>{0}</From>" +
                       "<Options>" +
                       " <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">{1}</ContentType>" +
                       "<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" +
                       "</Options>" +
                       "<Texts>";

            foreach (string text in texts)
            {
                body += "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">" + text + "</string>";
            }

            body += "</Texts>" +
                    "<To>{2}</To>" +
                    "</TranslateArrayRequest>";

            string requestBody = string.Format(body, from, "text/plain", to);

            using (var client = new HttpClient())
                using (var request = new HttpRequestMessage())
                {
                    request.Method     = HttpMethod.Post;
                    request.RequestUri = new Uri(uri);
                    request.Content    = new StringContent(requestBody, Encoding.UTF8, "text/xml");

                    var    authTokenSource = new AzureAuthToken(subKey);
                    string authToken;
                    authToken = await authTokenSource.GetAccessTokenAsync();

                    request.Headers.Add("Authorization", authToken);
                    var response = await client.SendAsync(request);

                    var responseBody = await response.Content.ReadAsStringAsync();

                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.OK:
                        Console.WriteLine("Request status is OK. Result of translate array method is:");
                        var doc = XDocument.Parse(responseBody);
                        var ns  = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2");
                        var sourceTextCounter = 0;
                        foreach (XElement xe in doc.Descendants(ns + "TranslateArrayResponse"))
                        {
                            foreach (var node in xe.Elements(ns + "TranslatedText"))
                            {
                                if (sourceTextCounter < texts.Count)
                                {
                                    texts[sourceTextCounter] = node.Value;
                                }
                            }
                            sourceTextCounter++;
                        }
                        break;

                    default:
                        Console.WriteLine("Request status code is: {0}.", response.StatusCode);
                        Console.WriteLine("Request error message: {0}.", responseBody);
                        break;
                    }
                }
        }