/SDK Sample Projects/Win8/PushSDK/TagsService.cs

https://github.com/doluyen/push-notifications-sdk · C# · 175 lines · 129 code · 33 blank · 13 comment · 17 complexity · 7c11423eb6630735badbb9aa50620192 MD5 · raw file

  1. using Newtonsoft.Json.Linq;
  2. using PushSDK.Classes;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Threading.Tasks;
  6. using System.Net.Http;
  7. using Newtonsoft.Json;
  8. using System.Linq;
  9. using System.Net;
  10. using System.IO;
  11. using System.Diagnostics;
  12. namespace PushSDK
  13. {
  14. public class TagsService
  15. {
  16. private readonly string _appId;
  17. private readonly HttpClient _httpClient = new HttpClient();
  18. public event EventHandler<CustomEventArgs<List<KeyValuePair<string, string>>>> OnSendingComplete;
  19. public event EventHandler<CustomEventArgs<string>> OnError;
  20. public TagsService(string appId)
  21. {
  22. _appId = appId;
  23. //_webClient.UploadStringCompleted += UploadStringCompleted;
  24. }
  25. /// <summary>
  26. /// Sending tag to server
  27. /// </summary>
  28. /// <param name="tagList">Tags list</param>
  29. public async void SendRequest(List<KeyValuePair<string, object>> tagList)
  30. {
  31. var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);
  32. webRequest.Method = "POST";
  33. webRequest.ContentType = "application/x-www-form-urlencoded";
  34. string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(tagList)));
  35. byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);
  36. // Write the channel URI to the request stream.
  37. Stream requestStream = await webRequest.GetRequestStreamAsync();
  38. requestStream.Write(requestBytes, 0, requestBytes.Length);
  39. try
  40. {
  41. // Get the response from the server.
  42. WebResponse response = await webRequest.GetResponseAsync();
  43. StreamReader requestReader = new StreamReader(response.GetResponseStream());
  44. String webResponse = requestReader.ReadToEnd();
  45. string errorMessage = String.Empty;
  46. Debug.WriteLine("Response: " + webResponse);
  47. JObject jRoot = JObject.Parse(webResponse);
  48. int code = JsonHelpers.GetStatusCode(jRoot);
  49. if (code == 200 || code == 103)
  50. {
  51. UploadStringCompleted(webResponse);
  52. }
  53. else
  54. errorMessage = JsonHelpers.GetStatusMessage(jRoot);
  55. if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
  56. {
  57. Debug.WriteLine("Error: " + errorMessage);
  58. OnError(this, new CustomEventArgs<string> { Result = errorMessage });
  59. }
  60. }
  61. catch (Exception ex)
  62. {
  63. OnError(this, new CustomEventArgs<string> { Result = ex.Message });
  64. }
  65. }
  66. /// <summary>
  67. /// Sending tag to server
  68. /// </summary>
  69. /// <param name="jTagList">tag format: [tagKey:tagValue]</param>
  70. public async void SendRequest(string jTagList)
  71. {
  72. var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);
  73. webRequest.Method = "POST";
  74. webRequest.ContentType = "application/x-www-form-urlencoded";
  75. string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(jTagList)));
  76. byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);
  77. // Write the channel URI to the request stream.
  78. Stream requestStream = await webRequest.GetRequestStreamAsync();
  79. requestStream.Write(requestBytes, 0, requestBytes.Length);
  80. try
  81. {
  82. // Get the response from the server.
  83. WebResponse response = await webRequest.GetResponseAsync();
  84. StreamReader requestReader = new StreamReader(response.GetResponseStream());
  85. String webResponse = requestReader.ReadToEnd();
  86. string errorMessage = String.Empty;
  87. Debug.WriteLine("Response: " + webResponse);
  88. JObject jRoot = JObject.Parse(webResponse);
  89. int code = JsonHelpers.GetStatusCode(jRoot);
  90. if (code == 200 || code == 103)
  91. {
  92. UploadStringCompleted(webResponse);
  93. }
  94. else
  95. errorMessage = JsonHelpers.GetStatusMessage(jRoot);
  96. if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
  97. {
  98. Debug.WriteLine("Error: " + errorMessage);
  99. OnError(this, new CustomEventArgs<string> { Result = errorMessage });
  100. }
  101. }
  102. catch (Exception ex)
  103. {
  104. OnError(this, new CustomEventArgs<string> { Result = ex.Message });
  105. }
  106. }
  107. private string BuildRequest(IEnumerable<KeyValuePair<string, object>> tagList)
  108. {
  109. JObject tags = new JObject();
  110. foreach (var tag in tagList)
  111. {
  112. tags.Add(new JProperty(tag.Key, tag.Value));
  113. }
  114. return BuildRequest(tags.ToString());
  115. }
  116. private string BuildRequest(string tags)
  117. {
  118. return (new JObject(
  119. new JProperty("request",
  120. new JObject(
  121. new JProperty("application", _appId),
  122. new JProperty("hwid", SDKHelpers.GetDeviceUniqueId()),
  123. new JProperty("tags", JObject.Parse(tags)))))).ToString();
  124. }
  125. private void UploadStringCompleted(string responseBodyAsText)
  126. {
  127. JObject jRoot = JObject.Parse(responseBodyAsText);
  128. if (JsonHelpers.GetStatusCode(jRoot) == 200)
  129. {
  130. var skippedTags = new List<KeyValuePair<string, string>>();
  131. if (jRoot["response"].HasValues)
  132. {
  133. JArray jItems = jRoot["response"]["skipped"] as JArray;
  134. skippedTags = jItems.Select(jItem => new KeyValuePair<string, string>(jItem.Value<string>("tag"), jItem.Value<string>("reason"))).ToList();
  135. }
  136. OnSendingComplete(this, new CustomEventArgs<List<KeyValuePair<string, string>>> { Result = skippedTags });
  137. }
  138. else
  139. OnError(this, new CustomEventArgs<string> { Result = JsonHelpers.GetStatusMessage(jRoot) });
  140. }
  141. }
  142. }