Example #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            ApnsConfiguration ApnsConfig = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, "iOSDevicesToken\\production.p12", "00000");  //production  //development
            var broker = new ApnsServiceBroker(ApnsConfig);
            broker.OnNotificationFailed += (notification, exception) =>
            {
                failed++;
                //listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] -> " + "發送失敗." + exception.Message);
            };
            broker.OnNotificationSucceeded += (notification) =>
            {
                succeeded++;
                //listBox1.Items.Add("[" + DateTime.Now.ToString("HH:mm:ss") + "] -> " + "發送成功.");
            };
            broker.Start();

            attempted++;
            broker.QueueNotification(new ApnsNotification
            {
                DeviceToken = "fd531fb09d0fe0554105e7e8101e15a1ec7006ad43bd57c4cedbe99d0896d31b",
                Payload = JObject.Parse("{ \"aps\" : { \"alert\" : \"Hello LeXin Push Test!\", \"badge\" : 1, \"sound\" : \"default\" } }")
            });

            broker.Stop();
        }
Example #2
0
        public void APNS_Send_Single ()
        {
            var succeeded = 0;
            var failed = 0;
            var attempted = 0;

            var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox, Settings.Instance.ApnsCertificateFile, Settings.Instance.ApnsCertificatePassword);
            var broker = new ApnsServiceBroker (config);
            broker.OnNotificationFailed += (notification, exception) => {
                failed++;
            };
            broker.OnNotificationSucceeded += (notification) => {
                succeeded++;
            };
            broker.Start ();

            foreach (var dt in Settings.Instance.ApnsDeviceTokens) {
                attempted++;
                broker.QueueNotification (new ApnsNotification {
                    DeviceToken = dt,
                    Payload = JObject.Parse ("{ \"aps\" : { \"alert\" : \"Hello PushSharp!\" } }")
                });
            }

            broker.Stop ();

            Assert.AreEqual (attempted, succeeded);
            Assert.AreEqual (0, failed);
        }
        public IosPushMessageSender(ApplicationType? appType)
        {
            if(appType == ApplicationType.Tablet)
                config = new ApnsConfiguration(PushSharp.Apple.ApnsConfiguration.ApnsServerEnvironment.Production,
                    Options.ApnsCertificateFileTablet, Options.ApnsCertificatePasswordTablet);
            else
                config = new ApnsConfiguration(PushSharp.Apple.ApnsConfiguration.ApnsServerEnvironment.Production,
                    Options.ApnsCertificateFileMobile, Options.ApnsCertificatePasswordMobile);

            SetUpFeedbackServiceTimer(Options.APNSFeedbackServiceRunDelay);

            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;

                        logger.Error(string.Format("Apple Notification Failed: ID={0}, Code={1}, Token ={2}", apnsNotification.Identifier, statusCode, notification.DeviceToken));
                        System.Diagnostics.Debug.WriteLine(string.Format("Apple Notification Failed: ID={0}, Code={1}, Token ={2}", apnsNotification.Identifier, statusCode, notification.DeviceToken));
                    }
                    else
                    {
                        logger.Error(string.Format("Apple Notification Failed for some unknown reason : {0}, Token = {1}", ex.InnerException, notification.DeviceToken));
                        System.Diagnostics.Debug.WriteLine(string.Format("Apple Notification Failed for some unknown reason : {0}, Token = {1}", ex.InnerException, notification.DeviceToken));
                    }

                    notificationService.Unsubscribe(notification.DeviceToken, userId);

                    return true;
                });
            };

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                logger.Info("Notification Successfully Sent to: " + notification.DeviceToken);
                System.Diagnostics.Debug.WriteLine("Notification Successfully Sent to: " + notification.DeviceToken);
            };

            apnsBroker.Start();
        }
Example #4
0
        public async Task Should_Fail_Connect ()
        {
            int count = 2;
            long failed = 0;
            long success = 0;

            var server = new TestApnsServer ();
            #pragma warning disable 4014
            server.Start ();
            #pragma warning restore 4014

            var config = new ApnsConfiguration ("invalidhost", 2195);
            var broker = new ApnsServiceBroker (config);
            broker.OnNotificationFailed += (notification, exception) => {
                Interlocked.Increment (ref failed);
                Console.WriteLine ("Failed: " + notification.Identifier);
            };
            broker.OnNotificationSucceeded += (notification) => Interlocked.Increment (ref success);
            broker.Start ();

            for (int i = 0; i < count; i++) {
                broker.QueueNotification (new ApnsNotification {
                    DeviceToken = (i + 1).ToString ().PadLeft (64, '0'),
                    Payload = JObject.Parse (@"{""aps"":{""badge"":" + (i + 1) + "}}")
                });
            }

            broker.Stop ();
            await server.Stop ().ConfigureAwait (false);

            var actualFailed = failed;
            var actualSuccess = success;

            Console.WriteLine ("Success: {0}, Failed: {1}", actualSuccess, actualFailed);

            Assert.AreEqual (count, actualFailed);//, "Expected Failed Count not met");
            Assert.AreEqual (0, actualSuccess);//, "Expected Success Count not met");
        }
Example #5
0
        /// <summary>
        /// Sends the push.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns> Result message </returns>
        public string SendVOIPNotification(PushNotificationModel model)
        {
            string resultmessage = string.Empty;

            // Create a new broker
            ApnsServiceBroker apnsBroker = new ApnsServiceBroker(this._voipConfig);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        ////Delete invalid token
                        if (statusCode == ApnsNotificationErrorStatusCode.InvalidToken)
                        {
                            this._logger.LogInformation($"Token deleted : {apnsNotification.DeviceToken}");
                        }

                        ////Console.WriteLine(
                        resultmessage = resultmessage +
                                        $"\r\nApple Notification Failed: ID={apnsNotification.DeviceToken}, Code={statusCode}";
                    }
                    else
                    {
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        ////Console.WriteLine(
                        resultmessage = resultmessage + $"\r\nApple Notification Failed for some unknown reason : {ex.InnerException}";
                    }

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

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                ////Console.WriteLine(
                resultmessage = resultmessage + "\r\nApple Notification Sent!";
            };

            // Start the broker
            apnsBroker.Start();

            foreach (var deviceToken in model.DeviceTokens)
            {
                var jdata = new JObject
                {
                    { "aps", new JObject
                      {
                          { "alert", model.Message },
                          { "content-available", 1 }
                      } }
                };

                // Queue a notification to send
                apnsBroker.QueueNotification(
                    new ApnsNotification()
                {
                    DeviceToken = deviceToken,
                    Payload     = jdata
                });
            }
            ;

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();

            return(resultmessage);
        }
Example #6
0
        private void InitApnsBroker(GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment)
        {
            if(string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificatePassword)
                || string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificateThumbprint))
            {
                return;
            }

            var apnsCertificate = GetCertificate(globalSettings.Push.ApnsCertificateThumbprint);
            if(apnsCertificate == null)
            {
                return;
            }

            var apnsConfig = new ApnsConfiguration(hostingEnvironment.IsProduction() ?
                ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                apnsCertificate.RawData, globalSettings.Push.ApnsCertificatePassword);

            _apnsBroker = new ApnsServiceBroker(apnsConfig);
            _apnsBroker.OnNotificationFailed += ApnsBroker_OnNotificationFailed;
            _apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                Debug.WriteLine("Apple Notification Sent!");
            };
            _apnsBroker.Start();

            var feedbackService = new FeedbackService(apnsConfig);
            feedbackService.FeedbackReceived += FeedbackService_FeedbackReceived;
            feedbackService.Check();
        }
        public void sendMessage(string BarCode, string token, string WineName, int StoreId)
        {
            try
            {
                var succeeded = 0;
                var failed    = 0;
                var attempted = 0;
                logger.Info("Sending notification for :" + BarCode);
                //var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox, Settings.Instance.ApnsCertificateFile, Settings.Instance.ApnsCertificatePassword);
                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, "Production2.p12", "Wineoutlet@99666");
                var broker = new ApnsServiceBroker(config);
                broker.ChangeScale(10);
                broker.OnNotificationFailed += (notification, exception) =>
                {
                    failed++;
                };
                broker.OnNotificationSucceeded += (notification) =>
                {
                    succeeded++;
                };
                broker.Start();
                string dt = token;       //"3b0d4407d7fdfb5b3c4c0f421004407d5787595b4dea0875a75db9de75d368a0";
                broker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = dt,
                    //Payload = JObject.Parse("{\"aps\":{ \"alert\" : \"You've just tasted a new wine\" },{\"title\":\"222\"}")
                    //Payload = JObject.Parse("{ \"aps\" : { \"alert\" : \"You've just tasted a new wine\" } }")
                    Payload = JObject.Parse("{ \"aps\" : { \"alert\" : \"You've just tasted " + WineName + ". Please review the wine.\" },\"barcode\":\"" + BarCode + "\",\"storeid\":\"" + StoreId + "\" }")
                });
                logger.Info("Notification sent");
                //foreach (var dt in Settings.Instance.ApnsDeviceTokens)
                //{
                //    attempted++;
                //    broker.QueueNotification(new ApnsNotification
                //    {
                //        DeviceToken = dt,
                //        Payload = JObject.Parse("{ \"aps\" : { \"alert\" : \"Hello PushSharp!\" } }")
                //    });
                //}

                broker.Stop();
            }
            catch (Exception ex)
            {
                string path    = ConfigurationManager.AppSettings["ErrorLog"];
                string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
                message += Environment.NewLine;
                message += "-----------------------------------------------------------";
                message += Environment.NewLine;
                message += string.Format("Message: {0}", ex.Message);
                message += Environment.NewLine;
                message += string.Format("StackTrace: {0}", ex.StackTrace);
                message += Environment.NewLine;
                message += string.Format("Source: {0}", ex.Source);
                message += Environment.NewLine;
                message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
                message += Environment.NewLine;
                message += "-----------------------------------------------------------";
                message += Environment.NewLine;
                System.IO.Directory.CreateDirectory(path);
                using (StreamWriter writer = new StreamWriter(path + "Error.txt", true))
                {
                    writer.WriteLine(message);
                    writer.Close();
                }
            }
        }
