Exemplo n.º 1
0
 private void RenewAccessToken()
 {
     AdmAccessToken newAccessToken = HttpPost(DatamarketAccessUri, this.request);
     //swap the new token with old one
     //Note: the swap is thread unsafe
     this.token = newAccessToken;
     Console.WriteLine(string.Format("Renewed token for user: {0} is: {1}", this.clientId, this.token.access_token));
 }
Exemplo n.º 2
0
 public AdmAuthentication(string clientId, string clientSecret)
 {
     this.clientId = clientId;
     this.clientSecret = clientSecret;
     //If clientid or client secret has special characters, encode before sending request
     this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
     this.token = HttpPost(DatamarketAccessUri, this.request);
     //renew the token every specfied minutes
     accessTokenRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback), this, TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1));
 }
Exemplo n.º 3
0
        public Translator(string clientId, string clientSecret)
        {
            this.clientId    = clientId;
            this.cientSecret = clientSecret;
            //If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", System.Uri.EscapeDataString(clientId), System.Uri.EscapeDataString(clientSecret));

            admToken           = HttpPost(DatamarketAccessUri, this.request);
            accessTokenRenewer = new Timer(new TimerCallback(OnTokenExpiredCallback), this, TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1));
        }
Exemplo n.º 4
0
    public string MicrosoftTranslate(string input)
    {
        string clientID               = "translatedhruba_123";
        string clientSecret           = "sJnnJgpG12Rysf7KxjeBpY5ulaCKSdaJYot7adFzXWY=";
        String strTranslatorAccessURI =
            "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        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));

        System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method      = "POST";
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
        webRequest.ContentLength = bytes.Length;

        string translatedtext = "";

        try
        {
            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.WebResponse webResponse = webRequest.GetResponse();
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
                                                                                      System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));

            AdmAccessToken token =
                (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            string headerValue = "Bearer " + token.access_token;

            string txtToTranslate = input;
            string uri            = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" +
                                    System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=no&to=en";
            System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
            translationWebRequest.Headers.Add("Authorization", headerValue);
            System.Net.WebResponse response = null;
            response = translationWebRequest.GetResponse();
            System.IO.Stream     stream = response.GetResponseStream();
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
            System.Xml.XmlDocument xTranslation     = new System.Xml.XmlDocument();
            xTranslation.LoadXml(translatedStream.ReadToEnd());
            translatedtext = xTranslation.InnerText;
        }
        catch (Exception ex)
        {
            ExceptionHandling.errorMessage = ex.ToString();
        }
        return(translatedtext);
    }
Exemplo n.º 5
0
        private void StartTranslationWithToken(AdmAccessToken token)
        {
            string translateUri = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text={0}&from={1}&to={2}",
                                                HttpUtility.UrlEncode(_originalText),
                                                HttpUtility.UrlEncode(_sourceLanguage),
                                                HttpUtility.UrlEncode(_targetLanguage));

            WebRequest translationRequest = HttpWebRequest.Create(translateUri);

            // We need to put our access token into the Authorization header
            //    with "Bearer " preceeding it.
            string bearerHeader = "Bearer " + token.access_token;

            translationRequest.Headers["Authorization"] = bearerHeader;

            // Finally call our translation service

            translationRequest.BeginGetResponse(asyncResult =>
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                    // Read the contents of the response into a string
                    Stream streamResponse   = response.GetResponseStream();
                    StreamReader streamRead = new StreamReader(streamResponse);
                    string translationData  = streamRead.ReadToEnd();

                    // Read the XML return from the translator
                    //  you can get a preview of this XML if you go to your Azure
                    //  account, click on My Data on the left and then on "Use" on
                    //  Microsoft Translator. run a trial query and then click the
                    //  XML button at the top of the query tool.

                    // You'll need to add "System.XML.Linq" to your project to use XDocument
                    XDocument translationXML = XDocument.Parse(translationData);
                    string translationText   = translationXML.Root.FirstNode.ToString();

                    RaiseTranslationComplete(_originalText, _sourceLanguage, _targetLanguage, translationText);
                }
                catch (WebException webExc)
                {
                    RaiseTranslationFailed(webExc.Status.ToString());
                }
            }, translationRequest);
        }
