示例#1
0
        /// <summary>
        /// 推送成功
        /// </summary>
        /// <param name="notification"></param>
        private void Broker_NotificationSucceeded(ApnsNotification notification)
        {
            try
            {
                if (notification.Tag != null)
                {
                    var result = (dynamic)notification.Tag;
                    if (result != null && result.BatchNo != null)
                    {
                        if (!result.BatchNo.Equals("0"))
                        {
                            var handler = PushSucceeded;
                            if (handler != null)
                            {
                                handler(this, result.BatchNo);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("回调失败:{0},{1}", ex, JsonConvert.SerializeObject(notification));
            }

#if DEBUG
            _log.DebugFormat("IOS消息推送成功:Token:{0}, Tag:{1}", notification.DeviceToken, notification.Tag);
#endif
        }
示例#2
0
文件: ApnsBroker.cs 项目: sunche/mccm
        /// <inheritdoc/>
        public async Task <NotificationResult> Send(ApnsNotification notification, string deviceToken, bool isVoip)
        {
            var hostUri = $"{apnsUri}{deviceToken}";
            var payload = notification.GetPayload();
            var counter = 0;

            NotificationResult result = NotificationResult.Successful();

            while (counter < 5)
            {
                HttpResponseMessage response = await SendRequest(isVoip, payload, hostUri);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(NotificationResult.Successful());
                }

                result = await GetErrorResult(response);

                if (result.Error.Code != NotificationErrorCode.ExpiredAccessToken)
                {
                    return(result);
                }

                RefreshToken(DateTimeOffset.Now, true);
                counter++;
            }

            return(result);
        }
        public void Send(NotificationPayload notification, IDevice device)
        {
            if (string.IsNullOrEmpty(device.Token))
            {
                return;
            }

            // Configuration (NOTE: .pfx can also be used here)
            ApnsConfiguration config           = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certificatePath, certificatePassword);
            IOSNotification   payload          = new IOSNotification(notification);
            ApnsNotification  apnsNotification = new ApnsNotification
            {
                DeviceToken = device.Token,
                Payload     = JObject.FromObject(payload)
            };

            Console.WriteLine(apnsNotification.ToString());

            ApnsServiceBroker apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.OnNotificationSucceeded += this.onSuccess;
            apnsBroker.OnNotificationFailed    += this.onFailure;

            apnsBroker.Start();
            apnsBroker.QueueNotification(apnsNotification);
            apnsBroker.Stop();
        }
示例#4
0
        private static void Events_OnNotificationFailed(ApnsNotification notification, AggregateExeption exeption)
        {
            exeption.Handle(Function, ex);
            // see what kind of exeption it was to further diagnose'
            if ((ex.GetType() == ApnsNotificationExeption))
            {
                object notificationExeption;
                ex;
                ApnsNotificationExeption;
                // ApnsNotificationExeption.ErrorStatusCode'
                // deal with the failed notification'
                object apnsNotification = notificationExeption.Notification;
                object statusCode = notificationExeption.ErrorStatusCode;
                // notificationExeption.Notification.DeviceToken'
                System.Diagnostics.Debug.Writeline(("Apple Notification Failed: ID="
                                + (notification.Identifier + (", Code="
                                + (statusCode + ("Token:"
                                + (notificationExeption.Notification.DeviceToken + "}")))))));
            }
            else
            {
                // inner exeption might hold more infirmation like an ApnsConnectionExeption'
                System.Diagnostics.Debug.WriteLine("Apple notification Failed for some unknown reason:       {ex.InnerExeption}");
            }

        }
 protected virtual void NofificationFailed(ApnsNotification notification, AggregateException exception)
 {
     if (OnNofificationFailed != null)
     {
         OnNofificationFailed.Invoke(notification, exception);
     }
 }
        public static void WriteSuccessLog(ApnsNotification notification)
        {
            if (!File.Exists(apnSuccessLogPath))
            {
                File.Create(apnSuccessLogPath).Dispose();
            }
            try
            {
                using (StreamWriter writer = File.AppendText(apnSuccessLogPath))
                {
                    writer.WriteLine("===========Start============= " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
                    writer.WriteLine($"Notification sent to Device with Token ID : {0}, Identifier : {1} at Time : {2} with Payload : {3}",
                                     notification.DeviceToken, notification.Identifier, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"), notification.Payload);
                    writer.WriteLine("===========End============= " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
                    writer.WriteLine(Environment.NewLine);

                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception e)
            {
                //Do not do anything
            }
        }
        private void OnNotificationFailed(ApnsNotification notification, AggregateException aggregateEx)
        {
            aggregateEx.Handle(ex =>
            {
                if (ex is ApnsNotificationException notificationException)
                {
                    var apnsNotification = notificationException.Notification;
                    var statusCode       = notificationException.ErrorStatusCode;
                    _logger.LogError(notificationException, "Apple Notification Failed: ID={0}, Code={1}, Token={2}, Payload={3}", apnsNotification.Identifier, statusCode, notification.DeviceToken, notification.Payload);

                    switch (statusCode)
                    {
                    case ApnsNotificationErrorStatusCode.InvalidTokenSize:
                    case ApnsNotificationErrorStatusCode.InvalidToken:
                        OnInvalidToken(this, new InvalidTokenEventArgs(notification.DeviceToken));
                        break;
                    }
                }
                else
                {
                    _logger.LogError(ex.InnerException, "Apple Notification Failed for some unknown reason, Token={0}, Payload={1}", notification.DeviceToken, notification.Payload);
                }

                return(true);
            });
        }
示例#8
0
        private void ApnsBroker_OnNotificationFailed(ApnsNotification notification, AggregateException exception)
        {
            exception.Handle(ex =>
            {
                // See what kind of exception it was to further diagnose
                if (ex is ApnsNotificationException)
                {
                    var notificationException = ex as ApnsNotificationException;

                    // Deal with the failed notification
                    var apnsNotification = notificationException.Notification;
                    var statusCode       = notificationException.ErrorStatusCode;

                    Debug.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                }
                else
                {
                    // Inner exception might hold more useful information like an ApnsConnectionException
                    Debug.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
                }

                // Mark it as handled
                return(true);
            });
        }
示例#9
0
        private void IOSPushNotificationFailed(ApnsNotification notification, AggregateException exception)
        {
            exception.Handle(ex =>
            {
                // See what kind of exception it was to further diagnose
                if (ex is ApnsNotificationException)
                {
                    var notificationException = (ApnsNotificationException)ex;

                    // Deal with the failed notification
                    var apnsNotification = notificationException.Notification;
                    var statusCode       = notificationException.ErrorStatusCode;

                    Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                    if (Convert.ToString(statusCode) == "InvalidToken")
                    {
                        DeleteExpiredSubscription(notification.DeviceToken);
                    }
                }
                else
                {
                    // Inner exception might hold more useful information like an ApnsConnectionException
                    Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
                }

                // Mark it as handled
                return(true);
            });
        }
示例#10
0
        /// <summary>
        /// 推送失败
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="aggregateEx"></param>
        private void Broker_NotificationFailed(ApnsNotification notification, AggregateException aggregateEx)
        {
#if DEBUG
            _log.DebugFormat("【iOS发送推送】失败 回调{0},{1}", notification.DeviceToken, aggregateEx.Message);
#endif
            //aggregateEx.Handle(ex =>
            //{
            //	var notificationException = ex as ApnsNotificationException;
            //	if (notificationException != null)
            //	{
            //		_log.Error($"IOS推送失败: Token:{notification.DeviceToken}, Tag: {notification.Tag};{Environment.NewLine}" +
            //                            $"Notification:{notificationException.Notification};{Environment.NewLine}" +
            //		           $"Exception:{aggregateEx}; StatusCode:{notificationException.ErrorStatusCode}");
            //	}
            //	else
            //	{
            //		// Inner exception might hold more useful information like an ApnsConnectionException
            //		_log.ErrorFormat("IOS推送失败:Exception:{0}", aggregateEx.InnerExceptions);
            //	}

            //	// Mark it as handled
            //	return true;
            //});

            aggregateEx.Handle(ex =>
            {
                _log.Error($"IOS推送失败: Token:{notification.DeviceToken}, Tag: {notification.Tag};{Environment.NewLine}" +
                           $"Exception:{ex.Message}; ");

                // Mark it as handled
                return(true);
            });

            //回调
            try
            {
                if (notification.Tag != null)
                {
                    var result = (dynamic)notification.Tag;
                    if (result != null && result.BatchNo != null)
                    {
                        if (!result.BatchNo.Equals("0"))
                        {
                            var handler = PushFailed;
                            if (handler != null)
                            {
                                handler(this, result.BatchNo);
                            }
                        }
                    }
                }
            }
            catch (Exception exs)
            {
                _log.ErrorFormat("回调失败:{0},{1}", exs, JsonConvert.SerializeObject(notification));
            }
#if DEBUG
            _log.DebugFormat("IOS消息推送失败:Notification:{0}", notification);
#endif
        }
        public void NotifyDevice(Device device, IEnumerable <Transaction> transactions)
        {
            if (device == null)
            {
                throw new NullReferenceException("device");
            }

            if (string.IsNullOrEmpty(device.Token))
            {
                throw new ArgumentException("device.token");
            }

            if (transactions == null || !transactions.Any())
            {
                return;
            }


            // Get transaction type, check if we have payload content for this type

            var type = transactions.First().Type;

            if (!_contents.ContainsKey(type))
            {
                return;
            }

            var content = _contents[type];


            // Make payload and notification

            var payload = new Payload
            {
                Sound = content.Sound,
                Badge = 1
            };

            if (!string.IsNullOrEmpty(content.Body))
            {
                payload.Body = content.Body;
            }

            if (!string.IsNullOrEmpty(content.Title))
            {
                payload.Title = content.Title;
            }

            var notification = new ApnsNotification
            {
                DeviceToken = device.Token,
                Payload     = payload.ToJObject()
            };


            // Send it

            _broker.QueueNotification(notification);
        }
示例#12
0
        static void Main(string[] args)
        {
            Console.WriteLine($"PushVoIP");
            var certificate          = AppDomain.CurrentDomain.BaseDirectory + @"you certificate.p12";
            ApnsConfiguration config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, File.ReadAllBytes(certificate), "you certificate password", false);
            var apnsBroker           = new ApnsServiceBroker(config);

            //推送异常
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                aggregateEx.Handle(ex =>
                {
                    //判断例外,进行诊断
                    if (ex is ApnsNotificationException)
                    {
                        var notificationException = (ApnsNotificationException)ex;
                        //处理失败的通知
                        var apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;
                        Console.WriteLine(
                            $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}" +
                            notification.DeviceToken);
                    }
                    else
                    {
                        Console.WriteLine($"pple Notification Failed for some unknown reason : {ex}------{notification.DeviceToken}");
                    }
                    // 标记为处理
                    return(true);
                });
            };
            JObject obj = new JObject();

            obj.Add("content-availabl", 1);
            obj.Add("badge", 1);
            obj.Add("alert", "apple voip test !");
            obj.Add("sound", "default");
            var voIpToken = "you voip token";
            var payload   = new JObject();

            payload.Add("aps", obj);
            var apns = new ApnsNotification()
            {
                DeviceToken = voIpToken,
                Payload     = payload
            };

            //推送成功
            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                //apnsBroker.QueueNotification(apns);
                Console.WriteLine("Apple Notification Sent ! " + notification.DeviceToken);
            };
            //启动代理
            apnsBroker.Start();
            apnsBroker.QueueNotification(apns);

            Console.ReadKey();
        }
示例#13
0
        void apnsPush_OnNotificationFailed(ApnsNotification notification, AggregateException exception)
        {
            ContadorNoEnviados++;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("================================================================================");
            sb.AppendLine("Notificacion: " + notification.ToString());
            sb.AppendLine("Error: " + exception.Message);

            EscribirEnLog(sb.ToString());
        }
 /// <summary>
 /// Notification Sent Event Handler
 /// </summary>
 /// <param name="notification"></param>
 private void NotificationSent(ApnsNotification notification)
 {
     try
     {
         StringBuilder traceLog = new StringBuilder();
         traceLog.Append("Sent: -> " + notification);
         LogManager.LogManagerInstance.WriteTraceLog(traceLog);
     }
     catch (Exception ex)
     {
         LogManager.LogManagerInstance.WriteErrorLog(ex);
         return;
     }
 }
示例#15
0
        void apnsPush_OnNotificationSucceeded(ApnsNotification notification)
        {
            string token = "";

            try
            {
                token = notification.DeviceToken;
                TokensSended.Add(token);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            ContadorEnviados++;
        }
示例#16
0
        private void button1_Click(object sender, EventArgs e)
        {
            //service.Send(new List<NeeoUser>(), new NotificationModel(){ NType = NotificationType.Im, Alert = "zohaib says: hello", Badge = 6});
            var payload = "{";

            payload += "\"aps\":{";
            payload += "\"alert\":\"hello world\",";
            //payload += "\"sound\":\"" + notificationModel.IMTone.GetDescription() + "\",";
            payload += "\"sound\":\"imTone1.m4r\",";
            payload += "\"badge\" : 7";
            payload += "},";
            payload += "}";
            var notification = new ApnsNotification("cee0ffae7a0ad0ee3a2b70092c3ba3d29be0be39c42b719d146681c11710b9a9", JObject.Parse(payload));

            _apnsServiceBroker.QueueNotification(notification);
        }
        /// <summary>
        /// Notification Failed Event Handler
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="exception"></param>
        private void NotificationFailed(ApnsNotification notification, AggregateException exception)
        {
            StringBuilder traceLog = new StringBuilder();

            try
            {
                traceLog.AppendLine("Failure: " + exception.Message + " -> " + notification);
            }
            catch (Exception ex)
            {
                LogManager.LogManagerInstance.WriteErrorLog(ex);
                return;
            }
            finally
            {
                LogManager.LogManagerInstance.WriteTraceLog(traceLog);
            }
        }
示例#18
0
        public override void Send(List <NeeoUser> receiverList, NotificationModel notificationModel)
        {
            if (receiverList == null || receiverList.Count == 0)
            {
                LogManager.CurrentInstance.ErrorLogger.LogError(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
                    "receiverList is either null or empty.");
                return;
            }

            Parallel.ForEach(receiverList, (item) =>
            {
                Dictionary <string, object> payload;
                payload = new ApnsPayload().Create(item, notificationModel);

                var notification = new ApnsNotification(item.DeviceToken, JObject.FromObject(payload));

                _apnsServiceBroker.QueueNotification(notification);
            });
        }
示例#19
0
        public void ApnsSerialization()
        {
            var notification = new ApnsNotification
            {
                Payload = new ApnsPayload
                {
                    Alert = new ApnsNotificationAlert
                    {
                        BodyLocalizationKey  = "GAME_PLAY_REQUEST_FORMAT",
                        BodyLocalizationArgs = new string[] { "Jenna", "Frank" }
                    },
                    Sound = "chime.aiff"
                }
            };
            var expected = "{\"aps\":{\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]},\"sound\":\"chime.aiff\"}}";

            var serialized = JsonConvert.SerializeObject(notification, Formatting.None, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            Assert.Equal(expected, serialized);
        }
        protected void Apns_OnNotificationFailed(ApnsNotification notification, AggregateException exception)
        {
            Log.ErrorFormat("APNS failed {0}: {1}", notification.Tag, exception);
            var statusMessage = exception == null ? "Unknown error" : exception.Flatten().ToString();

            TrackEvent(notification.Tag, TrackingStatus.Error, statusMessage);

            if (exception != null && exception.InnerExceptions != null)
            {
                foreach (var e in exception.InnerExceptions.OfType <DeviceSubscriptionExpiredException>())
                {
                    ProcessExpiredToken(notification.Tag as string, e);
                }

                var ex = exception.InnerExceptions.FirstOrDefault(e => e is ApnsNotificationException);
                if (ex != null && ((ApnsNotificationException)ex).ErrorStatusCode == ApnsNotificationErrorStatusCode.InvalidToken)
                {
                    Log.Debug("Invalid token detected, do cleanig up");
                    ProcessInvalidToken(notification.Tag as string, ex);
                    TrackEvent(notification.Tag, TrackingStatus.Ignored, "Invalid APNS token, subscription dropped");
                }
            }
        }
        public void Send(NotificationPayload notification, IEnumerable <IDevice> devices)
        {
            ApnsConfiguration config     = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certificatePath, certificatePassword);
            IOSNotification   payload    = new IOSNotification(notification);
            ApnsServiceBroker apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.OnNotificationSucceeded += this.onSuccess;
            apnsBroker.OnNotificationFailed    += this.onFailure;

            apnsBroker.Start();
            ApnsNotification apnsNotification = new ApnsNotification
            {
                Payload = JObject.FromObject(payload)
            };

            foreach (var device in devices)
            {
                apnsNotification.DeviceToken = device.Token;
                Console.WriteLine(apnsNotification.ToString());
                apnsBroker.QueueNotification(apnsNotification);
            }

            apnsBroker.Stop();
        }
        private void SendAppleNotification(string alert, IDictionary <string, object> data, string deviceToken)
        {
            // build the payload, following the documentation
            // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html

            IDictionary <string, object> aps = new Dictionary <string, object>();

            aps.Add("alert", alert);
            aps.Add("sound", "default");
            IDictionary <string, object> payload = new Dictionary <string, object>();

            payload.Add("aps", aps);

            foreach (var kvp in data)
            {
                payload.Add(kvp.Key, kvp.Value);
            }

            JObject x = JObject.FromObject(payload);

            var notification = new ApnsNotification(deviceToken, x);

            _apps[iOSApp].Apns.QueueNotification(notification);
        }
        public override object Create(Model.NotificationModel notificationModel)
        {
            var notification = new ApnsNotification();

            switch (notificationModel.NType)
            {
            case NotificationType.Im:
                break;

            case NotificationType.IncomingSipCall:
                break;

            case NotificationType.Mcr:
                break;

            case NotificationType.GInvite:
                break;

            case NotificationType.GIm:
                break;
            }

            return(notification);
        }
示例#24
0
 private void ApnsServiceBrokerNotificationSucceeded(ApnsNotification notification)
 {
 }
示例#25
0
 private void ApnsServiceBrokeNotificationFailed(ApnsNotification notification, AggregateException exception)
 {
     Logger.Error(exception, $"Failed to deliver APNS notification: {exception.Message}");
 }
示例#26
0
        public static ResponseEntity ApnsSend(DbEntity record)
        {
            const string apns = "[APNS]";

#if DEBUG
            Console.WriteLine($"Вошли в метод ApnsSend");
#endif
            ApnsConfiguration config     = null;
            ApnsServiceBroker apnsBroker = null;

            try
            {
                config = ApnsConfigBuilder.Config(ApnsConfiguration.ApnsServerEnvironment.Production);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{apns} Возникла критическая ошибка. "
                                  + $"Отправка сообщений на сервер {apns} отменена "
                                  + Environment.NewLine
                                  + $"{ex.Message}");
                return(null);
            }

            // Create a new broker

            ResponseEntity pushResult = new ResponseEntity();
            apnsBroker = new ApnsServiceBroker(config);
            var apnsNotification = new ApnsNotification();

            try
            {
                // Wire up events
                apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
#if DEBUG
                    Console.WriteLine($"Сервер APNS ответил ошибкой. Попытка определить тип ошибки");
#endif
                    aggregateEx.Handle(ex =>
                    {
                        // See what kind of exception it was to further diagnose
                        if (ex is ApnsNotificationException)
                        {
                            var notificationException = (ApnsNotificationException)ex;
                            // Deal with the failed notification

                            var apnsNotificationWithException = notificationException.Notification;
                            var statusCode = notificationException.ErrorStatusCode;
                            string desc    = $"{apns} Notification Failed: Message ID = [{record.Message_id}], Code = [{statusCode}]";
                            Console.WriteLine(desc);

                            pushResult = BasePush.GetResponseEntity(record, notificationException);
                        }
                        else if (ex is ApnsConnectionException)
                        {
                            var connectionException = (ApnsConnectionException)ex;
                            var innerException      = connectionException.InnerException;
                            var message             = connectionException.Message;
                            string desc             = $"{apns} Notification Failed. Connection failure: \nMessage = [{message}], \nInnerException = [{innerException}], \nMessage Id = [{record.Message_id}]";
                            Console.WriteLine(desc);

                            pushResult = BasePush.GetResponseEntity(record, connectionException);
                        }
                        else
                        {
                            var otherException = ex;
                            // Inner exception might hold more useful information like an ApnsConnectionException
                            string desc = $"{apns} Notification Failed for some unknown reason : \nMessage = [{otherException.Message}], \nInnerException = [{otherException.InnerException}], \nMessage Id = [{record.Message_id}]";
                            Console.WriteLine(desc);

                            pushResult = BasePush.GetResponseEntity(record, otherException);
                        }
                        // Mark it as handled
                        return(true);                           //	обязательное условие такой конструкции (выдать bool)
                    });
                };
                apnsBroker.OnNotificationSucceeded += (notification) =>
                {
#if DEBUG
                    var desc = "Сообщение отправлено на сервер APNS";
                    //responseMessage = desc;
                    Console.WriteLine(desc);
#endif
                    Console.WriteLine($"{apns} Сообщение [{record.Message_id}] успешно отправлено");
                    pushResult = BasePush.GetResponseEntity(record);
                };
                // Start the broker
                apnsBroker.Start();

#if DEBUG
                Console.WriteLine($"Брокер отправки сообщений запущен");
#endif

                var jsonString      = $"{{\"aps\":{{\"alert\":\"{record.Message_text}\"}}}}";
                var apns_expiration = DateTime.UtcNow.AddSeconds(record.Msg_Ttl);
                apnsNotification = new ApnsNotification
                {
                    DeviceToken = record.Push_id,
                    Payload     = JObject.Parse(jsonString),
                    Expiration  = apns_expiration
                };
                apnsBroker.QueueNotification(apnsNotification);

                // Stop the broker, wait for it to finish
                // This isn't done after every message, but after you're
                // done with the broker
#if DEBUG
                Console.WriteLine($"Останавливаем брокер - это действие выполнит отправку сообщения");
#endif
                apnsBroker.Stop();

                return(pushResult);                 //	выдаём наружу результат отправки пуша
            }
            catch (Exception ex)
            {
                Console.WriteLine("{apns} ERROR: " + ex.Message);

                return(BasePush.GetResponseEntity(record, ex));
            }
        }
 private void OnApnsNotificationSucceeded(ApnsNotification notification)
 {
     _logger.LogMessage("Sent: " + (notification.Payload != null ? notification.Payload.ToString() : String.Empty));
 }
        private void EnsureApnsStarted()
        {
            if (_appleStarted)
            {
                return;
            }


            try
            {
                _appleStarted = true;
                ApnsConfiguration configuration;

#if DEBUG
                // looks like for now we should specify production even in debug, using sandbox messages are not coming through.
                const ApnsConfiguration.ApnsServerEnvironment environment = ApnsConfiguration.ApnsServerEnvironment.Production;
                var certificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                   _serverSettings.ServerData.APNS.DevelopmentCertificatePath);
#else
                const ApnsConfiguration.ApnsServerEnvironment environment = ApnsConfiguration.ApnsServerEnvironment.Production;
                var certificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                   _serverSettings.ServerData.APNS.ProductionCertificatePath);
#endif

                // Apple settings placed next for development purpose. (Crashing the method when certificate is missing.)
                var appleCert = File.ReadAllBytes(certificatePath);

                configuration = new ApnsConfiguration(environment, appleCert, _serverSettings.ServerData.APNS.CertificatePassword);
                _apps.Add(iOSApp, new AppPushBrokers {
                    Apns = new ApnsServiceBroker(configuration)
                });

                _apps[iOSApp].Apns.OnNotificationSucceeded += OnApnsNotificationSucceeded;
                _apps[iOSApp].Apns.OnNotificationFailed    += (notification, aggregateEx) =>
                {
                    aggregateEx.Handle(ex =>
                    {
                        // See what kind of exception it was to further diagnose
                        if (ex is ApnsNotificationException)
                        {
                            var x = ex as ApnsNotificationException;

                            // Deal with the failed notification
                            ApnsNotification n = x.Notification;
                            string description = "Message: " + x.Message + " Data:" + x.Data.ToString();

                            _logger.LogMessage(string.Format("Notification Failed: ID={0}, Desc={1}", n.Identifier, description));
                        }
                        else if (ex is ApnsConnectionException)
                        {
                            var x = ex as ApnsConnectionException;
                            string description = "Message: " + x.Message + " Data:" + x.Data.ToString();

                            _logger.LogMessage(string.Format("Notification Failed: Connection exception, Desc={0}", description));
                        }
                        else if (ex is DeviceSubscriptionExpiredException)
                        {
                            LogDeviceSubscriptionExpiredException((DeviceSubscriptionExpiredException)ex);
                        }
                        else if (ex is RetryAfterException)
                        {
                            LogRetryAfterException((RetryAfterException)ex);
                        }
                        else
                        {
                            _logger.LogMessage("Notification Failed for some (Unknown Reason)");
                        }


                        // Mark it as handled
                        return(true);
                    });
                };

                _apps[iOSApp].Apns.Start();
            }
            catch (Exception e)
            {
                _logger.LogError(e);
            }
        }
 protected void Apns_OnNotificationSucceeded(ApnsNotification notification)
 {
     Log.DebugFormatExt("APNS success {0}", notification.Tag);
     TrackEvent(notification.Tag, TrackingStatus.Delivered, "Successfully accepted by Apple");
 }
示例#30
0
 public WrappedApnsNotification(ApnsNotification notification, string appId)
 {
     Notification = notification;
     AppId        = appId;
 }