Example #8
0
        public static void Main(string[] args)
        {
            using (var db = new TransafeRxEntities())
            {
                try
                {
                    var deviceTokenUsers = db.GetAllDeviceTokensWithUser().ToList();

                    //var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                    //Shared.Properties.Resources.TransafeRx_DEV_PUSH, Shared.Properties.Settings.Default.ApplePushPW);
                    var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
                                                       Shared.Properties.Resources.TransafeRx_PROD_PUSH, Shared.Properties.Settings.Default.ApplePushPW);

                    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}");
                            }
                            else
                            {
                                //Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
                            }

                            return(true);
                        });
                    };

                    apnsBroker.OnNotificationSucceeded += (notification) =>
                    {
                        Console.WriteLine("Apple Notification Sent!");
                    };

                    apnsBroker.Start();

                    foreach (var user in deviceTokenUsers)
                    {
                        var notifications = db.GetAllUserNotifications(user.UserId).SingleOrDefault();

                        if (!string.IsNullOrEmpty(user.Token))
                        {
                            //blood pressure notification
                            if (notifications != null)
                            {
                                if (notifications.BpNotificationTypeId != null)
                                {
                                    if (notifications.BpDaysSinceLastNotification.HasValue)
                                    {
                                        if (notifications.BpDaysSinceLastReading.HasValue)
                                        {
                                            if (notifications.BpDaysSinceLastReading > notifications.BpNotificationDays && notifications.BpDaysSinceLastNotification >= notifications.BpNotificationDays)
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Pressure Reminder\",\"body\":\"" + "Time to take your Blood Pressure!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 1, user.TokenId);
                                            }
                                        }
                                        else
                                        {
                                            apnsBroker.QueueNotification(new ApnsNotification
                                            {
                                                DeviceToken = user.Token,
                                                Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Pressure Reminder\",\"body\":\"" + "Time to take your Blood Pressure!" + "\"}}}")
                                            });
                                            db.AddNotificationMessage(user.UserId, 1, user.TokenId);
                                        }
                                    }
                                    else
                                    {
                                        if (notifications.BpNotificationDays.HasValue)
                                        {
                                            if (notifications.BpDaysSinceLastReading.HasValue)
                                            {
                                                if (notifications.BpDaysSinceLastReading > notifications.BpNotificationDays)
                                                {
                                                    apnsBroker.QueueNotification(new ApnsNotification
                                                    {
                                                        DeviceToken = user.Token,
                                                        Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Pressure Reminder\",\"body\":\"" + "Time to take your Blood Pressure!" + "\"}}}")
                                                    });
                                                    db.AddNotificationMessage(user.UserId, 1, user.TokenId);
                                                }
                                            }
                                            else
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Pressure Reminder\",\"body\":\"" + "Time to take your Blood Pressure!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 1, user.TokenId);
                                            }
                                        }
                                    }
                                }
                            }
                            //blood glucose notification
                            if (notifications != null)
                            {
                                if (notifications.BgNotificationTypeId != null)
                                {
                                    if (notifications.BgDaysSinceLastNotification.HasValue)
                                    {
                                        if (notifications.BgDaysSinceLastReading.HasValue)
                                        {
                                            if (notifications.BgDaysSinceLastReading > notifications.BgNotificationDays && notifications.BgDaysSinceLastNotification >= notifications.BgNotificationDays)
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Glucose Reminder\",\"body\":\"" + "Time to take your Blood Glucose!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 2, user.TokenId);
                                            }
                                        }
                                        else
                                        {
                                            apnsBroker.QueueNotification(new ApnsNotification
                                            {
                                                DeviceToken = user.Token,
                                                Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Glucose Reminder\",\"body\":\"" + "Time to take your Blood Glucose!" + "\"}}}")
                                            });
                                            db.AddNotificationMessage(user.UserId, 2, user.TokenId);
                                        }
                                    }
                                    else
                                    {
                                        if (notifications.BgNotificationDays.HasValue)
                                        {
                                            if (notifications.BgDaysSinceLastReading.HasValue)
                                            {
                                                if (notifications.BgDaysSinceLastReading > notifications.BgNotificationDays)
                                                {
                                                    apnsBroker.QueueNotification(new ApnsNotification
                                                    {
                                                        DeviceToken = user.Token,
                                                        Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Glucose Reminder\",\"body\":\"" + "Time to take your Blood Glucose!" + "\"}}}")
                                                    });
                                                    db.AddNotificationMessage(user.UserId, 2, user.TokenId);
                                                }
                                            }
                                            else
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Blood Glucose Reminder\",\"body\":\"" + "Time to take your Blood Glucose!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 2, user.TokenId);
                                            }
                                        }
                                    }
                                }
                            }
                            //survey notification
                            if (notifications != null)
                            {
                                if (notifications.SnNotificationTypeId != null)
                                {
                                    if (notifications.SnDaysSinceLastNotification.HasValue)
                                    {
                                        if (notifications.SnDaysSinceLastReading.HasValue)
                                        {
                                            if (notifications.SnDaysSinceLastReading > notifications.SnNotificationDays && notifications.SnDaysSinceLastNotification >= notifications.SnNotificationDays)
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Symptom Survey Reminder\",\"body\":\"" + "Time to take the Symptom Survey!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 3, user.TokenId);
                                            }
                                        }
                                        else
                                        {
                                            apnsBroker.QueueNotification(new ApnsNotification
                                            {
                                                DeviceToken = user.Token,
                                                Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Symptom Survey Reminder\",\"body\":\"" + "Time to take the Symptom Survey!" + "\"}}}")
                                            });
                                            db.AddNotificationMessage(user.UserId, 3, user.TokenId);
                                        }
                                    }
                                    else
                                    {
                                        if (notifications.SnNotificationDays.HasValue)
                                        {
                                            if (notifications.SnDaysSinceLastReading.HasValue)
                                            {
                                                if (notifications.SnDaysSinceLastReading > notifications.SnNotificationDays)
                                                {
                                                    apnsBroker.QueueNotification(new ApnsNotification
                                                    {
                                                        DeviceToken = user.Token,
                                                        Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Symptom Survey Reminder\",\"body\":\"" + "Time to take the Symptom Survey!" + "\"}}}")
                                                    });
                                                    db.AddNotificationMessage(user.UserId, 3, user.TokenId);
                                                }
                                            }
                                            else
                                            {
                                                apnsBroker.QueueNotification(new ApnsNotification
                                                {
                                                    DeviceToken = user.Token,
                                                    Payload     = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"alarm\",\"alert\":{\"title\":\"Symptom Survey Reminder\",\"body\":\"" + "Time to take the Symptom Survey!" + "\"}}}")
                                                });
                                                db.AddNotificationMessage(user.UserId, 3, user.TokenId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    apnsBroker.Stop();
                }
                catch (Exception e)
                {
                    SmtpClient  client  = new SmtpClient(ConfigurationManager.AppSettings["SMTP"]);
                    MailAddress from    = new MailAddress("*****@*****.**");
                    MailMessage message = new MailMessage(from, to);
                    message.Body  = "An error has occured in TransafeRx User Notification Service.  Please see below for details.\r\n";
                    message.Body += "Stack Trace: " + e.StackTrace + "\r\n";

                    message.Subject = "TransafeRx User Notification Service Error Report";
                    client.Send(message);

                    message.Dispose();
                }
            }
        }