Exemplo n.º 6
0
        protected AdmAccessToken getToken()
        {
            try
            {
                //retrieve the clientID and clientSecret from web.config
                string clientID = ConfigurationManager.AppSettings["ClientID"].ToString();

                string clientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString();

                String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

                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));

                WebRequest webRequest = WebRequest.Create(strTranslatorAccessURI);

                webRequest.ContentType = "application/x-www-form-urlencoded";

                webRequest.Method = "POST";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);

                webRequest.ContentLength = bytes.Length;

                using (System.IO.Stream outputStream = webRequest.GetRequestStream())
                {
                    outputStream.Write(bytes, 0, bytes.Length);
                }

                //send request to get authentication token
                WebResponse webResponse = webRequest.GetResponse();

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));

                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

                return(token);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        public void GetToken()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("admAccessToken"))
            {
                AdmAccessToken savedToken = (AdmAccessToken)IsolatedStorageSettings.ApplicationSettings["admAccessToken"];
                if (!savedToken.IsExpired())
                {
                    RaiseAccessTokenComplete(true, savedToken);
                    return;
                }
            }

            // Create our HTTP request
            WebRequest request = WebRequest.Create(OAUTH_URI);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //IAsyncResult postCallback = (IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), request);
            request.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), request);
        }
        public async Task <AdmAccessToken> GetAccessToken()
        {
            WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            //webRequest.ContentType = bytes.Length;
            using (Stream outputStream = await webRequest.GetRequestStreamAsync())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            WebResponse webResponse = await webRequest.GetResponseAsync();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
            //Get deserialized object from JSON stream
            AdmAccessToken token       = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            string         headerValue = "Bearer " + token.access_token;

            return(token);
        }
Exemplo n.º 9
0
        private static AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
        {
            //Prepare OAuth request
            WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return(token);
            }
        }
Exemplo n.º 10
0
    private static string GetAccesToken()
    {
        //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/
        //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx)

        string clientId     = DotNetNuke.Common.Utilities.Config.GetSetting("MSTranslatorClientId");
        string clientSecret = DotNetNuke.Common.Utilities.Config.GetSetting("MSTranslatorClientSecret");

        AdmAuthentication admAuth = new AdmAuthentication(clientId, clientSecret);

        try
        {
            AdmAccessToken admToken = admAuth.GetAccessToken();
            return(admToken.access_token);
        }
        catch (WebException e)
        {
            // Obtain detailed error information
            string strResponse = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)e.Response)
            {
                if (response != null)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
                        {
                            strResponse = sr.ReadToEnd();
                        }
                    }
                }
            }
            throw new Exception(string.Format("Http status code={0}, error message={1}", e.Status, strResponse), e);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 11
0
        private string GetAccessToken()
        {
            String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            String strRequestDetails      = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(_subscriptionKey), HttpUtility.UrlEncode(_secret));

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            webRequest.ContentLength = bytes.Length;
            using (System.IO.Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            System.Net.WebResponse webResponse = webRequest.GetResponse();

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));

            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());

            return(token.access_token);
        }
Exemplo n.º 12
0
            async private Task<AdmAccessToken> HttpPost(string DatamarketAccessUri)
            {
                using (HttpClient client = new HttpClient())
                {
                    var list = new List<KeyValuePair<string, string>>();
                    list.Add(new KeyValuePair<string,string>("grant_type", "client_credentials"));
                    list.Add(new KeyValuePair<string,string>("client_id", Uri.EscapeUriString(clientId)));
                    list.Add(new KeyValuePair<string,string>("client_secret", Uri.EscapeUriString(clientSecret)));
                    list.Add(new KeyValuePair<string, string>("scope", "http://api.microsofttranslator.com"));
                    var hscDetails = new HttpFormUrlEncodedContent(list);
                    var headers = client.DefaultRequestHeaders;
                    var httpResponse = await client.PostAsync(new Uri(DatamarketAccessUri), hscDetails);
                    var strResponse = await httpResponse.Content.ReadAsStringAsync();

                    var obj = JsonObject.Parse(strResponse);
                    AdmAccessToken token = new AdmAccessToken() {
                        access_token = obj.GetNamedString("access_token"),
                        token_type = obj.GetNamedString("token_type"),
                        expires_in = obj.GetNamedString("expires_in"),
                        scope = obj.GetNamedString("scope")
                    };
                    return token;
                }
            }
Exemplo n.º 13
0
        /// <summary>
        /// Request a new token from the azure data market
        /// </summary>
        /// <returns>Whether it succesfully aquired a token</returns>
        public bool RequestToken()
        {
            //If there is already a _AccessToken, return true
            if (Active == true)
            {
                return(true);
            }


            string request = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope={2}", EncodedId, EncodedSecret, EncodedScope);

            //If the RequestToken successfully executes and returns, return true, otherwise return false
            try
            {
                _AccessToken = HttpPost(_DataMarketURI, request);
                ExpiresOn    = DateTime.Now.AddMinutes(Int32.Parse(_AccessToken.expires_in));
                return(true);
            }
            catch
            {
                _AccessToken = null;
                return(false);
            }
        }
