PushNotificationMessage.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using WindowsPhone.Recipes.Push.Messasges.Properties;
  9. namespace WindowsPhone.Recipes.Push.Messasges
  10. {
  11. /// <summary>
  12. /// Represents a base class for push notification messages.
  13. /// </summary>
  14. /// <remarks>
  15. /// This class members are thread safe.
  16. /// </remarks>
  17. public abstract class PushNotificationMessage
  18. {
  19. #region Constants
  20. /// <value>Push notification maximum message size including headers and payload.</value>
  21. protected const int MaxMessageSize = 1024;
  22. /// <summary>
  23. /// Well known push notification message web request headers.
  24. /// </summary>
  25. internal static class Headers
  26. {
  27. public const string MessageId = "X-MessageID";
  28. public const string BatchingInterval = "X-NotificationClass";
  29. public const string NotificationStatus = "X-NotificationStatus";
  30. public const string DeviceConnectionStatus = "X-DeviceConnectionStatus";
  31. public const string SubscriptionStatus = "X-SubscriptionStatus";
  32. public const string WindowsPhoneTarget = "X-WindowsPhone-Target";
  33. }
  34. #endregion
  35. #region Fields
  36. /// <value>Synchronizes payload manipulations.</value>
  37. private readonly object _sync = new object();
  38. /// <value>The payload raw bytes of this message.</value>
  39. private byte[] _payload;
  40. private MessageSendPriority _sendPriority;
  41. #endregion
  42. #region Properties
  43. /// <summary>
  44. /// Gets this message unique ID.
  45. /// </summary>
  46. public Guid Id { get; private set; }
  47. /// <summary>
  48. /// Gets or sets the send priority of this message in the MPNS.
  49. /// </summary>
  50. public MessageSendPriority SendPriority
  51. {
  52. get
  53. {
  54. return _sendPriority;
  55. }
  56. set
  57. {
  58. SafeSet(ref _sendPriority, value);
  59. }
  60. }
  61. /// <summary>
  62. /// Gets or sets the message payload.
  63. /// </summary>
  64. protected byte[] Payload
  65. {
  66. get
  67. {
  68. return _payload;
  69. }
  70. set
  71. {
  72. SafeSet(ref _payload, value);
  73. }
  74. }
  75. protected abstract int NotificationClassId
  76. {
  77. get;
  78. }
  79. /// <summary>
  80. /// Gets or sets the flag indicating that one of the message properties
  81. /// has changed, thus the payload should be rebuilt.
  82. /// </summary>
  83. private bool IsDirty { get; set; }
  84. #endregion
  85. #region Ctor
  86. /// <summary>
  87. /// Initializes a new instance of this type with <see cref="WindowsPhone.Recipes.Push.Messasges.MessageSendPriority.Normal"/> send priority.
  88. /// </summary>
  89. protected PushNotificationMessage(MessageSendPriority sendPriority = MessageSendPriority.Normal)
  90. {
  91. Id = Guid.NewGuid();
  92. SendPriority = sendPriority;
  93. IsDirty = true;
  94. }
  95. #endregion
  96. #region Operations
  97. /// <summary>
  98. /// Synchronously send this messasge to the destination address.
  99. /// </summary>
  100. /// <remarks>
  101. /// Note that properties of this instance may be changed by different threads while
  102. /// sending, but once the payload created, it won't be changed until the next send.
  103. /// </remarks>
  104. /// <param name="uri">Destination address uri.</param>
  105. /// <exception cref="ArgumentNullException">One of the arguments is null.</exception>
  106. /// <exception cref="ArgumentOutOfRangeException">Payload size is out of range. For maximum allowed message size see <see cref="PushNotificationMessage.MaxPayloadSize"/></exception>
  107. /// <exception cref="MessageSendException">Failed to send message for any reason.</exception>
  108. /// <returns>The result instance with relevant information for this send operation.</returns>
  109. public MessageSendResult Send(Uri uri)
  110. {
  111. Guard.ArgumentNotNull(uri, "uri");
  112. // Create payload or reuse cached one.
  113. var payload = GetOrCreatePayload();
  114. // Create and initialize the request object.
  115. var request = CreateWebRequest(uri, payload);
  116. var result = SendSynchronously(payload, uri, request);
  117. return result;
  118. }
  119. /// <summary>
  120. /// Asynchronously send this messasge to the destination address.
  121. /// </summary>
  122. /// <remarks>
  123. /// This method uses the .NET Thread Pool. Use this method to send one or few
  124. /// messages asynchronously. If you have many messages to send, please consider
  125. /// of using the synchronous method with custom (external) queue-thread solution.
  126. ///
  127. /// Note that properties of this instance may be changed by different threads while
  128. /// sending, but once the payload created, it won't be changed until the next send.
  129. /// </remarks>
  130. /// <param name="uri">Destination address uri.</param>
  131. /// <param name="messageSent">Message sent callback.</param>
  132. /// <param name="messageError">Message send error callback.</param>
  133. /// <exception cref="ArgumentNullException">One of the arguments is null.</exception>
  134. /// <exception cref="ArgumentOutOfRangeException">Payload size is out of range. For maximum allowed message size see <see cref="PushNotificationMessage.MaxPayloadSize"/></exception>
  135. public void SendAsync(Uri uri, Action<MessageSendResult> messageSent = null, Action<MessageSendResult> messageError = null)
  136. {
  137. Guard.ArgumentNotNull(uri, "uri");
  138. // Create payload or reuse cached one.
  139. var payload = GetOrCreatePayload();
  140. // Create and initialize the request object.
  141. var request = CreateWebRequest(uri, payload);
  142. SendAsynchronously(
  143. payload,
  144. uri,
  145. request,
  146. messageSent ?? (result => { }),
  147. messageError ?? (result => { }));
  148. }
  149. #endregion
  150. #region Protected & Virtuals
  151. /// <summary>
  152. /// Override to create the message payload.
  153. /// </summary>
  154. /// <returns>The messasge payload bytes.</returns>
  155. protected virtual byte[] OnCreatePayload()
  156. {
  157. return _payload;
  158. }
  159. /// <summary>
  160. /// Override to initialize the message web request with custom headers.
  161. /// </summary>
  162. /// <param name="request">The message web request.</param>
  163. protected virtual void OnInitializeRequest(HttpWebRequest request)
  164. {
  165. }
  166. /// <summary>
  167. /// Check the size of the payload and reject it if too big.
  168. /// </summary>
  169. /// <param name="payload">Payload raw bytes.</param>
  170. protected abstract void VerifyPayloadSize(byte[] payload);
  171. /// <summary>
  172. /// Safely set oldValue with newValue in case that are different, and raise the dirty flag.
  173. /// </summary>
  174. /// <typeparam name="T">The type of the value.</typeparam>
  175. /// <param name="oldValue">The old value.</param>
  176. /// <param name="newValue">The new value.</param>
  177. protected void SafeSet<T>(ref T oldValue, T newValue)
  178. {
  179. lock (_sync)
  180. {
  181. if (!object.Equals(oldValue, newValue))
  182. {
  183. oldValue = newValue;
  184. IsDirty = true;
  185. }
  186. }
  187. }
  188. #endregion
  189. #region Privates
  190. /// <summary>
  191. /// Synchronously send this message to the destination uri.
  192. /// </summary>
  193. /// <param name="payload">The message payload bytes.</param>
  194. /// <param name="uri">The message destination uri.</param>
  195. /// <param name="payload">Initialized Web request instance.</param>
  196. /// <returns>The result instance with relevant information for this send operation.</returns>
  197. private MessageSendResult SendSynchronously(byte[] payload, Uri uri, HttpWebRequest request)
  198. {
  199. try
  200. {
  201. // Get the request stream.
  202. using (var requestStream = request.GetRequestStream())
  203. {
  204. // Start to write the payload to the stream.
  205. requestStream.Write(payload, 0, payload.Length);
  206. // Switch to receiving the response from MPNS.
  207. using (var response = (HttpWebResponse)request.GetResponse())
  208. {
  209. var result = new MessageSendResult(this, uri, response);
  210. if (response.StatusCode != HttpStatusCode.OK)
  211. {
  212. throw new InvalidOperationException(string.Format(Resources.ServerErrorStatusCode, response.StatusCode));
  213. }
  214. return result;
  215. }
  216. }
  217. }
  218. catch (WebException ex)
  219. {
  220. var result = new MessageSendResult(this, uri, ex);
  221. throw new MessageSendException(result, ex);
  222. }
  223. catch (Exception ex)
  224. {
  225. var result = new MessageSendResult(this, uri, ex);
  226. throw new MessageSendException(result, ex);
  227. }
  228. }
  229. /// <summary>
  230. /// Asynchronously send this message to the destination uri using the HttpWebRequest context.
  231. /// </summary>
  232. /// <param name="payload">The message payload bytes.</param>
  233. /// <param name="uri">The message destination uri.</param>
  234. /// <param name="payload">Initialized Web request instance.</param>
  235. /// <param name="sent">Message sent callback.</param>
  236. /// <param name="error">Message send error callback.</param>
  237. /// <returns>The result instance with relevant information for this send operation.</returns>
  238. private void SendAsynchronously(byte[] payload, Uri uri, HttpWebRequest request, Action<MessageSendResult> sent, Action<MessageSendResult> error)
  239. {
  240. try
  241. {
  242. // Get the request stream asynchronously.
  243. request.BeginGetRequestStream(requestAsyncResult =>
  244. {
  245. try
  246. {
  247. using (var requestStream = request.EndGetRequestStream(requestAsyncResult))
  248. {
  249. // Start writing the payload to the stream.
  250. requestStream.Write(payload, 0, payload.Length);
  251. }
  252. // Switch to receiving the response from MPNS asynchronously.
  253. request.BeginGetResponse(responseAsyncResult =>
  254. {
  255. try
  256. {
  257. using (var response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult))
  258. {
  259. var result = new MessageSendResult(this, uri, response);
  260. if (response.StatusCode == HttpStatusCode.OK)
  261. {
  262. sent(result);
  263. }
  264. else
  265. {
  266. error(result);
  267. }
  268. }
  269. }
  270. catch (Exception ex3)
  271. {
  272. error(new MessageSendResult(this, uri, ex3));
  273. }
  274. }, null);
  275. }
  276. catch (Exception ex2)
  277. {
  278. error(new MessageSendResult(this, uri, ex2));
  279. }
  280. }, null);
  281. }
  282. catch (Exception ex1)
  283. {
  284. error(new MessageSendResult(this, uri, ex1));
  285. }
  286. }
  287. /// <summary>
  288. /// Create a payload and verify its size.
  289. /// </summary>
  290. /// <returns>Payload raw bytes.</returns>
  291. private byte[] GetOrCreatePayload()
  292. {
  293. if (IsDirty)
  294. {
  295. lock (_sync)
  296. {
  297. if (IsDirty)
  298. {
  299. var payload = OnCreatePayload() ?? new byte[0];
  300. DebugOutput(payload);
  301. VerifyPayloadSize(payload);
  302. _payload = payload;
  303. IsDirty = false;
  304. }
  305. }
  306. }
  307. return _payload;
  308. }
  309. private HttpWebRequest CreateWebRequest(Uri uri, byte[] payload)
  310. {
  311. var request = (HttpWebRequest)WebRequest.Create(uri);
  312. request.Method = WebRequestMethods.Http.Post;
  313. request.ContentType = "text/xml; charset=utf-8";
  314. request.ContentLength = payload.Length;
  315. request.Headers[Headers.MessageId] = Id.ToString();
  316. // Batching interval is composed of the message priority and the message class id.
  317. int batchingInterval = ((int)SendPriority * 10) + NotificationClassId;
  318. request.Headers[Headers.BatchingInterval] = batchingInterval.ToString();
  319. OnInitializeRequest(request);
  320. return request;
  321. }
  322. #endregion
  323. #region Diagnostics
  324. [Conditional("DEBUG")]
  325. private static void DebugOutput(byte[] payload)
  326. {
  327. string payloadString = Encoding.ASCII.GetString(payload);
  328. Debug.WriteLine(payloadString);
  329. }
  330. #endregion
  331. }
  332. }