Example #9
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));
            }
        }
Example #10
0
        private void QueueAppleNotifications(UserDeviceInfo lstSplit, string pMessage, ApnsServiceBroker push)
        {
            try
            {
                String jsonPayload = "{ \"aps\" : { \"alert\" : \"" + pMessage + "\",\"badge\" : 0 }}";

                _logger.Information("Inside QueueNotifications with message: " + pMessage);

                if (lstSplit.DeviceToken != null)
                {
                    if (lstSplit.DeviceToken.Length == 64)
                    {
                        _logger.Information("***INFO*** Queing notification for token :" + lstSplit.DeviceToken.ToString());
                        push.QueueNotification(new ApnsNotification()
                        {
                            DeviceToken = (lstSplit.DeviceToken),
                            Payload     = JObject.Parse(jsonPayload)
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("***Error***: " + this.GetType().Name + ", Method " + MethodBase.GetCurrentMethod().Name + "****** Error details :" + ex.Message);
                throw ex;
            }
        }
        private void SendIOSNotification(string httpPath, Broadcast broadcastModel)
        {
            try
            {
                string[] TokenIds = getIOSTokenId();
                //Get Certificate

                var certicatePath = (ConfigurationManager.AppSettings["ProdCertificate"]);
                // var appleCert = System.IO.File.ReadAllBytes(Server.MapPath("~/Files/APNS_PROD_Certificates.p12"));
                var appleCert = System.IO.File.ReadAllBytes(Server.MapPath(certicatePath));
                //var appleCert = System.IO.File.ReadAllBytes(Server.MapPath("~/Files/APNS_DEV_Certificates.p12"));
                // Configuration (NOTE: .pfx can also be used here)
                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "");

                // Create a new broker

                foreach (var deviceToken in TokenIds)
                {
                    var apnsBroker = new ApnsServiceBroker(config);

                    // Wire up events
                    apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                    {
                        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 apnsNotification = notificationException.Notification;
                                var statusCode       = notificationException.ErrorStatusCode;
                                string desc          = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                                //               Console.WriteLine(desc);
                                //lblStatus.Text = desc;
                                //return  new HttpStatusCodeResult(HttpStatusCode.OK);
                            }
                            else
                            {
                                string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                                // Inner exception might hold more useful information like an ApnsConnectionException
                                Console.WriteLine(desc);
                                //lblStatus.Text = desc;
                            }

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

                    apnsBroker.OnNotificationSucceeded += (notification) =>
                    {
                        //lblStatus.Text = "Apple Notification Sent successfully!";

                        var test = notification;
                    };

                    var fbs = new FeedbackService(config);
                    fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
                    {
                        // Remove the deviceToken from your database
                        // timestamp is the time the token was reported as expired
                    };

                    // Start Proccess
                    apnsBroker.Start();
                    var jsonObject = JObject.Parse("{\"aps\":{ \"sound\":\"default\",\"alert\":{\"body\":\"" + broadcastModel.Message + "\",\"title\":\"" + broadcastModel.Title + "\"},\"mutable-content\":1},\"media-url\":\"" + httpPath + "\"}");
                    //var jsonObject = "{\"data\":{\"body\":\"" + broadcastModel.Message + "\",\"message\":\"" + broadcastModel.Title + "\",\"url\":\"" + httpPath + "\"}}";
                    //var jsonObject = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (broadcastModel.Message + "\"}}")));
                    if (deviceToken != "")
                    {
                        apnsBroker.QueueNotification(new ApnsNotification
                        {
                            DeviceToken = deviceToken,
                            Payload     = jsonObject
                                          //Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
                        });
                    }

                    apnsBroker.Stop();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void SendAppleNotification(Message message)
        {
            var deviceTokens = new List <string>();

            //var devices = message.Recipients.Split(';');
            //foreach (var device in devices)
            //{
            //    if(!string.IsNullOrEmpty(device))
            //    {
            //        var deviceInfo = device.Split('_');
            //        var platform = deviceInfo[0];
            //        var deviceToken = deviceInfo[1];
            //        if (platform == "iOS")
            //        {
            //            deviceTokens.Add(deviceToken);
            //        }
            //    }
            //}

            deviceTokens.Add("b81dcb4df68bac383ff863d6845b68dbcc24989388b7a1986a33b2ea0264d42e");

            // Configuration (NOTE: .pfx can also be used here)

            // Sandbox
            //var file = new X509Certificate2(File.ReadAllBytes("baseeam_push_sandbox.p12"), "Ng11235813$",
            //    X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            //var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
            //    "baseeam_push_sandbox.p12", "Ng11235813$");

            // Production
            var file = new X509Certificate2(File.ReadAllBytes("baseeam_push_production.p12"), "Ng112358$",
                                            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
                                               "baseeam_push_production.p12", "Ng112358$");

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

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

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

            apnsBroker.OnNotificationSucceeded += (notification) => {
                logger.Info("Apple Notification Sent!");
            };

            // Start the broker
            apnsBroker.Start();

            foreach (var deviceToken in deviceTokens)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse("{ \"aps\" : { \"alert\" : \"" + message.Messages + "\", \"sound\": \"default\" } }")
                });
            }

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();
        }
Example #13
0
        public async Task Apns (int expectFailed, List<ApnsNotification> notifications, IEnumerable<ApnsResponseFilter> responseFilters, int batchSize = 1000, int scale = 1)
        {
            long success = 0;
            long failed = 0;

            var server = new TestApnsServer ();
            server.ResponseFilters.AddRange (responseFilters);

            // We don't want to await this, so we can start the server and listen without blocking
            #pragma warning disable 4014
            server.Start ();
            #pragma warning restore 4014

            var config = new ApnsConfiguration ("127.0.0.1", 2195) {
                InternalBatchSize = batchSize
            };


            var broker = new ApnsServiceBroker (config);
            broker.OnNotificationFailed += (notification, exception) => {
                Interlocked.Increment (ref failed);
            };
            broker.OnNotificationSucceeded += (notification) => Interlocked.Increment (ref success);

            broker.Start ();

            if (scale != 1)
                broker.ChangeScale (scale);

            var c = Log.StartCounter ();

            foreach (var n in notifications)
                broker.QueueNotification (n);

            broker.Stop ();

            c.StopAndLog ("Test Took {0} ms");

            await server.Stop ().ConfigureAwait (false);

            var expectedSuccess = notifications.Count - expectFailed;

            var actualFailed = failed;
            var actualSuccess = success;

            Console.WriteLine("EXPECT: Successful: {0}, Failed: {1}", expectedSuccess, expectFailed);
            Console.WriteLine("SERVER: Successful: {0}, Failed: {1}", server.Successful, server.Failed);
            Console.WriteLine("CLIENT: Successful: {0}, Failed: {1}", actualSuccess, actualFailed);

            Assert.AreEqual (expectFailed, actualFailed);
            Assert.AreEqual (expectedSuccess, actualSuccess);

            Assert.AreEqual (server.Failed, actualFailed);
            Assert.AreEqual (server.Successful, actualSuccess);
        }
Example #14
0
        /// ================== A P N S ==================
        public static void Send_APNS(string[] recieverIds, string title, string content)
        {
            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(APNSConfig);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

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

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

            apnsBroker.OnNotificationSucceeded += (notification) => {
                PushLog.Write("  Apple Notification Sent! : " + content);
            };

            // Start the broker
            apnsBroker.Start();


            foreach (var deviceToken in recieverIds)
            {
                if (string.IsNullOrEmpty(deviceToken))
                {
                    continue;
                }

                ///              ============ WITH ALERT
                ///             {
                ///                 "aps":{
                ///                     "alert":{
                ///                         "title":"Notification Title",
                ///                         "subtitle":"Notification Subtitle",
                ///                         "body":"This is the message body of the notification."
                ///                     },
                ///                     "badge":1
                ///                 }
                ///             }
                ///
                ///              ============ DATA ONLY
                ///             {
                ///                 "aps" : {
                ///                     "content-available" : 1
                ///                 },
                ///                 "TopicType" : "topictype",
                ///                 "TopicIDp" : "topicidp",
                ///                 "TopicIDp" : "topicidp",
                ///             }



                NotiPayloadData payloadData = new NotiPayloadData
                {
                    aps = new Aps
                    {
                        sound = "default",
                        alert = new Alert
                        {
                            title = title,
                            body  = content,
                        }
                    }
                };
                string payloadString = JsonConvert.SerializeObject(payloadData);


                PushLog.Write("PAYLOAD STRING 1 : \n" + payloadString);
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse(payloadString)
                });



                /// PAYLOAD STRING 2
                ///payloadString = "{\"aps\" : {\"content-available\" : 1}" +
                ///    ",\"TopicType\" : \"" + (int)topicType +
                ///    "\",\"TopicIDp\" : \"" + topicID.IdPrefix +
                ///    "\",\"TopicIDp\" : \"" + topicID.IdSurfix +
                ///    "\",}";

                ///CpT.LogTag("PAYLOAD STRING 2 : \n" + payloadString);
                ///apnsBroker.QueueNotification(new ApnsNotification
                ///{
                ///    DeviceToken = deviceToken,
                ///    Payload = JObject.Parse(payloadString)
                ///});
            }

            // Stop the broker, wait for it to finish This isn't done after every message, but after you're done with the broker
            apnsBroker.Stop();
        }
Example #15
0
        public static bool Notify(IEnumerable <string> registrationIds, List <string> error, NotificationModel model)
        {
            var succeed = false;

            var cert = System.Web.HttpContext.Current.Server.MapPath(WebConfigurationManager.AppSettings["CertFile"]);
            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               cert, " ");
            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            #region OnNotificationFailed
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

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

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

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                succeed = true;
            };

            // Start the broker
            apnsBroker.Start();

            foreach (var deviceToken in registrationIds)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken.Replace(" ", "").Replace("<", "").Replace(">", ""),
                    Payload     = JObject.FromObject(new IOSNotification
                    {
                        aps = model
                    })
                });
            }

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();

            return(succeed);
        }
