private static AccessToken GetAccessToken(string clientID, string clientSecret) { if (string.IsNullOrEmpty(clientID) && string.IsNullOrEmpty(clientSecret)) { throw new Exception("To enable Bing translation you have to specify the Client ID and the Client Secret in the options."); } if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret)) { throw new Exception("To enable Bing translation you have to specify both the Client ID and the Client Secret in the options."); } string key = string.Format("{0}\x01{1}", clientID, clientSecret); if (BingTranslator._loadedTokens.ContainsKey(key) && !BingTranslator._loadedTokens[key].Expired) { return(BingTranslator._loadedTokens[key]); } else { Dictionary <string, string> fields = new Dictionary <string, string>(); fields.Add("grant_type", "client_credentials"); fields.Add("client_id", clientID); fields.Add("client_secret", clientSecret); fields.Add("scope", "http://api.microsofttranslator.com"); StringBuilder f = null; foreach (KeyValuePair <string, string> kv in fields) { if (f == null) { f = new StringBuilder(); } else { f.Append('&'); } f.Append(HttpUtility.UrlEncode(kv.Key)).Append('=').Append(HttpUtility.UrlEncode(kv.Value)); } WebRequest request = WebRequest.Create("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"); request.ContentType = "application/x-www-form-urlencoded"; request.Method = WebRequestMethods.Http.Post; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(f.ToString()); request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } WebResponse response = null; try { Exception error; try { response = request.GetResponse(); error = null; } catch (WebException x) { response = x.Response; error = x; } string rs; using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8, false)) { rs = reader.ReadToEnd(); } } if (error == null) { AccessToken result = new AccessToken(rs); BingTranslator._loadedTokens.Add(key, result); return(result); } else { ErrorResponseException er = ErrorResponseException.Parse(rs); throw (er == null) ? error : er; } } catch { throw; } finally { if (response != null) { try { response.Close(); } catch { } response = null; } } } }