public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var message = notification as FirefoxOSNotification; var data = Encoding.UTF8.GetBytes(message.ToString()); var request = (HttpWebRequest)WebRequest.Create(message.EndPointUrl); request.Method = "PUT"; request.ContentLength = data.Length; request.UserAgent = string.Format("PushSharp (version: {0})", version); using (var rs = request.GetRequestStream()) { rs.Write(data, 0, data.Length); } try { request.BeginGetResponse(ResponseCallback, new object[] { request, message, callback }); } catch (WebException ex) { callback(this, new SendNotificationResult(message, false, ex)); } }
void HandleStatus(SendNotificationCallbackDelegate callback, BISMessageStatus status, string desc, BISNotification notification = null) { if (status.NotificationStatus == BISNotificationStatus.NoAppReceivePush) { if (callback != null) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true }); } return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == BISNotificationStatus.RequestAcceptedForProcessing) { if (callback != null) { callback(this, new SendNotificationResult(notification)); } return; } if (callback != null) { callback(this, new SendNotificationResult(status.Notification, false, new BISNotificationSendFailureException(status, desc))); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var msg = notification as GcmNotification; var result = new GcmMessageTransportResponse(); result.Message = msg; //var postData = msg.GetJson(); var webReq = (HttpWebRequest)WebRequest.Create(gcmSettings.GcmUrl); //webReq.ContentLength = postData.Length; webReq.Method = "POST"; webReq.ContentType = "application/json"; //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8 can be used for plaintext bodies webReq.UserAgent = "PushSharp (version: " + assemblyVerison.ToString() + ")"; webReq.Headers.Add("Authorization: key=" + gcmSettings.SenderAuthToken); webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters() { Callback = callback, WebRequest = webReq, WebResponse = null, Message = msg, SenderAuthToken = gcmSettings.SenderAuthToken, SenderId = gcmSettings.SenderID, ApplicationId = gcmSettings.ApplicationIdPackageName }); }
void HandleStatus(SendNotificationCallbackDelegate callback, WindowsPhoneMessageStatus status, WindowsPhoneNotification notification = null) { if (callback == null) { return; } if (status.SubscriptionStatus == WPSubscriptionStatus.Expired) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true, OldSubscriptionId = notification != null ? notification.EndPointUrl : null, SubscriptionExpiryUtc = DateTime.UtcNow }); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Received) { callback(this, new SendNotificationResult(notification)); return; } callback(this, new SendNotificationResult(status.Notification, false, new WindowsPhoneNotificationSendFailureException(status))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { if (string.IsNullOrEmpty(googleAuthToken)) RefreshGoogleAuthToken(); var msg = notification as C2dmNotification; var result = new C2dmMessageTransportResponse(); result.Message = msg; //var postData = msg.GetPostData(); var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL); //webReq.ContentLength = postData.Length; webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.UserAgent = "PushSharp (version: 1.0)"; webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleAuthToken); webReq.BeginGetRequestStream(requestStreamCallback, new C2dmAsyncParameters() { Callback = callback, WebRequest = webReq, WebResponse = null, Message = msg, GoogleAuthToken = googleAuthToken, SenderId = androidSettings.SenderID, ApplicationId = androidSettings.ApplicationID }); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { Interlocked.Increment(ref waitCounter); var msg = notification as GcmNotification; var result = new GcmMessageTransportResponse(); result.Message = msg; //var postData = msg.GetJson(); var webReq = (HttpWebRequest)WebRequest.Create(gcmSettings.GcmUrl); //webReq.ContentLength = postData.Length; webReq.Method = "POST"; webReq.ContentType = "application/json"; //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8 can be used for plaintext bodies webReq.UserAgent = "PushSharp (version: " + assemblyVerison.ToString () + ")"; webReq.Headers.Add("Authorization: key=" + gcmSettings.SenderAuthToken); webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters() { Callback = callback, WebRequest = webReq, WebResponse = null, Message = msg, SenderAuthToken = gcmSettings.SenderAuthToken, SenderId = gcmSettings.SenderID, ApplicationId = gcmSettings.ApplicationIdPackageName }); }
void HandleStatus(SendNotificationCallbackDelegate callback, WindowsPhoneMessageStatus status, WindowsPhoneNotification notification = null) { if (status.SubscriptionStatus == WPSubscriptionStatus.Expired) { if (callback != null) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true }); } } else if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Received) { if (callback != null) { callback(this, new SendNotificationResult(notification)); } } else { if (callback != null) { callback(this, new SendNotificationResult(status.Notification, false, new WindowsPhoneNotificationSendFailureException(status))); } } Interlocked.Decrement(ref waitCounter); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var message = notification as FirefoxOSNotification; var data = Encoding.UTF8.GetBytes(message.ToString()); var request = (HttpWebRequest)WebRequest.Create(message.EndPointUrl); request.Method = "PUT"; request.ContentLength = data.Length; request.UserAgent = string.Format("PushSharp (version: {0})", version); using (var rs = request.GetRequestStream()) { rs.Write(data, 0, data.Length); } try { request.BeginGetResponse(ResponseCallback, new object[] { request, message, callback }); } catch (WebException ex) { callback(this, new SendNotificationResult(message, false, ex)); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { if (string.IsNullOrEmpty(googleAuthToken)) { RefreshGoogleAuthToken(); } var msg = notification as C2dmNotification; var result = new C2dmMessageTransportResponse(); result.Message = msg; //var postData = msg.GetPostData(); var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL); //webReq.ContentLength = postData.Length; webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.UserAgent = "PushSharp (version: 1.0)"; webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleAuthToken); webReq.BeginGetRequestStream(requestStreamCallback, new C2dmAsyncParameters() { Callback = callback, WebRequest = webReq, WebResponse = null, Message = msg, GoogleAuthToken = googleAuthToken, SenderId = androidSettings.SenderID, ApplicationId = androidSettings.ApplicationID }); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { lock (this.sentLock) { Interlocked.Increment(ref this.trackedNotificationCount); AppleNotification notification1 = notification as AppleNotification; bool flag = true; byte[] numArray = new byte[0]; byte[] bytes; try { bytes = notification1.ToBytes(); } catch (NotificationFailureException ex) { flag = false; Interlocked.Decrement(ref this.trackedNotificationCount); if (callback == null) { return; } callback((object)this, new SendNotificationResult(notification, false, (Exception)ex)); return; } try { lock (this.connectLock) this.Connect(); lock (this.streamWriteLock) { if (!this.client.Connected || !this.client.Client.Poll(0, SelectMode.SelectWrite) || !this.networkStream.CanWrite) { throw new ObjectDisposedException("Connection to APNS is not Writable"); } this.networkStream.Write(bytes, 0, bytes.Length); this.networkStream.Flush(); this.sentNotifications.Add(new SentNotification(notification1) { Callback = callback }); Thread.Sleep(1); } } catch (Exception ex) { this.connected = false; Interlocked.Decrement(ref this.trackedNotificationCount); Log.Error("Exception during APNS Send: {0} -> {1}", (object)notification1.Identifier, (object)ex); bool shouldRequeue = true; if (callback == null) { return; } callback((object)this, new SendNotificationResult(notification, shouldRequeue, ex)); } } }
void HandleStatus(WindowsNotificationStatus status, SendNotificationCallbackDelegate callback) { Boolean shouldRequeue = false; if (callback == null) { return; } //RESPONSE HEADERS // X-WNS-Debug-Trace string // X-WNS-DeviceConnectionStatus connected | disconnected | tempdisconnected (if RequestForStatus was set to true) // X-WNS-Error-Description string // X-WNS-Msg-ID string (max 16 char) // X-WNS-NotificationStatus received | dropped | channelthrottled // // 200 OK // 400 One or more headers were specified incorrectly or conflict with another header. // 401 The cloud service did not present a valid authentication ticket. The OAuth ticket may be invalid. // 403 The cloud service is not authorized to send a notification to this URI even though they are authenticated. // 404 The channel URI is not valid or is not recognized by WNS. - Raise Expiry // 405 Invalid Method - never will get // 406 The cloud service exceeded its throttle limit. // 410 The channel expired. - Raise Expiry // 413 The notification payload exceeds the 5000 byte size limit. // 500 An internal failure caused notification delivery to fail. // 503 The server is currently unavailable. if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WindowsNotificationSendStatus.Received) { callback(this, new SendNotificationResult(status.Notification)); return; } if (status.HttpStatus == HttpStatusCode.Unauthorized) { Trace.WriteLine("Status no autorizado, reencolando"); shouldRequeue = true; } if (status.HttpStatus == HttpStatusCode.NotFound || status.HttpStatus == HttpStatusCode.Gone) //404 or 410 { callback(this, new SendNotificationResult(status.Notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true, OldSubscriptionId = status.Notification.ChannelUri, SubscriptionExpiryUtc = DateTime.UtcNow }); return; } callback(this, new SendNotificationResult(status.Notification, shouldRequeue, new WindowsNotificationSendFailureException(status))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { string body; var n = notification as ChromeNotification; try { if (string.IsNullOrEmpty(this.AccessToken) || DateTime.UtcNow >= this.Expires) { RefreshAccessToken(); } var json = new JObject(); json["channelId"] = n.ChannelId; json["subchannelId"] = ((int)n.SubChannelId).ToString(); json["payload"] = n.Payload; var sc = new StringContent(json.ToString()); sc.Headers.ContentType = new MediaTypeHeaderValue("application/json"); sc.Headers.TryAddWithoutValidation("Authorization", "Bearer " + this.AccessToken); var result = http.PostAsync(chromeSettings.Url, sc).Result; body = result.Content.ReadAsStringAsync().Result; if (result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.NoContent) { callback(this, new SendNotificationResult(n)); return; } try { var jsonresp = JObject.Parse(body); var code = jsonresp["error"]["code"].Value <int>(); var message = jsonresp["error"]["message"].Value <string>() ?? "Unknown Error"; callback(this, new SendNotificationResult(n, false, new ChromeNotificationSendFailureException(code, message))); return; } catch { } } catch (Exception ex) { body = ex.ToString(); } Console.WriteLine(body); callback(this, new SendNotificationResult(n, false, new NotificationFailureException(body, n))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { string body; var n = notification as ChromeNotification; try { if (string.IsNullOrEmpty(this.AccessToken) || DateTime.UtcNow >= this.Expires) RefreshAccessToken(); var json = new JObject(); json["channelId"] = n.ChannelId; json["subchannelId"] = ((int)n.SubChannelId).ToString(); json["payload"] = n.Payload; var sc = new StringContent(json.ToString()); sc.Headers.ContentType = new MediaTypeHeaderValue("application/json"); sc.Headers.TryAddWithoutValidation("Authorization", "Bearer " + this.AccessToken); var result = http.PostAsync (chromeSettings.Url, sc).Result; body = result.Content.ReadAsStringAsync ().Result; if (result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.NoContent) { callback(this, new SendNotificationResult(n)); return; } try { var jsonresp = JObject.Parse(body); var code = jsonresp["error"]["code"].Value<int>(); var message = jsonresp["error"]["message"].Value<string>() ?? "Unknown Error"; callback(this, new SendNotificationResult(n, false, new ChromeNotificationSendFailureException(code, message))); return; } catch { } } catch (Exception ex) { body = ex.ToString (); } Log.Debug (body); callback (this, new SendNotificationResult (n, false, new NotificationFailureException(body, n))); }
/// <summary> /// 单推消息 /// </summary> /// <param name="notification"></param> /// <param name="callback"></param> public void SendSingleDeviceNotification(INotification notification, SendNotificationCallbackDelegate callback) { if (/*!(notification is XGSingleDeviceTileNotification) && */ !(notification is XGSingleDeviceRawNotification)) { callback(this, new SendNotificationResult(notification) { ErrMsg = "notification 既不是XGSingleDeviceTileNotification类型,也不是XGSingleDeviceRawNotification类型", RetCode = -99 }); return; } var wr = HttpWebRequest.Create("http://" + pushChannelSetting.XGSingleDevice_RestAPI_Url); wr.ContentType = "application/x-www-form-urlencoded";//"text/json;charset=\"utf-8\""; wr.Method = pushChannelSetting.XGSingleDevice_RestAPI_Method; notification.AccessId = pushChannelSetting.XGSingleDevice_RestAPI_AccessId; notification.TimeStamp = (DateTime.Now.ToLocalTime().Ticks - new DateTime(1970, 1, 1).ToLocalTime().Ticks) / 10000000; notification.GetSign(pushChannelSetting); var postData = notification.GetPostData(); using (var wrs = new StreamWriter(wr.GetRequestStream())) { wrs.Write(postData); } try { wr.BeginGetResponse(getNotificationResponseCallback, new object[] { wr, notification, callback }); } catch (WebException wex) { var resp = wex.Response as HttpWebResponse; var status = resp.StatusCode; if (callback != null) { SendNotificationResult result = new SendNotificationResult(notification, wex); result.HttpStatus = status; callback(this, result); } } }
void HandleStatus(SendNotificationCallbackDelegate callback, WindowsPhoneMessageStatus status, WindowsPhoneNotification notification = null) { if (callback == null) return; if (status.SubscriptionStatus == WPSubscriptionStatus.Expired) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true, OldSubscriptionId = notification != null ? notification.EndPointUrl : null, SubscriptionExpiryUtc = DateTime.UtcNow }); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Received) { callback(this, new SendNotificationResult(notification)); return; } callback(this, new SendNotificationResult(status.Notification, false, new WindowsPhoneNotificationSendFailureException(status))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { //See if we need an access token if (string.IsNullOrEmpty(AccessToken)) { Trace.WriteLine("AccessToken nulo, renovando"); RenewAccessToken(); } if (DateTime.Now > ExpiresIn) { Trace.WriteLine("AccessToken expirado, renovando"); RenewAccessToken(); } var winNotification = notification as WindowsNotification; //https://cloud.notify.windows.com/?token=..... //Authorization: Bearer {AccessToken} // var wnsType = string.Empty; switch (winNotification.Type) { case WindowsNotificationType.Tile: wnsType = "wns/tile"; break; case WindowsNotificationType.Badge: wnsType = "wns/badge"; break; case WindowsNotificationType.DeleteNotification: case WindowsNotificationType.Toast: wnsType = "wns/toast"; break; default: wnsType = "wns/raw"; break; } var request = (HttpWebRequest)HttpWebRequest.Create(winNotification.ChannelUri); // "https://notify.windows.com"); if (winNotification.Type == WindowsNotificationType.DeleteNotification) request.Method = "DELETE"; else request.Method = "POST"; request.Headers.Add("X-WNS-Type", wnsType); request.Headers.Add("Authorization", string.Format("Bearer {0}", this.AccessToken)); request.ContentType = "text/xml"; if (winNotification.Type == WindowsNotificationType.Raw) request.ContentType = "application/octet-stream"; if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && winTileNot.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } else if (winNotification.Type == WindowsNotificationType.Badge) { if (winNotification is WindowsBadgeNumericNotification) { var winTileBadge = winNotification as WindowsBadgeNumericNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } else if (winNotification is WindowsBadgeGlyphNotification) { var winTileBadge = winNotification as WindowsBadgeGlyphNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } else if (winNotification.Type == WindowsNotificationType.Toast) { var winToastPopup = winNotification as WindowsToastNotification; ; if (winToastPopup != null && winToastPopup.SuppressPopup) request.Headers.Add("X-WNS-SuppressPopup", "true"); } else if (winNotification.Type == WindowsNotificationType.DeleteNotification) { var deleteArgs = "type=wns/toast"; if (!string.IsNullOrEmpty(winNotification.NotificationTag)) deleteArgs += string.Format(";tag={0}", winNotification.NotificationTag); if (!string.IsNullOrEmpty(winNotification.NotificationGroup)) deleteArgs += string.Format(";group={0}", winNotification.NotificationGroup); request.Headers.Add("X-WNS-Match", deleteArgs); } if (winNotification.RequestForStatus.HasValue) request.Headers.Add("X-WNS-RequestForStatus", winNotification.RequestForStatus.Value.ToString().ToLower()); if (!string.IsNullOrEmpty(winNotification.NotificationTag)) request.Headers.Add("X-WNS-Tag", winNotification.NotificationTag); if (!string.IsNullOrEmpty(winNotification.NotificationGroup)) request.Headers.Add("X-WNS-Group", winNotification.NotificationGroup); if (winNotification.TimeToLive.HasValue) request.Headers.Add("X-WNS-TTL", winNotification.TimeToLive.Value.ToString()); //Time to live in seconds //Microsoft recommends we disable expect-100 to improve latency request.ServicePoint.Expect100Continue = false; var payload = winNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); request.ContentLength = data.Length; using (var rs = request.GetRequestStream()) rs.Write(data, 0, data.Length); try { request.BeginGetResponse(new AsyncCallback(getResponseCallback), new object[] { request, winNotification, callback }); } catch (WebException wex) { WindowsNotificationStatus status = null; try { //Handle different httpstatuses status = ParseStatus(wex.Response as HttpWebResponse, winNotification); HandleStatus(status, callback); } catch (Exception ex) { Log.Error(ex.Message, ex); HandleStatus(new WindowsNotificationStatus() { HttpStatus = HttpStatusCode.RequestTimeout, DeviceConnectionStatus = WindowsDeviceConnectionStatus.Connected, MessageID = "", Notification = winNotification, NotificationStatus = WindowsNotificationSendStatus.Dropped, }, callback); } } }
public void SendNotification (INotification notification, SendNotificationCallbackDelegate callback) { SendNotificationAsync (notification, callback); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var wpNotification = notification as WindowsPhoneNotification; var uri = new Uri(wpNotification.EndPointUrl, UriKind.Absolute); var wr = (HttpWebRequest)WebRequest.Create(uri); wr.ServicePoint.Expect100Continue = false; wr.UserAgent = string.Format("PushSharp/{0}", assemblyVerison.ToString(4)); wr.ContentType = "text/xml;charset=\"utf-8\""; wr.Method = "POST"; wr.KeepAlive = false; #region batching intervall var immediateValue = 3; var mediumValue = 13; var slowValue = 23; if (wpNotification is WindowsPhoneToastNotification) { immediateValue = 2; mediumValue = 12; slowValue = 22; } else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) { immediateValue = 1; mediumValue = 11; slowValue = 21; } var val = immediateValue; if (wpNotification.NotificationClass.HasValue) { if (wpNotification.NotificationClass.Value == BatchingInterval.Medium) { val = mediumValue; } else if (wpNotification.NotificationClass.Value == BatchingInterval.Slow) { val = slowValue; } } wr.Headers.Add("X-NotificationClass", val.ToString()); #endregion #region notification type if (wpNotification is WindowsPhoneToastNotification) { wr.Headers.Add("X-WindowsPhone-Target", "toast"); } else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) { wr.Headers.Add("X-WindowsPhone-Target", "token"); } #endregion #region message id if (wpNotification.MessageID != null) { wr.Headers.Add("X-MessageID", wpNotification.MessageID.ToString()); } #endregion #region certificate if (this.windowsPhoneSettings.WebServiceCertificate != null) { wr.ClientCertificates.Add(this.windowsPhoneSettings.WebServiceCertificate); } #endregion wr.BeginGetRequestStream(requestCallback, new object[] { wr, wpNotification, callback }); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { SendNotificationAsync(notification, callback); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { lock (sentLock) { Interlocked.Increment(ref trackedNotificationCount); var appleNotification = notification as AppleNotification; bool isOkToSend = true; byte[] notificationData = new byte[] {}; try { notificationData = appleNotification.ToBytes(); } catch (NotificationFailureException nfex) { //Bad notification format already isOkToSend = false; Interlocked.Decrement(ref trackedNotificationCount); if (callback != null) callback(this, new SendNotificationResult(notification, false, nfex)); return; } try { lock (connectLock) Connect(); lock (streamWriteLock) { bool stillConnected = client.Connected && client.Client.Poll(0, SelectMode.SelectWrite) && networkStream.CanWrite; if (!stillConnected) throw new ObjectDisposedException("Connection to APNS is not Writable"); //if (notificationData.Length > 45) //{ // networkStream.Write(notificationData, 0, 45); // networkStream.Write(notificationData, 45, notificationData.Length - 45); //} //else networkStream.Write(notificationData, 0, notificationData.Length); networkStream.Flush(); sentNotifications.Add(new SentNotification(appleNotification) {Callback = callback}); Thread.Sleep(1); //Cleanup(); } } catch (Exception ex) { connected = false; //If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref trackedNotificationCount); Log.Error ("Exception during APNS Send: {0} -> {1}", appleNotification.Identifier, ex); var shouldRequeue = true; if (callback != null) callback(this, new SendNotificationResult(notification, shouldRequeue, ex)); } } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { lock (sentLock) { Interlocked.Increment(ref trackedNotificationCount); var appleNotification = notification as AppleNotification; bool isOkToSend = true; byte[] notificationData = new byte[] {}; try { notificationData = appleNotification.ToBytes(); } catch (NotificationFailureException nfex) { //Bad notification format already isOkToSend = false; Interlocked.Decrement(ref trackedNotificationCount); if (callback != null) { callback(this, new SendNotificationResult(notification, false, nfex)); } return; } try { lock (connectLock) Connect(); lock (streamWriteLock) { bool stillConnected = client.Connected && client.Client.Poll(0, SelectMode.SelectWrite) && networkStream.CanWrite; if (!stillConnected) { throw new ObjectDisposedException("Connection to APNS is not Writable"); } //if (notificationData.Length > 45) //{ // networkStream.Write(notificationData, 0, 45); // networkStream.Write(notificationData, 45, notificationData.Length - 45); //} //else networkStream.Write(notificationData, 0, notificationData.Length); networkStream.Flush(); sentNotifications.Add(new SentNotification(appleNotification) { Callback = callback }); Thread.Sleep(1); //Cleanup(); } } catch (Exception ex) { connected = false; //If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref trackedNotificationCount); Log.Error("Exception during APNS Send: {0} -> {1}", appleNotification.Identifier, ex); var shouldRequeue = true; if (callback != null) { callback(this, new SendNotificationResult(notification, shouldRequeue, ex)); } } } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var n = notification as BlackberryNotification; try { var response = http.PostNotification(bisChannelSettings, n).Result; var description = string.Empty; var status = new BlackberryMessageStatus { Notification = n, HttpStatus = HttpStatusCode.ServiceUnavailable }; var bbNotStatus = string.Empty; status.HttpStatus = response.StatusCode; var doc = XDocument.Load(response.Content.ReadAsStreamAsync().Result); var result = doc.Descendants("response-result").SingleOrDefault(); if (result != null) { bbNotStatus = result.Attribute("code").Value; description = result.Attribute("desc").Value; } else { result = doc.Descendants("badmessage-response").SingleOrDefault(); if (result != null) { bbNotStatus = result.Attribute("code").Value; description = result.Attribute("desc").Value; } } BlackberryNotificationStatus notStatus; Enum.TryParse(bbNotStatus, true, out notStatus); status.NotificationStatus = notStatus; if (status.NotificationStatus == BlackberryNotificationStatus.NoAppReceivePush) { if (callback != null) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true }); } return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == BlackberryNotificationStatus.RequestAcceptedForProcessing) { if (callback != null) { callback(this, new SendNotificationResult(notification)); } return; } if (callback != null) { callback(this, new SendNotificationResult(status.Notification, false, new BisNotificationSendFailureException(status, description))); } } catch (Exception ex) { if (callback != null) { callback(this, new SendNotificationResult(notification, false, ex)); } } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { FacebookNotification msg = notification as FacebookNotification; FacebookMessageTransportResponse result = new FacebookMessageTransportResponse(); result.Message = msg; FacebookClient v_FacebookClient = new FacebookClient(); if (!string.IsNullOrEmpty(this.FacebookSettings.AppAccessToken)) { v_FacebookClient.AccessToken = this.FacebookSettings.AppAccessToken; } else { v_FacebookClient.AccessToken = this.GetAppAccessToken(); } Dictionary<string, object> parameters = new Dictionary<string, object>(); switch (msg.NotificationType) { case FacebookNotificationType.ApplicationRequest: parameters["message"] = msg.Message; parameters["title"] = msg.Title; break; case FacebookNotificationType.Wall: parameters["message"] = msg.Message; break; case FacebookNotificationType.Notification: default: parameters["href"] = msg.CallbackUrl; parameters["template"] = msg.Message; parameters["ref"] = msg.Category; break; } // Prepare object in call back FacebookAsyncParameters v_FacebookAsyncParameters = new FacebookAsyncParameters() { Callback = callback, WebRequest = null, WebResponse = null, Message = msg, AppAccessToken = FacebookSettings.AppAccessToken, AppId = FacebookSettings.AppId, AppSecret = FacebookSettings.AppSecret }; CancellationToken v_CancellationToken = new CancellationToken(); v_FacebookClient.PostCompleted += FacebookClient_PostCompleted; IDictionary<string, object> v_FacebookClientResult = v_FacebookClient.PostTaskAsync (string.Format("{0}/{1}", msg.RegistrationIds[0], msg.CommandNotification) , parameters , v_FacebookAsyncParameters , v_CancellationToken) as IDictionary<string, object>; //var postData = msg.GetJson(); //var webReq = (HttpWebRequest)WebRequest.Create(FacebookSettings.FacebookUrl); ////webReq.ContentLength = postData.Length; //webReq.Method = "POST"; //webReq.ContentType = "application/json"; ////webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8 can be used for plaintext bodies //webReq.UserAgent = "PushSharp (version: 1.0)"; //webReq.Headers.Add("Authorization: key=" + FacebookSettings.SenderAuthToken); //webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new FacebookAsyncParameters() //{ // Callback = callback, // WebRequest = webReq, // WebResponse = null, // Message = msg, // SenderAuthToken = FacebookSettings.SenderAuthToken, // SenderId = FacebookSettings.SenderID, // ApplicationId = FacebookSettings.ApplicationIdPackageName //}); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { //See if we need an access token if (string.IsNullOrEmpty(AccessToken)) RenewAccessToken(); var winNotification = notification as WindowsNotification; //https://cloud.notify.windows.com/?token=..... //Authorization: Bearer {AccessToken} // var wnsType = string.Empty; switch (winNotification.Type) { case WindowsNotificationType.Tile: wnsType = "wns/tile"; break; case WindowsNotificationType.Badge: wnsType = "wns/badge"; break; case WindowsNotificationType.Toast: wnsType = "wns/toast"; break; default: wnsType = "wns/raw"; break; } var request = (HttpWebRequest)HttpWebRequest.Create(winNotification.ChannelUri); // "https://notify.windows.com"); request.Method = "POST"; request.Headers.Add("X-WNS-Type", wnsType); request.Headers.Add("Authorization", string.Format("Bearer {0}", this.AccessToken)); request.ContentType = "text/xml"; if (winNotification.Type == WindowsNotificationType.Raw) request.ContentType = "application/octet-stream"; if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && winTileNot.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } else if (winNotification.Type == WindowsNotificationType.Badge) { if (winNotification is WindowsBadgeNumericNotification) { var winTileBadge = winNotification as WindowsBadgeNumericNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } else if (winNotification is WindowsBadgeGlyphNotification) { var winTileBadge = winNotification as WindowsBadgeGlyphNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } if (winNotification.RequestForStatus.HasValue) request.Headers.Add("X-WNS-RequestForStatus", winNotification.RequestForStatus.Value.ToString().ToLower()); if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && !string.IsNullOrEmpty(winTileNot.NotificationTag)) request.Headers.Add("X-WNS-Tag", winTileNot.NotificationTag); // TILE only } if (winNotification.TimeToLive.HasValue) request.Headers.Add("X-WNS-TTL", winNotification.TimeToLive.Value.ToString()); //Time to live in seconds //Microsoft recommends we disable expect-100 to improve latency request.ServicePoint.Expect100Continue = false; var payload = winNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); request.ContentLength = data.Length; using (var rs = request.GetRequestStream()) rs.Write(data, 0, data.Length); try { request.BeginGetResponse(new AsyncCallback(getResponseCallback), new object[] { request, winNotification, callback }); } catch (WebException wex) { //Handle different httpstatuses var status = ParseStatus(wex.Response as HttpWebResponse, winNotification); HandleStatus(status, callback); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { //See if we need an access token if (string.IsNullOrEmpty(AccessToken)) { Trace.WriteLine("AccessToken nulo, renovando"); RenewAccessToken(); } if (DateTime.Now > ExpiresIn) { Trace.WriteLine("AccessToken expirado, renovando"); RenewAccessToken(); } var winNotification = notification as WindowsNotification; //https://cloud.notify.windows.com/?token=..... //Authorization: Bearer {AccessToken} // var wnsType = string.Empty; switch (winNotification.Type) { case WindowsNotificationType.Tile: wnsType = "wns/tile"; break; case WindowsNotificationType.Badge: wnsType = "wns/badge"; break; case WindowsNotificationType.DeleteNotification: case WindowsNotificationType.Toast: wnsType = "wns/toast"; break; default: wnsType = "wns/raw"; break; } var request = (HttpWebRequest)HttpWebRequest.Create(winNotification.ChannelUri); // "https://notify.windows.com"); if (winNotification.Type == WindowsNotificationType.DeleteNotification) { request.Method = "DELETE"; } else { request.Method = "POST"; } request.Headers.Add("X-WNS-Type", wnsType); request.Headers.Add("Authorization", string.Format("Bearer {0}", this.AccessToken)); request.ContentType = "text/xml"; if (winNotification.Type == WindowsNotificationType.Raw) { request.ContentType = "application/octet-stream"; } if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && winTileNot.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } else if (winNotification.Type == WindowsNotificationType.Badge) { if (winNotification is WindowsBadgeNumericNotification) { var winTileBadge = winNotification as WindowsBadgeNumericNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } else if (winNotification is WindowsBadgeGlyphNotification) { var winTileBadge = winNotification as WindowsBadgeGlyphNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } } else if (winNotification.Type == WindowsNotificationType.Toast) { var winToastPopup = winNotification as WindowsToastNotification;; if (winToastPopup != null && winToastPopup.SuppressPopup) { request.Headers.Add("X-WNS-SuppressPopup", "true"); } } else if (winNotification.Type == WindowsNotificationType.DeleteNotification) { var deleteArgs = "type=wns/toast"; if (!string.IsNullOrEmpty(winNotification.NotificationTag)) { deleteArgs += string.Format(";tag={0}", winNotification.NotificationTag); } if (!string.IsNullOrEmpty(winNotification.NotificationGroup)) { deleteArgs += string.Format(";group={0}", winNotification.NotificationGroup); } request.Headers.Add("X-WNS-Match", deleteArgs); } if (winNotification.RequestForStatus.HasValue) { request.Headers.Add("X-WNS-RequestForStatus", winNotification.RequestForStatus.Value.ToString().ToLower()); } if (!string.IsNullOrEmpty(winNotification.NotificationTag)) { request.Headers.Add("X-WNS-Tag", winNotification.NotificationTag); } if (!string.IsNullOrEmpty(winNotification.NotificationGroup)) { request.Headers.Add("X-WNS-Group", winNotification.NotificationGroup); } if (winNotification.TimeToLive.HasValue) { request.Headers.Add("X-WNS-TTL", winNotification.TimeToLive.Value.ToString()); //Time to live in seconds } //Microsoft recommends we disable expect-100 to improve latency request.ServicePoint.Expect100Continue = false; var payload = winNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); request.ContentLength = data.Length; using (var rs = request.GetRequestStream()) rs.Write(data, 0, data.Length); try { request.BeginGetResponse(new AsyncCallback(getResponseCallback), new object[] { request, winNotification, callback }); } catch (WebException wex) { WindowsNotificationStatus status = null; try { //Handle different httpstatuses status = ParseStatus(wex.Response as HttpWebResponse, winNotification); HandleStatus(status, callback); } catch (Exception ex) { Log.Error(ex.Message, ex); HandleStatus(new WindowsNotificationStatus() { HttpStatus = HttpStatusCode.RequestTimeout, DeviceConnectionStatus = WindowsDeviceConnectionStatus.Connected, MessageID = "", Notification = winNotification, NotificationStatus = WindowsNotificationSendStatus.Dropped, }, callback); } } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var bbNotification = notification as BISNotification; var bbr = WebRequest.Create(BisSettings.BbUrl) as HttpWebRequest; if (bbNotification == null || bbr == null) { return; } bbr.Method = "POST"; bbr.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"; bbr.KeepAlive = true; bbr.PreAuthenticate = true; bbr.ContentType = "multipart/related; boundary=" + BisSettings.Boundary + "; type=application/xml"; var authInfo = BisSettings.BbApplicationId + ":" + BisSettings.PushPassword; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); bbr.Headers.Add("Authorization", "Basic " + authInfo); var dataToSend = new StringBuilder(); dataToSend.AppendLine("--" + BisSettings.Boundary); dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8"); dataToSend.AppendLine(""); dataToSend.AppendLine("<?xml version=\"1.0\"?>"); dataToSend.AppendLine("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\">"); dataToSend.AppendLine("<pap>"); var pushId = DateTime.Now.ToFileTime().ToString(CultureInfo.InvariantCulture); var deliverBefore = DateTime.UtcNow.AddMinutes(5).ToString("s", CultureInfo.InvariantCulture) + "Z"; dataToSend.AppendLine("<push-message push-id=\"" + pushId + "\" deliver-before-timestamp=\"" + deliverBefore + "\" source-reference=\"" + BisSettings.BbApplicationId + "\">"); dataToSend.AppendLine("<address address-value=\"" + bbNotification.DeviceToken + "\"/>"); dataToSend.AppendLine("<quality-of-service delivery-method=\"unconfirmed\"/>"); dataToSend.AppendLine("</push-message>"); dataToSend.AppendLine("</pap>"); dataToSend.AppendLine("--" + BisSettings.Boundary); dataToSend.AppendLine("Content-Type: " + bbNotification.BISContentType); dataToSend.AppendLine("Push-Message-ID: " + pushId); //Custom payload goes here,I can add as many payload items as I want //but I have to put each item in a new line i.e I used profileId dataToSend.AppendLine(bbNotification.PayLoadToString()); //if (bbNotification.BISNoType != BISNotificationType.JpegImage) //{ dataToSend.AppendLine(bbNotification.Message); //} //else //{ // dataToSend.AppendLine(bbNotification.GetJpegImageBytes()); //} dataToSend.AppendLine("--" + BisSettings.Boundary + "--"); dataToSend.AppendLine(""); var data = Encoding.UTF8.GetBytes(dataToSend.ToString()); bbr.ContentLength = data.Length; using (var rs = bbr.GetRequestStream()) { rs.Write(data, 0, data.Length); } try { bbr.BeginGetResponse(GetResponseCallback, new object[] { bbr, bbNotification, callback }); } catch (WebException wex) { // Handle different statuses string desc = string.Empty; var status = new BISMessageStatus(); ParseStatus(wex.Response as HttpWebResponse, bbNotification, ref status, ref desc); HandleStatus(callback, status, desc, bbNotification); } }
void SendNotificationAsync(INotification notification, SendNotificationCallbackDelegate callback) { var n = notification as AdmNotification; try { Interlocked.Increment(ref waitCounter); if (string.IsNullOrEmpty(AccessToken) || Expires <= DateTime.UtcNow) { UpdateAccessToken(); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); } var sc = new StringContent(n.ToJson()); sc.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = http.PostAsync (string.Format(admSettings.AdmSendUrl, n.RegistrationId), sc).Result; if (response.IsSuccessStatusCode) { callback(this, new SendNotificationResult(n)); return; } var data = response.Content.ReadAsStringAsync().Result; var json = JObject.Parse (data); var reason = json ["reason"].ToString (); var regId = n.RegistrationId; if (json["registrationID"] != null) regId = json["registrationID"].ToString(); switch (response.StatusCode) { case HttpStatusCode.BadGateway: //400 case HttpStatusCode.BadRequest: // if ("InvalidRegistrationId".Equals (reason, StringComparison.InvariantCultureIgnoreCase)) { callback (this, new SendNotificationResult (n) { IsSubscriptionExpired = true, OldSubscriptionId = regId }); } callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Send Failed: " + reason))); break; case HttpStatusCode.Unauthorized: //401 //Access token expired this.AccessToken = null; callback(this, new SendNotificationResult(n, true)); break; case HttpStatusCode.Forbidden: //403 callback(this, new SendNotificationResult(n, true, new AdmRateLimitExceededException(n, "Rate Limit Exceeded (" + reason + ")"))); break; case HttpStatusCode.RequestEntityTooLarge: //413 callback(this, new SendNotificationResult(n, false, new AdmMessageTooLargeException(n, "ADM Message too Large, must be <= 6kb"))); break; default: callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Unknown Failure"))); break; } } catch (Exception ex) { callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Unknown Failure"))); } finally { Interlocked.Decrement (ref waitCounter); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var wpNotification = notification as WindowsPhoneNotification; var wr = HttpWebRequest.Create(wpNotification.EndPointUrl) as HttpWebRequest; wr.ContentType = "text/xml;charset=\"utf-8\""; wr.Method = "POST"; var immediateValue = 3; var mediumValue = 13; var slowValue = 23; if (wpNotification is WindowsPhoneToastNotification) { immediateValue = 2; mediumValue = 12; slowValue = 22; } else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) { immediateValue = 1; mediumValue = 11; slowValue = 21; } var val = immediateValue; if (wpNotification.NotificationClass.HasValue) { if (wpNotification.NotificationClass.Value == BatchingInterval.Medium) val = mediumValue; else if (wpNotification.NotificationClass.Value == BatchingInterval.Slow) val = slowValue; } wr.Headers.Add("X-NotificationClass", val.ToString()); if (wpNotification is WindowsPhoneToastNotification) wr.Headers.Add("X-WindowsPhone-Target", "toast"); else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) wr.Headers.Add("X-WindowsPhone-Target", "token"); if (wpNotification.MessageID != null) wr.Headers.Add("X-MessageID", wpNotification.MessageID.ToString()); var payload = wpNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); wr.ContentLength = data.Length; if (this.windowsPhoneSettings.WebServiceCertificate != null) wr.ClientCertificates.Add(this.windowsPhoneSettings.WebServiceCertificate); using (var rs = wr.GetRequestStream()) { rs.Write(data, 0, data.Length); } try { wr.BeginGetResponse(getResponseCallback, new object[] { wr, wpNotification, callback }); } catch (WebException wex) { //Handle different httpstatuses var status = ParseStatus(wex.Response as HttpWebResponse, wpNotification); HandleStatus(callback, status, wpNotification); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var wpNotification = notification as WindowsPhoneNotification; var wr = HttpWebRequest.Create(wpNotification.EndPointUrl) as HttpWebRequest; wr.ContentType = "text/xml;charset=\"utf-8\""; wr.Method = "POST"; var immediateValue = 3; var mediumValue = 13; var slowValue = 23; if (wpNotification is WindowsPhoneToastNotification) { immediateValue = 2; mediumValue = 12; slowValue = 22; } else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) { immediateValue = 1; mediumValue = 11; slowValue = 21; } var val = immediateValue; if (wpNotification.NotificationClass.HasValue) { if (wpNotification.NotificationClass.Value == BatchingInterval.Medium) { val = mediumValue; } else if (wpNotification.NotificationClass.Value == BatchingInterval.Slow) { val = slowValue; } } wr.Headers.Add("X-NotificationClass", val.ToString()); if (wpNotification is WindowsPhoneToastNotification) { wr.Headers.Add("X-WindowsPhone-Target", "toast"); } else if (wpNotification is WindowsPhoneTileNotification || wpNotification is WindowsPhoneCycleTileNotification || wpNotification is WindowsPhoneFlipTileNotification || wpNotification is WindowsPhoneIconicTileNotification) { wr.Headers.Add("X-WindowsPhone-Target", "token"); } if (wpNotification.MessageID != null) { wr.Headers.Add("X-MessageID", wpNotification.MessageID.ToString()); } var payload = wpNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); wr.ContentLength = data.Length; if (this.windowsPhoneSettings.WebServiceCertificate != null) { wr.ClientCertificates.Add(this.windowsPhoneSettings.WebServiceCertificate); } using (var rs = wr.GetRequestStream()) { rs.Write(data, 0, data.Length); } try { wr.BeginGetResponse(getResponseCallback, new object[] { wr, wpNotification, callback }); } catch (WebException wex) { //Handle different httpstatuses var status = ParseStatus(wex.Response as HttpWebResponse, wpNotification); HandleStatus(callback, status, wpNotification); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { Interlocked.Increment(ref _trackedNotificationCount); var appleNotification = notification as AppleNotification; if (appleNotification == null) { throw new ArgumentException("Notification was not an AppleNotification", "notification"); } Exception failure; byte[] notificationData; if (!TryGetNotificationData(appleNotification, out notificationData, out failure)) { Interlocked.Decrement(ref _trackedNotificationCount); if (callback != null) { callback(this, new SendNotificationResult(notification, false, failure)); } return; } try { EnsureConnected(); lock (_sendLock) { PollConnection(); Log.Debug("ApplePushChannel instance {0}: Sending notification {1}", _channelInstanceId, appleNotification.Identifier); _networkStream.Write(notificationData, 0, notificationData.Length); _networkStream.Flush(); _sentNotifications.Add(new SentNotification(appleNotification) { Callback = callback }); } } catch (Exception exception) { Disconnect(); Log.Error("Exception during APNS Send with channel {2}: {0} -> {1}", appleNotification.Identifier, exception, _channelInstanceId); // If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref _trackedNotificationCount); if (callback != null) { callback(this, new SendNotificationResult(notification, true, exception)); } } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { var n = notification as BlackberryNotification; try { var response = http.PostNotification(bisChannelSettings, n).Result; var description = string.Empty; var status = new BlackberryMessageStatus { Notification = n, HttpStatus = HttpStatusCode.ServiceUnavailable }; var bbNotStatus = string.Empty; status.HttpStatus = response.StatusCode; var doc = XDocument.Load(response.Content.ReadAsStreamAsync().Result); var result = doc.Descendants("response-result").SingleOrDefault(); if (result != null) { bbNotStatus = result.Attribute("code").Value; description = result.Attribute("desc").Value; } else { result = doc.Descendants("badmessage-response").SingleOrDefault(); if (result != null) { bbNotStatus = result.Attribute("code").Value; description = result.Attribute("desc").Value; } } BlackberryNotificationStatus notStatus; Enum.TryParse(bbNotStatus, true, out notStatus); status.NotificationStatus = notStatus; if (status.NotificationStatus == BlackberryNotificationStatus.NoAppReceivePush) { if (callback != null) callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true }); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == BlackberryNotificationStatus.RequestAcceptedForProcessing) { if (callback != null) callback(this, new SendNotificationResult(notification)); return; } if (callback != null) callback(this, new SendNotificationResult(status.Notification, false, new BisNotificationSendFailureException(status, description))); } catch (Exception ex) { if (callback != null) callback(this, new SendNotificationResult(notification, false, ex)); } }
void HandleStatus(SendNotificationCallbackDelegate callback, WindowsPhoneMessageStatus status, WindowsPhoneNotification notification = null) { if (status.SubscriptionStatus == WPSubscriptionStatus.Expired) { if (callback != null) callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true }); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Received) { if (callback != null) callback(this, new SendNotificationResult(notification)); return; } if (callback != null) callback(this, new SendNotificationResult(status.Notification, false, new WindowsPhoneNotificationSendFailureException(status))); }
void SendNotificationAsync(INotification notification, SendNotificationCallbackDelegate callback) { var n = notification as AdmNotification; try { Interlocked.Increment(ref waitCounter); if (string.IsNullOrEmpty(AccessToken) || Expires <= DateTime.UtcNow) { UpdateAccessToken(); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); } var sc = new StringContent(n.ToJson()); sc.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = http.PostAsync(string.Format(admSettings.AdmSendUrl, n.RegistrationId), sc).Result; if (response.IsSuccessStatusCode) { callback(this, new SendNotificationResult(n)); return; } var data = response.Content.ReadAsStringAsync().Result; var json = JObject.Parse(data); var reason = json ["reason"].ToString(); var regId = n.RegistrationId; if (json["registrationID"] != null) { regId = json["registrationID"].ToString(); } switch (response.StatusCode) { case HttpStatusCode.BadGateway: //400 case HttpStatusCode.BadRequest: // if ("InvalidRegistrationId".Equals(reason, StringComparison.InvariantCultureIgnoreCase)) { callback(this, new SendNotificationResult(n) { IsSubscriptionExpired = true, OldSubscriptionId = regId }); } callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Send Failed: " + reason))); break; case HttpStatusCode.Unauthorized: //401 //Access token expired this.AccessToken = null; callback(this, new SendNotificationResult(n, true)); break; case HttpStatusCode.Forbidden: //403 callback(this, new SendNotificationResult(n, true, new AdmRateLimitExceededException(n, "Rate Limit Exceeded (" + reason + ")"))); break; case HttpStatusCode.RequestEntityTooLarge: //413 callback(this, new SendNotificationResult(n, false, new AdmMessageTooLargeException(n, "ADM Message too Large, must be <= 6kb"))); break; default: callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Unknown Failure"))); break; } } catch (Exception ex) { callback(this, new SendNotificationResult(n, false, new AdmSendException(n, "Unknown Failure"))); } finally { Interlocked.Decrement(ref waitCounter); } }
void HandleStatus(WindowsNotificationStatus status, SendNotificationCallbackDelegate callback) { if (callback == null) return; //RESPONSE HEADERS // X-WNS-Debug-Trace string // X-WNS-DeviceConnectionStatus connected | disconnected | tempdisconnected (if RequestForStatus was set to true) // X-WNS-Error-Description string // X-WNS-Msg-ID string (max 16 char) // X-WNS-NotificationStatus received | dropped | channelthrottled // // 200 OK // 400 One or more headers were specified incorrectly or conflict with another header. // 401 The cloud service did not present a valid authentication ticket. The OAuth ticket may be invalid. // 403 The cloud service is not authorized to send a notification to this URI even though they are authenticated. // 404 The channel URI is not valid or is not recognized by WNS. - Raise Expiry // 405 Invalid Method - never will get // 406 The cloud service exceeded its throttle limit. // 410 The channel expired. - Raise Expiry // 413 The notification payload exceeds the 5000 byte size limit. // 500 An internal failure caused notification delivery to fail. // 503 The server is currently unavailable. if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WindowsNotificationSendStatus.Received) { callback(this, new SendNotificationResult(status.Notification)); return; } if (status.HttpStatus == HttpStatusCode.NotFound || status.HttpStatus == HttpStatusCode.Gone) //404 or 410 { callback(this, new SendNotificationResult(status.Notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true, OldSubscriptionId = status.Notification.ChannelUri, SubscriptionExpiryUtc = DateTime.UtcNow }); return; } callback(this, new SendNotificationResult(status.Notification, false, new WindowsNotificationSendFailureException(status))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { //See if we need an access token if (string.IsNullOrEmpty(AccessToken)) { RenewAccessToken(); } var winNotification = notification as WindowsNotification; //https://cloud.notify.windows.com/?token=..... //Authorization: Bearer {AccessToken} // var wnsType = string.Empty; switch (winNotification.Type) { case WindowsNotificationType.Tile: wnsType = "wns/tile"; break; case WindowsNotificationType.Badge: wnsType = "wns/badge"; break; case WindowsNotificationType.Toast: wnsType = "wns/toast"; break; default: wnsType = "wns/raw"; break; } var request = (HttpWebRequest)HttpWebRequest.Create(winNotification.ChannelUri); // "https://notify.windows.com"); request.Method = "POST"; request.Headers.Add("X-WNS-Type", wnsType); request.Headers.Add("Authorization", string.Format("Bearer {0}", this.AccessToken)); request.ContentType = "text/xml"; if (winNotification.Type == WindowsNotificationType.Raw) { request.ContentType = "application/octet-stream"; } if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && winTileNot.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileNot.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } else if (winNotification.Type == WindowsNotificationType.Badge) { if (winNotification is WindowsBadgeNumericNotification) { var winTileBadge = winNotification as WindowsBadgeNumericNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } else if (winNotification is WindowsBadgeGlyphNotification) { var winTileBadge = winNotification as WindowsBadgeGlyphNotification; if (winTileBadge != null && winTileBadge.CachePolicy.HasValue) { request.Headers.Add("X-WNS-Cache-Policy", winTileBadge.CachePolicy == WindowsNotificationCachePolicyType.Cache ? "cache" : "no-cache"); } } } if (winNotification.RequestForStatus.HasValue) { request.Headers.Add("X-WNS-RequestForStatus", winNotification.RequestForStatus.Value.ToString().ToLower()); } if (winNotification.Type == WindowsNotificationType.Tile) { var winTileNot = winNotification as WindowsTileNotification; if (winTileNot != null && !string.IsNullOrEmpty(winTileNot.NotificationTag)) { request.Headers.Add("X-WNS-Tag", winTileNot.NotificationTag); // TILE only } } if (winNotification.TimeToLive.HasValue) { request.Headers.Add("X-WNS-TTL", winNotification.TimeToLive.Value.ToString()); //Time to live in seconds } //Microsoft recommends we disable expect-100 to improve latency request.ServicePoint.Expect100Continue = false; var payload = winNotification.PayloadToString(); var data = Encoding.UTF8.GetBytes(payload); request.ContentLength = data.Length; using (var rs = request.GetRequestStream()) rs.Write(data, 0, data.Length); try { request.BeginGetResponse(new AsyncCallback(getResponseCallback), new object[] { request, winNotification, callback }); } catch (WebException wex) { //Handle different httpstatuses var status = ParseStatus(wex.Response as HttpWebResponse, winNotification); HandleStatus(status, callback); } }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { Interlocked.Increment(ref _trackedNotificationCount); var appleNotification = notification as AppleNotification; if (appleNotification == null) { throw new ArgumentException("Notification was not an AppleNotification", "notification"); } Exception failure; byte[] notificationData; if (!TryGetNotificationData(appleNotification, out notificationData, out failure)) { Interlocked.Decrement(ref _trackedNotificationCount); if (callback != null) { callback(this, new SendNotificationResult(notification, false, failure)); } return; } try { EnsureConnected(); lock (_sendLock) { PollConnection(); Log.Debug("ApplePushChannel instance {0}: Sending notification {1}", _channelInstanceId, appleNotification.Identifier); _networkStream.Write(notificationData, 0, notificationData.Length); _networkStream.Flush(); _sentNotifications.Add(new SentNotification(appleNotification) { Callback = callback }); } } catch (Exception exception) { Disconnect(); Log.Error("Exception during APNS Send with channel {2}: {0} -> {1}", appleNotification.Identifier, exception, _channelInstanceId); // If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref _trackedNotificationCount); if (callback != null) { callback(this, new SendNotificationResult(notification, true, exception)); } } }
void HandleStatus(SendNotificationCallbackDelegate callback, WindowsPhoneMessageStatus status, WindowsPhoneNotification notification = null) { if (callback == null) { return; } if (status.SubscriptionStatus == WPSubscriptionStatus.Expired) { callback(this, new SendNotificationResult(notification, false, new Exception("Device Subscription Expired")) { IsSubscriptionExpired = true, OldSubscriptionId = notification != null ? notification.EndPointUrl : null, SubscriptionExpiryUtc = DateTime.UtcNow }); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Received) { callback(this, new SendNotificationResult(notification)); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Suppressed) { callback(this, new SendNotificationResult(notification, suppressed: true)); return; } if (status.HttpStatus == HttpStatusCode.OK && status.NotificationStatus == WPNotificationStatus.Dropped) { callback(this, new SendNotificationResult(notification)); return; } // Disconnected Device: he cloud service should continue sending notifications as usual even though those notifications // are dropped because when the device returns to Connected status this ensures the notification flow continues to the device. if (status.HttpStatus == HttpStatusCode.PreconditionFailed && status.NotificationStatus == WPNotificationStatus.Dropped) { callback(this, new SendNotificationResult(notification, suppressed: true)); return; } // This error occurs when an unauthenticated cloud service has reached the per-day throttling limit for a subscription, // or when a cloud service (authenticated or unauthenticated) has sent too many notifications per second. if (status.HttpStatus == HttpStatusCode.NotAcceptable && status.NotificationStatus == WPNotificationStatus.Dropped) { callback(this, new SendNotificationResult(notification, error: new WindowsPhoneNotificationSendFailureException(status, "This error occurs when an unauthenticated cloud service has reached the per-day throttling limit for a subscription, or when a cloud service (authenticated or unauthenticated) has sent too many notifications per second. "))); return; } callback(this, new SendNotificationResult(status.Notification, false, new WindowsPhoneNotificationSendFailureException(status))); }
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback) { lock (sentLock) { Interlocked.Increment(ref trackedNotificationCount); var appleNotification = notification as AppleNotification; bool isOkToSend = true; byte[] notificationData = new byte[] {}; try { notificationData = appleNotification.ToBytes(); } catch (NotificationFailureException nfex) { //Bad notification format already isOkToSend = false; Interlocked.Decrement(ref trackedNotificationCount); Log.Info("After conversion - catchNotificationFailure {0} {0}", nfex, notification); if (callback != null) { callback(this, new SendNotificationResult(notification, false, nfex)); } } if (isOkToSend) { try { lock (connectLock) Connect(); lock (streamWriteLock) { bool stillConnected = client.Connected && client.Client.Poll(2500, SelectMode.SelectWrite) && networkStream.CanWrite; if (!stillConnected) { throw new ObjectDisposedException("Connection to APNS is not Writable"); } lock (sentLock) { Log.Info("Writing data to stream"); if (notificationData.Length > 45) { networkStream.Write(notificationData, 0, 45); networkStream.Write(notificationData, 45, notificationData.Length - 45); } else { networkStream.Write(notificationData, 0, notificationData.Length); } networkStream.Flush(); Log.Info("Stream Flushed"); sentNotifications.Add(new SentNotification(appleNotification) { Callback = callback }); } } } catch (ConnectionFailureException cex) { connected = false; //If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref trackedNotificationCount); Log.Error("Connection failure {0} - {1}", cex, notification); if (callback != null) { callback(this, new SendNotificationResult(notification, false, cex)); } } catch (Exception ex) { connected = false; //If this failed, we probably had a networking error, so let's requeue the notification Interlocked.Decrement(ref trackedNotificationCount); Log.Error("Connection failure (Exception) - {0} - {1}", ex, notification); if (callback != null) { callback(this, new SendNotificationResult(notification, true, ex)); } } } } }