Example #16
0
        public HttpResponseMessage Push(string TokenDispositivo, string Mensaje, int TipoDispositivo)
        {
            IOS_Ambiente            = ConfigurationManager.AppSettings["IOS_Ambiente"].ToString();
            IOS_PasswordCertificado = ConfigurationManager.AppSettings["IOS_PasswordCertificado"].ToString();
            Android_SenderId        = ConfigurationManager.AppSettings["Android_SenderId"].ToString();
            Android_ServerKey       = ConfigurationManager.AppSettings["Android_ServerKey"].ToString();
            string result = "";

            try
            {
                if (TipoDispositivo == 1)
                {
                    ///////////////////////////////// SECCION Android //////////////////////////////////////
                    var webAddr        = "https://fcm.googleapis.com/fcm/send";
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
                    httpWebRequest.ContentType = "application/json";
                    httpWebRequest.Headers.Add("Authorization:key=" + Android_ServerKey);
                    httpWebRequest.Headers.Add("Sender:id=" + Android_SenderId);
                    httpWebRequest.Method = "POST";
                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        string json = "{\"to\": \"" + TokenDispositivo + "\",\"data\": {\"message\": \"" + Mensaje + "\",}}";
                        streamWriter.Write(json);
                        streamWriter.Flush();
                    }

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        result = streamReader.ReadToEnd();
                    }

                    if (result.Contains("\"failure\":1"))
                    {
                        result = "ERROR:" + result;
                    }
                    else
                    {
                        result = "MENSAJE ENVIADO";
                    }
                }
                else if (TipoDispositivo == 2)
                {
                    ///////////////////////////////// SECCION iOS //////////////////////////////////////

                    string ruta = HttpContext.Current.Server.MapPath("~/Certificates/" + IOS_NombreCertificado);

                    var config     = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, ruta, IOS_PasswordCertificado);
                    var apnsBroker = new ApnsServiceBroker(config);


                    if (IOS_Ambiente == "1") //Desarrollo
                    {
                        apnsBroker = new ApnsServiceBroker(config);
                    }

                    if (IOS_Ambiente == "2") //Producción
                    {
                        apnsBroker = new ApnsServiceBroker(config);
                    }

                    apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                    {
                        result = "ERROR: " + aggregateEx.Message; //Console.WriteLine("Error");
                    };

                    apnsBroker.OnNotificationSucceeded += (notification) =>
                    {
                        result = "Mensaje enviado";  //Console.WriteLine("Sent");
                    };

                    apnsBroker.Start();

                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = TokenDispositivo,
                        Payload     = JObject.Parse("{\"aps\":{\"alert\":{\"title\":\"\",\"body\":\"" + Mensaje + "\"},\"badge\":-1,\"sound\":\"chime.aiff\"}}")
                    });

                    apnsBroker.Stop();

                    result = "Mensaje enviado";
                }
            }
            catch (Exception ex)
            {
                result = "ERROR: " + ex.Message;
            }
            return(Request.CreateResponse(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter));
        }