Exemplo n.º 14
0
        private AdmAccessToken HttpPost(string DatamarketAccessUri, string appKey)
        {
            //Prepare OAuth request
            var webRequest = (HttpWebRequest)WebRequest.Create(DatamarketAccessUri);

            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Ocp-Apim-Subscription-Key", appKey);
            webRequest.ContentLength = 0;
            webRequest.Accept        = "application/json";
            webRequest.Method        = "POST";
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                /*
                 * DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                 * //Get deserialized object from JSON stream
                 * AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                 */
                var          admAccessToken = new AdmAccessToken();
                StreamReader reader         = new StreamReader(webResponse.GetResponseStream());
                string       strResponse    = reader.ReadToEnd();
                admAccessToken.access_token = strResponse;
                return(admAccessToken);
            }
        }
    //Exits on the WebResponse line
    private static async System.Threading.Tasks.Task <string> DetectMethod(string authToken, AdmAccessToken token, string txtToTranslate)
    {
        string     headerValue           = "Bearer " + token.access_token;
        string     uri                   = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + WebUtility.UrlEncode(txtToTranslate) + "&from=en&to=es";
        WebRequest translationWebRequest = WebRequest.Create(uri);

        translationWebRequest.Headers["Authorization"] = headerValue;
        WebResponse response = await translationWebRequest.GetResponseAsync();     //where it's exiting

        System.IO.Stream       stream           = response.GetResponseStream();
        System.Text.Encoding   encode           = System.Text.Encoding.GetEncoding("utf-8");
        System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
        System.Xml.XmlDocument xTranslation     = new System.Xml.XmlDocument();
        xTranslation.LoadXml(translatedStream.ReadToEnd());
        //translatedText = xTranslation.InnerText;
        return(xTranslation.InnerText);
    }
Exemplo n.º 16
0
 public async Task Init()
 {
     request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", clientId, Uri.EscapeDataString(clientSecret));
     token   = await HttpPost(DatamarketAccessUri, this.request);
 }
Exemplo n.º 17
0
 private void RetrieveToken(AdmAccessToken token)
 {
     _token = token;
     PerformAction();
 }
Exemplo n.º 18
0
    /// <summary>
    /// Gets the response callback for authentication
    /// </summary>
    /// <param name='ar'>
    /// the result of the callback
    /// </param>
    private void GetResponseCallback(IAsyncResult ar)
    {
        // Process the response callback to get the token
        // we'll then use that token to call the translator service
        // Pull the request out of the IAsynch result
        HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
        // The request now has the response details in it (because we've called back having gotten the response
        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.EndGetResponse(ar);
        }
        catch (WebException e)
        {
            response = null;
            using (response = (HttpWebResponse)e.Response)
            {
                //Error
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Debug.Log("Error code:" + httpResponse.StatusCode.ToString());
                using (Stream data = response.GetResponseStream())
                {
                    string text = new StreamReader(data).ReadToEnd();
                    Debug.Log(text);
                }
            }
        }
        // Using JSON we'll pull the response details out, and load it into an AdmAccess token class
        try
        {
            //Save the token and the header value for translation
            StreamReader streamReader = new StreamReader(response.GetResponseStream());
            string       jsonObject   = streamReader.ReadToEnd();
            streamReader.Close();

            token = new AdmAccessToken();
            Dictionary <string, object> accessTokenValues = Json.Deserialize(jsonObject) as Dictionary <string, object>;
            foreach (KeyValuePair <string, object> tokenValue in accessTokenValues)
            {
                if (tokenValue.Key == "access_token")
                {
                    token.access_token = tokenValue.Value.ToString();
                }
                else if (tokenValue.Key == "token_type")
                {
                    token.token_type = tokenValue.Value.ToString();
                }
                else if (tokenValue.Key == "expires_in")
                {
                    token.expires_in = tokenValue.Value.ToString();
                }
                else if (tokenValue.Key == "scope")
                {
                    token.scope = tokenValue.Value.ToString();
                }
            }
            headerValue = "Bearer " + token.access_token;

            //Set the translator manager to initialized
            Debug.Log("Microsoft Translator is authenticated");
            isInitialized = true;
            GetAllTranslationLanguages();
        }
        catch (Exception ex)
        {
            Debug.LogError("MicrosoftTranslatorManager.cs:" + ex.Message);
        }
        finally
        {
            if (response != null)
            {
                response.Close();
                response = null;
            }
        }
    }
