Example #1
0
        void SendMessage()
        {
            SqlDataReader count;
            SqlDataReader dr;
            System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Conn").ConnectionString);
            string strSql = "select * from APNSDevices";
            cnn.Open();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strSql, cnn);
            cmd.CommandType = System.Data.CommandType.Text;
            dr = cmd.ExecuteReader();
            // read the .p12 certificate file'
            object appleCert = System.IO.File.ReadAllBytes(Server.MapPath("~\\App_Data\\my.p12"));
            // create a push sharp APNS configuration'
            PushSharp.Apple.ApnsConfiguration config = new PushSharp.Apple.ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "myPassword");
            config.ValidateServerCertificate = false;
            object apnsbRoker = new ApnsServiceBroker(config);
            apnsbROKER.OnNotificationSucceeded += new System.EventHandler(this.Events_OnNotificationSucceeded);
            apnsbROKER.OnNotificationFailed += new System.EventHandler(this.Events_OnNotificationFailed);
            object fbs = new FeedbackService(config);
            fbs.FeedbackReceived += new EventHandler(this.Events_FeedbackReceived);
            while (dr.Read())
            {
                count = (count + 1);
            }

            dr.Close();
            cnn.Close();
            result.Text = ("notification sent" + count);
        }
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);
        }
Example #3
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 #4
0
        public ApnsConnection(ApnsConfiguration configuration)
        {
            id = ++ID;
            if (id >= int.MaxValue)
            {
                ID = 0;
            }

            Configuration = configuration;

            certificate = Configuration.Certificate;

            certificates = new X509CertificateCollection();

            // Add local/machine certificate stores to our collection if requested
            if (Configuration.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            // Add optionally specified additional certs into our collection
            if (Configuration.AdditionalCertificates != null)
            {
                foreach (var addlCert in Configuration.AdditionalCertificates)
                {
                    certificates.Add(addlCert);
                }
            }

            // Finally, add the main private cert for authenticating to our collection
            if (certificate != null)
            {
                certificates.Add(certificate);
            }

            timerBatchWait = new Timer(new TimerCallback(async state => {
                await batchSendSemaphore.WaitAsync();
                try
                {
                    await SendBatch().ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    //ignore
                }
                finally
                {
                    batchSendSemaphore.Release();
                }
            }), null, Timeout.Infinite, Timeout.Infinite);
        }
Example #5
0
 public void APNS_Feedback_Service ()
 {
     var config = new ApnsConfiguration (
         ApnsConfiguration.ApnsServerEnvironment.Sandbox, 
         Settings.Instance.ApnsCertificateFile, 
         Settings.Instance.ApnsCertificatePassword);
     
     var fbs = new FeedbackService (config);
     fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) => {
         // Remove the deviceToken from your database
         // timestamp is the time the token was reported as expired
     };
     fbs.Check ();
 }
Example #6
0
        public ApnsConnection(ApnsConfiguration configuration)
        {
            id = ++ID;
            if (id >= int.MaxValue)
                ID = 0;

            Configuration = configuration;

            certificate = Configuration.Certificate;

            certificates = new X509CertificateCollection();

            // Add local/machine certificate stores to our collection if requested
            if (Configuration.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            // Add optionally specified additional certs into our collection
            if (Configuration.AdditionalCertificates != null)
            {
                foreach (var addlCert in Configuration.AdditionalCertificates)
                    certificates.Add(addlCert);
            }

            // Finally, add the main private cert for authenticating to our collection
            if (certificate != null)
                certificates.Add(certificate);

            timerBatchWait = new Timer(new TimerCallback(async state =>
            {

                await batchSendSemaphore.WaitAsync();
                try
                {
                    await SendBatch().ConfigureAwait(false);
                }
                finally
                {
                    batchSendSemaphore.Release();
                }

            }), null, Timeout.Infinite, Timeout.Infinite);
        }
        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 #8
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 #9
0
 public ApnsServiceConnectionFactory(ApnsConfiguration configuration)
 {
     Configuration = configuration;
 }
Example #10
0
 public ApnsServiceConnection(ApnsConfiguration configuration)
 {
     connection = new ApnsConnection(configuration);
 }
Example #11
0
 public ApnsServiceBroker(ApnsConfiguration configuration) : base(new ApnsServiceConnectionFactory(configuration))
 {
 }
Example #12
0
 public FeedbackService(ApnsConfiguration configuration)
 {
     Configuration = configuration;
 }
Example #13
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 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 #15
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);
        }
 public FeedbackService (ApnsConfiguration configuration)
 {
     Configuration = configuration;
 }