Example #17
0
        public static async void PushNotifications(string _title, string _mess, List <string> listDeviceToken, bool isApple)
        {
            try
            {
                string json = "";
                if (isApple)
                {
                    string certificates = "http://115.78.191.245/poins.wallet/Certificates2.p12";
                    byte[] appleCert    = new System.Net.WebClient().DownloadData(certificates);
                    var    config       = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "1234qwer");

                    var broker = new ApnsServiceBroker(config);
                    broker.OnNotificationSucceeded += Broker_OnNotificationSucceeded;
                    broker.OnNotificationFailed    += Broker_OnNotificationFailed;

                    var fbs = new FeedbackService(config);
                    fbs.FeedbackReceived += Fbs_FeedbackReceived;

                    broker.Start();
                    NotificationObject obj = new NotificationObject();
                    if (string.IsNullOrEmpty(_title))
                    {
                        obj.aps.alert = _mess;
                    }
                    else
                    {
                        obj.aps.alert = new { title = _title, body = _mess }
                    };

                    json = JsonConvert.SerializeObject(obj);
                    foreach (var item in listDeviceToken)
                    {
                        broker.QueueNotification(new ApnsNotification()
                        {
                            DeviceToken = item,   /* token of device to push */
                            Payload     = JObject.Parse(json)
                        });
                    }

                    broker.Stop();
                }
                else
                {
                    string SERVER_API_KEY = "AIzaSyCYBfpo0fH_3owQdmB2RfX1HgbG4vx3epM";
                    string SENDER_ID      = "29694662630";
                    //string senderKey = "29694662630";
                    //string apiKey = "AIzaSyAXGWom6HmfBm5iJVGP5G8InK7KxOmBeVY";
                    var config = new GcmConfiguration(SENDER_ID, SERVER_API_KEY, null);
                    config.GcmUrl = "https://fcm.googleapis.com/fcm/send";

                    var gcmBroker = new GcmServiceBroker(config);
                    gcmBroker.OnNotificationFailed    += GcmBroker_OnNotificationFailed;
                    gcmBroker.OnNotificationSucceeded += GcmBroker_OnNotificationSucceeded;

                    gcmBroker.Start();

                    foreach (var item in listDeviceToken)
                    {
                        gcmBroker.QueueNotification(new GcmNotification
                        {
                            To = item,
                            // RegistrationIds = new List<string> { item },
                            ContentAvailable = true,
                            Priority         = GcmNotificationPriority.High,
                            DryRun           = true,
                            Notification     = JObject.Parse(
                                "{" +
                                "\"title\" : \"" + _title + "\"," +
                                "\"body\" : \"" + _mess + "\"," +
                                "\"sound\" : \"default\"" +
                                "}"),
                            Data = JObject.Parse(
                                "{" +
                                "\"content_id\":\"9daacefd-47bd-421d-a13d-efda4f13935f\"," +
                                "\"content_noti_id\":\"transferNoti\"," +
                                "\"content_code\":8," +
                                "\"badge\":1" +
                                "}")
                        });
                    }

                    gcmBroker.Stop();
                }

                Debug.WriteLine("Push Notifications Json: ", json);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Push Notifications Error: ", ex);
            }
        }
        private void SendPushNotification(string deviceToken, string message)
        {
            try
            {
                //Get Certificate
                var appleCert = System.IO.File.ReadAllBytes(Server.MapPath("~/IOS/" p12 certificate ""));

                // Configuration (NOTE: .pfx can also be used here)
                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "p12 Password");

                // Create a new broker
                var apnsBroker = new ApnsServiceBroker(config);

                // Wire up events
                apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
                    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 apnsNotification = notificationException.Notification;
                            var statusCode       = notificationException.ErrorStatusCode;
                            string desc          = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                            Console.WriteLine(desc);
                            Label1.Text = desc;
                        }
                        else
                        {
                            string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                            // Inner exception might hold more useful information like an ApnsConnectionException
                            Console.WriteLine(desc);
                            Label1.Text = desc;
                        }

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

                apnsBroker.OnNotificationSucceeded += (notification) =>
                {
                    Label1.Text = "Apple Notification Sent successfully!";
                };



                var fbs = new FeedbackService(config);
                fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
                {
                    // Remove the deviceToken from your database
                    // timestamp is the time the token was reported as expired
                };

                // Start Proccess
                apnsBroker.Start();

                var payload = new Dictionary <string, object>();
                var aps     = new Dictionary <string, object>();
                aps.Add("alert", "This is a sample notification!");
                aps.Add("badge", 1);
                aps.Add("sound", "chime.aiff");
                payload.Add("aps", aps);

                payload.Add("confId", "20");
                payload.Add("pageFormat", "Webs");
                payload.Add("pageTitle", "Evalu");
                payload.Add("webviewURL", "https:/UploadedImages/MobileApp/icons/Datalist-Defg");
                payload.Add("notificationBlastID", "");
                payload.Add("pushtype", "");

                payload.Add("content-available", );


                var jsonx = Newtonsoft.Json.JsonConvert.SerializeObject(payload);

                if (deviceToken != "")
                {
                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = deviceToken,
                        Payload     = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(payload))
                    });
                }

                apnsBroker.Stop();
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #19
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDeviceToken.Text))
            {
                return;
            }

            progressBar1.Value  = 5;
            progressBar1.Value += 5;

            if (rbAndroid.Checked)
            {
                var broker = new GcmServiceBroker(new GcmConfiguration(GcmSenderId, GcmSenderAuthToken, null));

                broker.OnNotificationFailed    += BrokerOnOnNotificationFailed;
                broker.OnNotificationSucceeded += BrokerOnOnNotificationSucceeded;

                progressBar1.Value += 5;
                broker.Start();

                progressBar1.Value += 5;
                var payload = JsonConvert.SerializeObject(new GcmNotificationPayload
                {
                    Title   = txtTitle.Text,
                    Message = txtMessage.Text,
                    Badge   = txtBadge.Text,
                    JobId   = int.Parse(txtJobId.Text),
                    UserId  = int.Parse(txtUserId.Text)
                });
                broker.QueueNotification(new GcmNotification
                {
                    RegistrationIds = new List <string> {
                        txtDeviceToken.Text
                    },
                    Data = JObject.Parse(payload)
                });

                progressBar1.Value += 5;
                broker.Stop();
            }
            else if (rbiOS.Checked)
            {
                var certificateFilePath = Path.GetDirectoryName(Application.ExecutablePath) + ApnsCertificateFile;
                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certificateFilePath, ApnsCertificatePassword);
                var broker = new ApnsServiceBroker(config);

                broker.OnNotificationFailed    += Broker_OnNotificationFailed;
                broker.OnNotificationSucceeded += Broker_OnNotificationSucceeded;

                progressBar1.Value += 5;
                broker.Start();

                progressBar1.Value += 5;
                var payload = JsonConvert.SerializeObject(new ApnsNotificationPayload
                {
                    Aps = new Aps
                    {
                        Alert = new Alert
                        {
                            Body  = txtMessage.Text,
                            Title = txtTitle.Text
                        },
                        Badge = int.Parse(txtBadge.Text)
                    },
                    JobId  = int.Parse(txtJobId.Text),
                    UserId = int.Parse(txtUserId.Text)
                });
                broker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = txtDeviceToken.Text.Replace(" ", string.Empty),
                    Payload     = JObject.Parse(payload)
                });

                progressBar1.Value += 5;
                broker.Stop();
            }
            else if (rbWindows.Checked)
            {
                var customParameters      = "/MainPage.xaml?" + HttpUtility.UrlEncode($"jobId={txtJobId.Text}&userId={txtUserId.Text}");
                var notificationXmlString = @"<toast launch='" + customParameters + $@"'>
                                              <visual lang='en-US'>
                                                <binding template='ToastImageAndText02'>
                                                  <image id='1' src='World' />
                                                  <text id='1'>{txtTitle.Text}</text>
                                                  <text id='2'>{txtMessage.Text}</text>
                                                </binding>
                                              </visual>
                                            </toast>";

                var config = new WnsConfiguration(WnsPackageName, WnsPackageSid, WnsClientSecret);
                var broker = new WnsServiceBroker(config);

                broker.OnNotificationSucceeded += BrokerOnOnNotificationSucceeded;
                broker.OnNotificationFailed    += BrokerOnOnNotificationFailed;

                progressBar1.Value += 5;
                broker.Start();

                progressBar1.Value += 5;
                broker.QueueNotification(new WnsToastNotification
                {
                    ChannelUri = txtDeviceToken.Text,
                    Payload    = XElement.Parse(notificationXmlString)
                });

                progressBar1.Value += 5;
                broker.Stop();
            }

            progressBar1.Value += 5;
            while (progressBar1.Value < 100)
            {
                progressBar1.Value += 5;
            }
            progressBar1.Value = 100;
        }
Example #20
0
        /// <summary>
        /// Sends the push.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns> Result message </returns>
        public string SendPushNotification(PushNotificationModel model)
        {
            string resultmessage = string.Empty;

            // Create a new broker
            ApnsServiceBroker apnsBroker = new ApnsServiceBroker(this._pushConfig);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        ////Delete invalid token
                        if (statusCode == ApnsNotificationErrorStatusCode.InvalidToken)
                        {
                            this._logger.LogInformation($"Token deleted : {apnsNotification.DeviceToken}");
                        }

                        ////Console.WriteLine(
                        resultmessage = resultmessage +
                                        $"\r\nApple Notification Failed: ID={apnsNotification.DeviceToken}, Code={statusCode}";
                    }
                    else
                    {
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        ////Console.WriteLine(
                        resultmessage = resultmessage + $"\r\nApple Notification Failed for some unknown reason : {ex.InnerException}";
                    }

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

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                ////Console.WriteLine(
                resultmessage = resultmessage + "\r\nApple Notification Sent!";
            };

            // Start the broker
            apnsBroker.Start();

            foreach (var deviceToken in  model.DeviceTokens)
            {
                var jsonData = JsonConvert.SerializeObject(new
                {
                    aps = new
                    {
                        alert = model.Message,
                        badge = 1,
                        sound = "default"
                    },
                    CustomParams = model.Parameter.Value
                });

                jsonData = jsonData.Replace("CustomParams", model.Parameter.Key);

                // Queue a notification to send
                apnsBroker.QueueNotification(
                    new ApnsNotification()
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse(jsonData)
                });
            }
            ;

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();

            return(resultmessage);
        }
        public ActionResult SendNotification()
        {
            try
            {
                string deviceId           = Request["deviceToken"];
                string certificateFilePwd = Request["certificateFilePwd"];
                var    file = Request.Files["p12File"];

                //Upload file into a directory
                string path = Path.Combine(Server.MapPath("~/Certificates/"), "CertificateName.p12");
                file.SaveAs(path);

                //Get Certificate
                //You will get this certificate from apple account
                var appleCert = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath("~/Certificates/CertificateName.p12"));


                // Configuration
                var config = new PushSharp.Apple.ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, certificateFilePwd);
                config.ValidateServerCertificate = false;

                // Create a new broker
                var apnsBroker = new ApnsServiceBroker(config);

                //Wire up events
                apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
                    aggregateEx.Handle(ex =>
                    {
                        if (ex is ApnsNotificationException)
                        {
                            var notificationException = (ApnsNotificationException)ex;

                            // Deal with the failed notification
                            var apnsNotification = notificationException.Notification;
                            var statusCode       = notificationException.ErrorStatusCode;
                            string desc          = $"Notification Failed: ID={apnsNotification.Identifier},Code={statusCode}";
                            Console.WriteLine(desc);
                        }
                        else
                        {
                            string desc = $"Notification Failed for some unknown reason: ID={ex.InnerException}";
                            Console.WriteLine(desc);
                        }
                        return(true);
                    });
                    ViewBag.Message = "Notification sent successfully.";
                };

                apnsBroker.OnNotificationSucceeded += (notification) =>
                {
                    ViewBag.Message = "Notification sent failed.";
                };

                var fbs = new FeedbackService(config);
                fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) =>
                {
                };

                //All apns configuration done
                //Now start the apns broker
                apnsBroker.Start();

                if (!string.IsNullOrEmpty(deviceId))
                {
                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = deviceId,
                        Payload     = JObject.Parse(("{\"aps\": {\"alert\": {\"title\":\"Notification Title\",\"body\" : \"" + "Message Body" + "\"},\"badge\": \"" + 0 + "\",\"content-available\": \"1\",\"sound\": \"default\"},\"notification_details\": {}} "))
                    });
                }
                apnsBroker.Stop();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(RedirectToAction("Index"));
        }
