PageRenderTime 56ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/App_Code/StaffBroker/BingTranslate.cs

https://github.com/mailekah/AgapeConnect1
C# | 154 lines | 137 code | 9 blank | 8 comment | 2 complexity | 9a17062aef910f7318d1e8aeaed48466 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Runtime.Serialization.Json;
  8. using System.Runtime.Serialization;
  9. using System.Web;
  10. using System.ServiceModel.Channels;
  11. using System.ServiceModel;
  12. namespace MicrosoftTranslatorSdk.HttpSamples
  13. {
  14. class Program
  15. {
  16. static void Main(string[] args)
  17. {
  18. AdmAccessToken admToken;
  19. string headerValue;
  20. //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/
  21. //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx)
  22. AdmAuthentication admAuth = new AdmAuthentication("AgapeConnect", "");
  23. try
  24. {
  25. admToken = admAuth.GetAccessToken();
  26. // Create a header with the access_token property of the returned token
  27. headerValue = "Bearer " + admToken.access_token;
  28. DetectMethod(headerValue);
  29. }
  30. catch (WebException e)
  31. {
  32. ProcessWebException(e);
  33. Console.WriteLine("Press any key to continue...");
  34. Console.ReadKey(true);
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.WriteLine(ex.Message);
  39. Console.WriteLine("Press any key to continue...");
  40. Console.ReadKey(true);
  41. }
  42. }
  43. private static void DetectMethod(string authToken)
  44. {
  45. Console.WriteLine("Enter Text to detect language:");
  46. string textToDetect = Console.ReadLine();
  47. //Keep appId parameter blank as we are sending access token in authorization header.
  48. string uri = "http://api.microsofttranslator.com/v2/Http.svc/Detect?text=" + textToDetect;
  49. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
  50. httpWebRequest.Headers.Add("Authorization", authToken);
  51. WebResponse response = null;
  52. try
  53. {
  54. response = httpWebRequest.GetResponse();
  55. using (Stream stream = response.GetResponseStream())
  56. {
  57. System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
  58. string languageDetected = (string)dcs.ReadObject(stream);
  59. Console.WriteLine(string.Format("Language detected:{0}", languageDetected));
  60. Console.WriteLine("Press any key to continue...");
  61. Console.ReadKey(true);
  62. }
  63. }
  64. catch
  65. {
  66. throw;
  67. }
  68. finally
  69. {
  70. if (response != null)
  71. {
  72. response.Close();
  73. response = null;
  74. }
  75. }
  76. }
  77. private static void ProcessWebException(WebException e)
  78. {
  79. Console.WriteLine("{0}", e.ToString());
  80. // Obtain detailed error information
  81. string strResponse = string.Empty;
  82. using (HttpWebResponse response = (HttpWebResponse)e.Response)
  83. {
  84. using (Stream responseStream = response.GetResponseStream())
  85. {
  86. using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
  87. {
  88. strResponse = sr.ReadToEnd();
  89. }
  90. }
  91. }
  92. Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
  93. }
  94. }
  95. [DataContract]
  96. public class AdmAccessToken
  97. {
  98. [DataMember]
  99. public string access_token { get; set; }
  100. [DataMember]
  101. public string token_type { get; set; }
  102. [DataMember]
  103. public string expires_in { get; set; }
  104. [DataMember]
  105. public string scope { get; set; }
  106. }
  107. public class AdmAuthentication
  108. {
  109. public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
  110. private string clientId;
  111. private string cientSecret;
  112. private string request;
  113. public AdmAuthentication(string clientId, string clientSecret)
  114. {
  115. this.clientId = clientId;
  116. this.cientSecret = clientSecret;
  117. //If clientid or client secret has special characters, encode before sending request
  118. 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));
  119. }
  120. public AdmAccessToken GetAccessToken()
  121. {
  122. return HttpPost(DatamarketAccessUri, this.request);
  123. }
  124. private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
  125. {
  126. //Prepare OAuth request
  127. WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
  128. webRequest.ContentType = "application/x-www-form-urlencoded";
  129. webRequest.Method = "POST";
  130. byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
  131. webRequest.ContentLength = bytes.Length;
  132. using (Stream outputStream = webRequest.GetRequestStream())
  133. {
  134. outputStream.Write(bytes, 0, bytes.Length);
  135. }
  136. using (WebResponse webResponse = webRequest.GetResponse())
  137. {
  138. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
  139. //Get deserialized object from JSON stream
  140. AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
  141. return token;
  142. }
  143. }
  144. }
  145. }