public Form1()
        {
            InitializeComponent();
            _authentication = new AzureAuthentication(
                AzureClientCredentials.clientId,
                AzureClientCredentials.clientSecret);

             _token = _authentication.GetAccessToken();
        }
 public AzureAuthentication(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));
 }
        public string Translate(AzureAccessToken token, string originaltext, string from, string to)
        {
            string headerValue = "Bearer " + token.access_token;

            try
            {
                string uri = string.Format(uriService,
                    System.Web.HttpUtility.UrlEncode(originaltext),
                    from,
                    to);

                WebRequest translationWebRequest = WebRequest.Create(uri);
                translationWebRequest.Proxy = null;
                translationWebRequest.Headers.Add("Authorization", headerValue);
                WebResponse response = null;
                response = translationWebRequest.GetResponse();
                Stream stream = response.GetResponseStream();
                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());

                return xTranslation.InnerText;
            }
            catch (WebException webex)
            {
                // Posiblemente el clientID, clientSecret, etc no sean correctos
                throw new System.Exception(webex.Message);
            }
            catch (Exception ex)
            {
                throw new System.Exception(ex.Message);
            }

            return originaltext;
        }
 private void RenewAccessToken()
 {
     AzureAccessToken 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));
 }