Exemplo n.º 19
0
        private void RenewAccessToken()
        {
            AdmAccessToken newAccessToken = HttpPost(DatamarketAccessUri, this.appKey);

            this.token = newAccessToken;
        }
Exemplo n.º 20
0
        public static string Translate(string text)
        {
            AdmAccessToken token = GetAccessToken();

            string[] textSplit = text.Split(':');

            if (textSplit.Length < 2)
            {
                return("Make sure the command is split by ':' from the text to translate");
            }

            Dictionary <string, string> languageDictionary = new Dictionary <string, string>()
            {
                { "arabic", "ar" },
                { "chinese", "zh-CHS" },
                { "english", "en" },
                { "french", "fr" },
                { "german", "de" },
                { "greek", "el" },
                { "hebrew", "he" },
                { "hindi", "hi" },
                { "italian", "it" },
                { "japanese", "ja" },
                { "klingon", "tlh" },
                { "korean", "ko" },
                { "polish", "pl" },
                { "romanian", "ro" },
                { "russian", "ru" },
                { "spanish", "es" }
            };

            string fromLanguage = null;
            string toLanguage   = null;

            foreach (string word in textSplit[0].Split(' '))
            {
                string wordLower = word.ToLower();
                if (languageDictionary.ContainsKey(wordLower))
                {
                    if (fromLanguage == null)
                    {
                        fromLanguage = languageDictionary[wordLower];
                    }
                    else
                    {
                        toLanguage = languageDictionary[wordLower];
                    }
                }
            }

            if (fromLanguage == null)
            {
                return("You need to specify a language to translate from");
            }
            if (toLanguage == null)
            {
                return("You need to specify a language to translate to");
            }

            string textToTranslate = textSplit[1];

            string translation = GetTranslation(textToTranslate, fromLanguage, toLanguage, token);

            return(translation);
        }
Exemplo n.º 21
0
        private static string GetTranslation(string text, string fromLanguage, string toLanguage, AdmAccessToken token)
        {
            // TRANSLATE
            string headerValue = "Bearer " + token.access_token;
            string textEncoded = WebUtility.UrlEncode(text);
            string uri         = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text={0}&from={1}&to={2}", text, fromLanguage, toLanguage);

            WebRequest translateRequest = WebRequest.Create(uri);

            translateRequest.Headers.Add("Authorization", headerValue);

            WebResponse response = translateRequest.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                string translation = (string)dcs.ReadObject(stream);
                return(translation);
            }
        }
 public TokenServiceCompleteEventArgs(bool isSuccess, AdmAccessToken token)
 {
     IsSuccess        = isSuccess;
     TranslationToken = token;
 }
Exemplo n.º 23
0
 public TranslatorClient(AdmAccessToken authToken)
 {
     this.AuthToken = "Bearer" + " " + authToken.access_token;
 }
Exemplo n.º 24
0
        private static string GetTranslation(string text, string fromLanguage, string toLanguage, AdmAccessToken token)
        {
            // TRANSLATE
            string headerValue = "Bearer " + token.access_token;
            string textEncoded = WebUtility.UrlEncode(text);
            string uri = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text={0}&from={1}&to={2}", text, fromLanguage, toLanguage);

            WebRequest translateRequest = WebRequest.Create(uri);
            translateRequest.Headers.Add("Authorization", headerValue);

            WebResponse response = translateRequest.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                string translation = (string)dcs.ReadObject(stream);
                return translation;

            }
        }
Exemplo n.º 25
0
            private async void RenewAccessToken()
            {
                AdmAccessToken newAccessToken = await HttpPost(DatamarketAccessUri, this.request);

                this.token = newAccessToken;
            }
Exemplo n.º 26
0
 public BingResourceTranslator(string clientId, string baseUrl, string sharedSecret)
 {
     _baseUrl = baseUrl;
     _accessToken = GetAccessToken(clientId, sharedSecret);
 }