Example #22
0
        public void SendIOSPushNotification(List <UserDevice> devices, AdminNotifications AdminNotification = null, Notification OtherNotification = null, int Type = 0)
        {
            try
            {
                // Configuration (NOTE: .pfx can also be used here)
                if (devices.Count() == 0) //it means there is no device no need to run the below code
                {
                    return;
                }

                if (ApnsConfig != null)
                {
                    IosPush pushModel = new IosPush();

                    foreach (var device in devices.Where(x => x.IsActive))
                    {
                        try
                        {
                            if (AdminNotification != null)
                            {
                                pushModel.aps.alert.title             = AdminNotification.Title;
                                pushModel.aps.alert.body              = AdminNotification.Description;
                                pushModel.notification.NotificationId = device.User.Notifications.FirstOrDefault(x => x.AdminNotification_Id == AdminNotification.Id).Id;
                                pushModel.notification.Type           = (int)PushNotificationType.Announcement;
                            }
                            else
                            {
                                pushModel.aps.alert.title             = OtherNotification.Title;
                                pushModel.aps.alert.body              = OtherNotification.Text;
                                pushModel.notification.NotificationId = OtherNotification.Id;
                                pushModel.notification.Type           = Type;
                            }

                            ApnsServiceBroker apnsBroker;

                            if (device.ApplicationType == UserDevice.ApplicationTypes.Enterprise)
                            {
                                if (device.EnvironmentType == UserDevice.ApnsEnvironmentTypes.Production)
                                {
                                    apnsBroker = new ApnsServiceBroker(Enterprise.IOS.ProductionConfig);
                                }
                                else // Sandbox/Development
                                {
                                    apnsBroker = new ApnsServiceBroker(Enterprise.IOS.SandboxConfig);
                                }
                            }
                            else //PlayStore
                            {
                                if (device.EnvironmentType == UserDevice.ApnsEnvironmentTypes.Production)
                                {
                                    apnsBroker = new ApnsServiceBroker(PlayStore.IOS.ProductionConfig);
                                }
                                else // Sandbox/Development
                                {
                                    apnsBroker = new ApnsServiceBroker(device.iOSPushConfiguration = PlayStore.IOS.SandboxConfig);
                                }
                            }

                            apnsBroker.OnNotificationFailed    += IOSPushNotificationFailed;
                            apnsBroker.OnNotificationSucceeded += IOSNotificationSuccess;

                            // Start the broker
                            apnsBroker.Start();
                            apnsBroker.QueueNotification(new ApnsNotification
                            {
                                DeviceToken = device.AuthToken,
                                Payload     = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(pushModel))
                            });

                            apnsBroker.Stop();
                            apnsBroker.OnNotificationFailed    -= IOSPushNotificationFailed;
                            apnsBroker.OnNotificationSucceeded -= IOSNotificationSuccess;
                        }
                        catch (Exception ex)
                        {
                            Utility.LogError(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex);
            }
        }
 public void SendNotification(List <long> userIdsList, string message, object data)
 {
     try
     {
         var cert             = Directory.GetCurrentDirectory() + "/wwwroot/Certs/RES_PUSH_PROD.p12";
         var MY_DEVICE_TOKENS = this._dbToken.Where(t => userIdsList.Any(usr => usr == t.UserId)).ToList();
         // Configuration (NOTE: .pfx can also be used here)
         var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, cert, "");
         // Create a new broker
         var apnsBroker = new ApnsServiceBroker(config);
         // Wire up events
         apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
             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 apnsNotification = notificationException.Notification;
                     var statusCode       = notificationException.ErrorStatusCode;
                     Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                 }
                 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);
             });
         };
         apnsBroker.OnNotificationSucceeded += (notification) => {
             Console.WriteLine("Apple Notification Sent!");
         };
         // Start the broker
         apnsBroker.Start();
         foreach (var deviceToken in MY_DEVICE_TOKENS)
         {
             // Queue a notification to send
             if (data.GetType() == typeof(ReportEntity))
             {
                 var report = (ReportEntity)data;
                 apnsBroker.QueueNotification(new ApnsNotification
                 {
                     DeviceToken = deviceToken.Token,
                     Payload     = JObject.FromObject(
                         new
                     {
                         aps = new
                         {
                             alert = new Dictionary <string, object>()
                             {
                                 { "title", "Reporte Actualizado" },
                                 { "body", message },
                                 {
                                     "loc-key", new string[]
                                     {
                                         report.CompanyId.ToString(),
                                         report.UserId.ToString(),
                                         report.WeekId.ToString()
                                     }
                                 }
                             },
                             sound = "default"
                         }
                     }
                         )
                 });
             }
             else if (data.GetType() == typeof(MessageResponse))
             {
                 var messageData = (MessageResponse)data;
                 apnsBroker.QueueNotification(new ApnsNotification
                 {
                     DeviceToken = deviceToken.Token,
                     Payload     = JObject.FromObject(
                         new
                     {
                         aps = new
                         {
                             alert = new Dictionary <string, object>()
                             {
                                 { "title", "Nuevo mensaje" },
                                 { "body", message },
                                 {
                                     "loc-key", new string[]
                                     {
                                         messageData.Id.ToString(),
                                         messageData.GroupId.ToString()
                                     }
                                 }
                             },
                             sound = "default"
                         }
                     }
                         )
                 });
             }
             else
             {
                 apnsBroker.QueueNotification(new ApnsNotification {
                     DeviceToken = deviceToken.Token,
                     Payload     = JObject.FromObject(
                         new { aps = new
                               {
                                   alert = new
                                   {
                                       title = "Aviso:",
                                       body  = message
                                   },
                                   sound = "default"
                               } }
                         )
                 });
             }
         }
         // Stop the broker, wait for it to finish
         // This isn't done after every message, but after you're
         // done with the broker
         apnsBroker.Stop();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Example #24
0
        public static bool Push(string apnToken, string message)
        {
            _log.DebugFormat("[Apns] step 1");

            _log.DebugFormat("Token = " + apnToken);

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               ConfigurationManager.AppSettings["ApnsCertificate"].ToString(), ConfigurationManager.AppSettings["ApnsPassword"].ToString());

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            _log.DebugFormat("[Apns] step 2");
            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                _log.DebugFormat("[Apns] step 3");
                aggregateEx.Handle(ex =>
                {
                    _log.DebugFormat("[Apns] step 4");
                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException)
                    {
                        _log.DebugFormat("[Apns] step 5");
                        var notificationException = (ApnsNotificationException)ex;
                        _log.DebugFormat("[Apns] step 6");
                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

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

                    // Mark it as handled
                    //return true;
                });
            };
            _log.DebugFormat("[Apns] step 7");
            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                _log.InfoFormat("Apple Notification Sent!");
            };

            _log.DebugFormat("[Apns] step 8");
            // Start the broker
            apnsBroker.Start();
            _log.DebugFormat("[Apns] step 9");

            // Queue a notification to send
            var apnsObj = new PayLoadEntity()
            {
                aps = new Aps()
                {
                    alert = message
                }
            };
            var apnsStr = JsonConvert.SerializeObject(apnsObj);

            _log.DebugFormat("[Apns] step 9.1");
            _log.DebugFormat(apnsStr);
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = apnToken,
                Payload     = JObject.Parse(apnsStr)
            });

            _log.DebugFormat("[Apns] step 10");

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();
            _log.DebugFormat("[Apns] step 11");
            return(true);
        }
Example #25
0
        public async Task <bool> APNS_Send(List <UserDeviceInfo> splitList, string Message)
        {
            if (string.IsNullOrWhiteSpace(Message))
            {
                Message = "Hello this is broadcast";
            }

            //Find  Certificate Path
            var certificatePath = Path.Combine(_hostingEnvironment.WebRootPath, _appSettings.CertificateName);

            //configure certificate with Password
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certificatePath, _appSettings.CertificatePwd);

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                _logger.Information("***Info***: notification success " + notification.DeviceToken);
            };


            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                aggregateEx.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;

                        _logger.Error($"Notification Failed: ID={apnsNotification.DeviceToken}, Code={statusCode}");
                    }
                    else
                    {
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        _logger.Error($"Notification Failed for some (Unknown Reason) : {ex.Message},token= {notification.DeviceToken}");
                    }

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

            // Start the broker
            apnsBroker.Start();

            var tasks = new Task[splitList.Count];

            //splitList contains multiple list of tokens waiting to queue, a list that holds list of token

            if (splitList.Count > 0)
            {
                int count = 0;
                //start a new task for each list in splitList
                foreach (var lst in splitList)
                {
                    tasks[count] = Task.Factory.StartNew(() =>
                    {
                        _logger.Information("***INFO*** calling task :" + count);
                        QueueAppleNotifications(lst, Message, apnsBroker);
                    },
                                                         TaskCreationOptions.None);

                    count++;
                }
            }
            return(WaitForTasksToFinish(tasks, apnsBroker));
        }
Example #26
0
 public void Stop()
 {
     _broker.Stop();
     _broker   = null;
     _contents = null;
 }
        public void SendAppleNotification(string message)
        {
            List <string> MY_DEVICE_TOKENS = new List <string> {
            };

            try
            {
                string path = "~/Files/Certificate/IOS/Production_Certificate.p12";
                //Get Certificate
                var appleCert = File.ReadAllBytes(path);

                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "password");


                // Create a new broker
                var apnsBroker = new ApnsServiceBroker(config);

                // Wire up events
                apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
                    aggregateEx.Handle(ex =>
                    {
                        // See what kind of exception it was to further diagnose
                        if (ex is ApnsNotificationException)
                        {
                            //var notificationException = (ApnsNotificationException)ex;
                            //var apnsNotification = notificationException.Notification;
                            //var statusCode = notificationException.ErrorStatusCode;
                            //string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                            //Console.WriteLine(desc);
                            ApnLog.WriteErrorLog(ex);
                        }
                        else
                        {
                            //string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                            // Inner exception might hold more useful information like an ApnsConnectionException
                            //Console.WriteLine(desc);
                            ApnLog.WriteErrorLog(ex);
                        }
                        // Mark it as handled
                        return(true);
                    });
                };

                apnsBroker.OnNotificationSucceeded += (notification) =>
                {
                    ApnLog.WriteSuccessLog(notification);
                    //Console.WriteLine("Apple Notification Sent successfully!");
                };

                // Start Proccess
                apnsBroker.Start();

                foreach (var deviceToken in MY_DEVICE_TOKENS)
                {
                    //Queue a notification to send
                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = deviceToken,
                        Payload     = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
                    });
                }

                apnsBroker.Stop();
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #28
0
        /// <summary>
        /// Apple notification
        /// </summary>
        /// <param name="file">Full path file name</param>
        /// <param name="pass">Password of file</param>
        /// <param name="tokens">List device tokens</param>
        /// <param name="title">Title message</param>
        /// <param name="text">Content message</param>
        /// <param name="module">Module name</param>
        public static void AppleNotification(string file, string pass, List <string> tokens,
                                             string title, string text, string module)
        {
            /*var baseDir = AppDomain.CurrentDomain.BaseDirectory;
             * file = @"bin\Certificates\aps_development.cer";
             * file = Path.Combine(baseDir, file);
             * pass = "******";*/

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, file, pass);

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                    }
                    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);
                });
            };

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                Console.WriteLine("Apple Notification Sent!");
            };

            // Start the broker
            apnsBroker.Start();

            var pushContent = "{ \"title\" : \"" + title + "\", \"text\" : \"" + text + "\", \"sound\" : \"true\" , \"Module\" : \"" + module + "\" ,\"additionalData\": {\"google.message_id\": \"0:1488356994305684%163a31bc163a31bc\",\"coldstart\": false,\"collapse_key\": \"com.hearti.walley\",\"foreground\": true } }";

            //pushContent = "{ \"title\" : \"" + title + "\", \"text\" : \"" + text + "\", \"Module\" : \"" + module + "\", \"sound\" : \"true\" }";

            foreach (var deviceToken in tokens)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse(pushContent)
                });
            }

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();
        }
Example #29
0
    public static string SendPushNotificationIOS(string DeviceToken, string Title, string Message)
    {
        string result = string.Empty;

        try
        {
            //Get Certificate
            var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Certificate/IOS/EchoDevAPNS.p12"));

            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "1234");

            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;
                        string desc          = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                        // Console.WriteLine(desc);
                        result = desc;
                    }
                    else
                    {
                        string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        // Console.WriteLine(desc);
                        result = desc;
                    }

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

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                result = "Success!";
            };

            var fbs = new FeedbackService(config);
            fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
            {
                // Remove the deviceToken from your database
                // timestamp is the time the token was reported as expired
            };

            // Start Proccess
            apnsBroker.Start();

            if (DeviceToken != "")
            {
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = DeviceToken,
                    Payload     = JObject.Parse(("{\"aps\":{\"badge\":0,\"sound\":\"default\",\"alert\":{ \"title\" : \"" + Title + "\",\"body\":\"" + (Message + "\"}}}")))
                });
            }

            apnsBroker.Stop();
        }
        catch (Exception)
        {
            throw;
        }

        return(result);
    }
Example #30
0
 public APNServices(ApnsServiceBroker apnsServiceBroker,
                    ILogger <APNServices> logger)
 {
     this.apnsServiceBroker = apnsServiceBroker;
     this.logger            = logger;
 }
Example #31
0
        private void IosSend(List <Lizay.dll.entity.USERS> users, string Message, string Header, string Url)
        {
            //var task = Task.Factory.StartNew(
            //state =>
            //{
            var context = HttpContext.Current;

            if (users.Count <= 0)
            {
                return;
            }
            var pass = ConfigurationManager.AppSettings["IosCerPass"];
            var path = string.Empty;

            if (HttpRuntime.AppDomainAppId != null)
            {
                path = context.Server.MapPath("~/Cer/" + "ios.p12");
            }
            else
            {
                path = @"C:\inetpub\wwwroot\lizayapp\Cer\ios.p12";
            }

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, path, pass)
            {
            };
            var apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.Start();

            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                    }
                    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);
                });
            };

            foreach (var item in users)
            {
                //var badge = MessageUtils.GetUnReadedMessages(item) + MessageUtils.GetUnreadedContactMessage(item);
                var badge = 0;

                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = item.DEVICE_ID,
                    //Payload = JObject.Parse("{\"aps\":{\"badge\":1,\"Header\":\"" + model.Header + "\",\"Text\":\"" + model.Message + "\",\"Url\":\"" + model.Url + "\"}}")
                    Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + Message + "\",\"badge\":\"" + badge + "\",\"sound\":\"default\",\"Header\":\"" + Header + "\",\"Text\":\"" + Message + "\",\"Url\":\"" + Url + "\"}}")
                });
            }
            apnsBroker.Stop();
            //},
            //HttpContext.Current);
        }