Exemplo n.º 27
0
	/// <summary>
	/// Gets the response callback for authentication
	/// </summary>
	/// <param name='ar'>
	/// the result of the callback
	/// </param>
	private void GetResponseCallback(IAsyncResult ar)
	{
		
				
	  // Process the response callback to get the token
	  // we'll then use that token to call the translator service
	  // Pull the request out of the IAsynch result
	  	HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
	  // The request now has the response details in it (because we've called back having gotten the response
		 HttpWebResponse response = null;
		try
		{
	   		response = (HttpWebResponse)request.EndGetResponse(ar);
		}
		catch (WebException e)
        {
			response = null;
            using (response = (HttpWebResponse)e.Response)
            {
				//Error
                HttpWebResponse httpResponse = (HttpWebResponse) response;
                Logger.Log("Error code:" +  httpResponse.StatusCode.ToString());
                using (Stream data = response.GetResponseStream())
                {
                    string text = new StreamReader(data).ReadToEnd();
                    Logger.Log(text);
                }
            }
        }
	  // Using JSON we'll pull the response details out, and load it into an AdmAccess token class 
	  try
	  {		
			//Save the token and the header value for translation
			StreamReader streamReader = new StreamReader(response.GetResponseStream());
			string jsonObject = streamReader.ReadToEnd();
			streamReader.Close();
			
			token = new AdmAccessToken();
			Dictionary<string,object> accessTokenValues = Json.Deserialize(jsonObject) as Dictionary<string,object>;
			foreach(KeyValuePair<string,object> tokenValue in accessTokenValues)
			{
				if(tokenValue.Key == "access_token")
				{
					token.access_token = tokenValue.Value.ToString();
				}
				else if(tokenValue.Key == "token_type")
				{
					token.token_type = tokenValue.Value.ToString();
				}
				else if(tokenValue.Key == "expires_in")
				{
					token.expires_in = tokenValue.Value.ToString();
				}
				else if(tokenValue.Key == "scope")
				{
					token.scope = tokenValue.Value.ToString();
				}
			}
			headerValue = "Bearer " + token.access_token;
			
			//Set the translator manager to initialized
			Logger.Log("Microsoft Translator is authenticated");
			isInitialized = true;
			GetAllTranslationLanguages();
	  }
	  catch (Exception ex)
	  {
		 Logger.Log("MicrosoftTranslatorManager.cs:" + ex.Message);
	  }
	  finally
      {
            if (response != null)
            {
                response.Close();
                response = null;
            }
      }
	}
Exemplo n.º 28
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="from">en</param>
        /// <param name="to">el</param>
        /// <param name="accessToken"></param>
        /// <returns>#NLA# if there was a problem with the service OR the translated text</returns>
        public string TranslateText(HttpApplicationState app, string from, string to, string text)
        {
            string uri = "";
            try
            {
                AdmAccessToken admToken = new AdmAccessToken();
                if (app["BingTranslateAccessToken"] != null)
                {
                    admToken = (AdmAccessToken)app["BingTranslateAccessToken"];
                    int timeLeft = 0;
                    DateTime now = DateTime.Now;
                    DateTime tokenCreatedOn = (DateTime)app["BingTranslateAccessTokenCreatedDateTime"];
                    double difference = (now - tokenCreatedOn).TotalSeconds;

                    if ((now - tokenCreatedOn).TotalSeconds > 580)
                    {
                        RefreshAccessToken(app);
                    }
                }
                else
                {
                    RefreshAccessToken(app);
                }
                admToken = (AdmAccessToken)app["BingTranslateAccessToken"];

                string headerValue;
                //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/
                //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx)

                // Create a header with the access_token property of the returned token
                //headerValue = "Bearer " + admToken.access_token;

                uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to;
                string authToken = "Bearer" + " " + admToken.access_token;

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Headers.Add("Authorization", authToken);

                WebResponse response = null;

                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
                    string translation = (string)dcs.ReadObject(stream);
                    return translation;
                    //Console.WriteLine("Translation for source text '{0}' from {1} to {2} is", text, "en", "de");
                    //Console.WriteLine(translation);
                }
            }
            catch (Exception ex)
            {
                if (app["BingTranslateAccessToken"] != null)
                {
                    AdmAccessToken admToken = (AdmAccessToken)app["BingTranslateAccessToken"];
                    string errorInfo = "Token: " + admToken.access_token + " | Expires in: " + admToken.expires_in + " | Scope: " + admToken.scope + " | Token type: " + admToken.token_type + " | Uri: " + uri;

                    Ourspace_Utilities.View util = new Ourspace_Utilities.View();
                    util.AddTranslationErrorLogEntry(admToken.access_token, uri, admToken.expires_in, ex.Message);
                }
                else
                {
                    Ourspace_Utilities.View util = new Ourspace_Utilities.View();
                    util.AddTranslationErrorLogEntry("no token", uri, "no expires in", ex.Message);
                }
                string error = ex.Message;
                return "#NLA#" + error;
            }
        }