Example #32
0
        public void DoWork()
        {
            while (!_shouldStop)
            {
                ContadorIntentos++;
                try
                {
                    byte[] appleCert = null;
                    if (!File.Exists(CertAppleURL))
                    {
                        EscribirEnLog("hubo Error : No existe el Certificado iOS");
                    }
                    else
                    {
                        appleCert = File.ReadAllBytes(CertAppleURL);
                        EscribirEnLog("certificado encontrado:" + "iOS:" + CertAppleURL + ",  Pass:"******", GCMKeyCliente: " + GCMKeyCliente + ", GCMKeyEmpresa: " + GCMKeyEmpresa + ", GCMKeyConductor: " + GCMKeyConductor + ", Alerta " + alerta);
                    }

                    foreach (var token in Tokens)
                    {
                        if (!TokensSended.Contains(token.TokenID))
                        {
                            try
                            {
                                string FBSenderAuthToken = "";
                                switch (token.TipoAplicacion)
                                {
                                case Aplicacion.Usuario: FBSenderAuthToken = GCMKeyCliente;
                                    break;

                                case Aplicacion.Conductor:
                                    FBSenderAuthToken = GCMKeyConductor;
                                    break;

                                case Aplicacion.Administrador:
                                    FBSenderAuthToken = GCMKeyCliente;
                                    break;

                                case Aplicacion.Encargado:
                                    FBSenderAuthToken = GCMKeyEmpresa;
                                    break;

                                default:
                                    FBSenderAuthToken = GCMKeyCliente;
                                    break;
                                }
                                switch (token.TipoDispositivo)
                                {
                                case Dispositivo.Apple:
                                    if (appleCert != null)
                                    {
                                        ApnsConfiguration.ApnsServerEnvironment ambiente = ApplePushProduccion ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox;
                                        var configApns = new ApnsConfiguration(ambiente, appleCert, CertApplePass, false);

                                        apnsPush = new ApnsServiceBroker(configApns);
                                        apnsPush.OnNotificationFailed    += apnsPush_OnNotificationFailed;
                                        apnsPush.OnNotificationSucceeded += apnsPush_OnNotificationSucceeded;
                                        apnsPush.Start();
                                        apnsPush.QueueNotification((ApnsNotification)alerta.Notificacion(token));
                                        apnsPush.Stop();
                                    }
                                    break;

                                case Dispositivo.Android:
                                    var configGCM = new GcmConfiguration(FBSenderAuthToken);

                                    configGCM.OverrideUrl("https://fcm.googleapis.com/fcm/send");
                                    configGCM.GcmUrl = "https://fcm.googleapis.com/fcm/send";
                                    gcmPush          = new GcmServiceBroker(configGCM);

                                    gcmPush.OnNotificationSucceeded += gcmPush_OnNotificationSucceeded;
                                    gcmPush.OnNotificationFailed    += gcmPush_OnNotificationFailed;
                                    gcmPush.Start();
                                    gcmPush.QueueNotification((GcmNotification)alerta.Notificacion(token));

                                    gcmPush.Stop();
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                EscribirEnLog("hubo Error : " + ex.Message);
                                Console.WriteLine(ex.Message);
                            }
                        }
                    }

                    if (todoCorrecto() || (ContadorIntentos >= CantidadIntentos))
                    {
                        this._shouldStop = true;
                    }
                    else
                    {
                        this.ContadorEnviados   = 0;
                        this.ContadorNoEnviados = 0;
                        Thread.Sleep(SegundosReintento * 1000);
                    }
                }
                catch (Exception ex)
                {
                    EscribirEnLog("hubo Error : " + ex.Message);
                    Console.WriteLine(ex.Message);
                }
            }
        }
Example #33
0
        public async Task Apns(int expectFailed, List <ApnsNotification> notifications, IEnumerable <ApnsResponseFilter> responseFilters, int batchSize = 1000, int scale = 1)
        {
            long success = 0;
            long failed  = 0;

            var server = new TestApnsServer();

            server.ResponseFilters.AddRange(responseFilters);

            // We don't want to await this, so we can start the server and listen without blocking
#pragma warning disable 4014
            server.Start();
#pragma warning restore 4014

            var config = new ApnsConfiguration("127.0.0.1", 2195)
            {
                InternalBatchSize = batchSize
            };


            var broker = new ApnsServiceBroker(config);
            broker.OnNotificationFailed += (notification, exception) =>
            {
                Interlocked.Increment(ref failed);
            };
            broker.OnNotificationSucceeded += (notification) => Interlocked.Increment(ref success);

            broker.Start();

            if (scale != 1)
            {
                broker.ChangeScale(scale);
            }

            var c = Log.StartCounter();

            foreach (var n in notifications)
            {
                broker.QueueNotification(n);
            }

            broker.Stop();

            c.StopAndLog("Test Took {0} ms");

            await server.Stop().ConfigureAwait(false);

            var expectedSuccess = notifications.Count - expectFailed;

            var actualFailed  = failed;
            var actualSuccess = success;

            Console.WriteLine("EXPECT: Successful: {0}, Failed: {1}", expectedSuccess, expectFailed);
            Console.WriteLine("SERVER: Successful: {0}, Failed: {1}", server.Successful, server.Failed);
            Console.WriteLine("CLIENT: Successful: {0}, Failed: {1}", actualSuccess, actualFailed);

            Assert.Equal(expectFailed, actualFailed);
            Assert.Equal(expectedSuccess, actualSuccess);

            Assert.Equal(server.Failed, actualFailed);
            Assert.Equal(server.Successful, actualSuccess);
        }
Example #34
0
 private static void ApplePusher_OnStop(ApnsServiceBroker obj)
 {
     Console.WriteLine($"End {DateTime.Now}");
 }
Example #35
0
        public static void APNSSendPushNotificationForBadgeByPushSharp(string deviceId, string message)
        {
            //For local and QA environment
            string pathToFiles = HttpContext.Current.Server.MapPath("~/Certifications/PalMarClientCertPushNotification.p12");
            var    appleCert   = File.ReadAllBytes(pathToFiles);

            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               appleCert, "PalMar.PUSH.NOTIFICATION?"); //For local and QA environment

            //////////////////////////////////////////////////////////////////////////////

            ////For Online environment
            //string pathToFiles = HttpContext.Current.Server.MapPath("~/Certifications/ss-prod.p12");
            //var appleCert = File.ReadAllBytes(pathToFiles);

            //// Configuration (NOTE: .pfx can also be used here)
            //var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
            //    appleCert, "ss123"); //For online environment

            //////////////////////////////////////////////////////////////////////////


            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);

            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                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 apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        //Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                    }
                    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);
                });
            };

            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                //Console.WriteLine("Apple Notification Sent!");
            };

            // Start the broker
            apnsBroker.Start();

            var data = new
            {
                aps = new
                {
                    alert    = message,
                    sound    = "default",
                    link_url = ""
                }
            };

            //var data = new
            //{
            //    aps = new
            //    {
            //        badge = count,
            //    }
            //};
            var json = JsonConvert.SerializeObject(data);

            //foreach (var deviceToken in MY_DEVICE_TOKENS)
            //{
            // Queue a notification to send
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = deviceId,
                //Payload = JObject.Parse("{\"aps\":{\"badge\":7}}")
                Payload = JObject.Parse(json)
            });
            //}

            // Stop the broker, wait for it to finish
            // This isn't done after every message, but after you're
            // done with the broker
            apnsBroker.Stop();
        }
Example #36
0
        /// <summary>
        /// PushToIphone
        /// </summary>
        /// <param name="devicelist"></param>
        /// <returns></returns>
        public static bool PushToIphone(List <PushNotificationModel> devicelist)
        {
            try
            {
                string certificatePath = HostingEnvironment.MapPath("~/Certificate/Certificates_bibliovelo_push_production.p12");
                //string certificatepath = "D:/Projects/BiblioVeloApi/BiblioVeloApi/Certificate/APNSDevBibliovelo";
                string certificatepassword = ConfigurationManager.AppSettings["CertificatePassword"].ToString();
                // string certificatePath = ConfigurationManager.AppSettings["CertificatePath"].ToString();
                // Configuration (NOTE: .pfx can also be used here)
                var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
                                                   certificatePath, string.Empty);

                // Create a new broker
                var apnsBroker = new ApnsServiceBroker(config);

                // Wire up events
                apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
                    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 apnsNotification = notificationException.Notification;
                            var statusCode       = notificationException.ErrorStatusCode;

                            Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                        }
                        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);
                    });
                };

                apnsBroker.OnNotificationSucceeded += (notification) =>
                {
                    Console.WriteLine("Apple Notification Sent!");
                };

                // Start the broker
                apnsBroker.Start();

                foreach (var deviceToken in devicelist)
                {
                    // Queue a notification to send
                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = deviceToken.DeviceToken,
                        Payload     = JObject.Parse("{\"aps\":{\"alert\":\"" + deviceToken.Message + "\",\"badge\":1,\"sound\":\"default\"}}")
                                      //Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + deviceToken.Message + "\",\"badge\":1,\"sound\":\"default\"}\"BookingId\":{\"" + deviceToken.BookingId + "\"}}")
                    });
                }

                // Stop the broker, wait for it to finish
                // This isn't done after every message, but after you're
                // done with the broker
                apnsBroker.Stop();

                return(true);
            }
            catch (Exception ex)
            {
                Common.ExcepLog(ex);
                throw;
            }
        }