Beispiel #1
0
        public static void SendNotificationToIOS(string message = "Hi", int badgeCount = 1)
        {
            try
            {
                var config    = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, Settings.Instance.ApnsCertificateFile, Settings.Instance.ApnsCertificatePassword);
                var tokenList = new List <string>();
                tokenList.Add("818ced5aeccb086e872ea9871d7272843b98ac566c5ea82c6f81655d7a79e768");
                tokenList.Add("f2661a9faf61b7724a716175cd423c3a9e49f3978edfb29013948a4642ec96f7");

                var broker = new ApnsServiceBroker(config);
                broker.Start();

                foreach (var token in tokenList)
                {
                    broker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = token,
                        Payload     = JObject.Parse("{ \"aps\" : { \"alert\" : \"" + message + "\", \"badge\":\"1\",\"sound\":\"sms-received1.mp3\"} }")
                    });
                }

                broker.Stop();
            }
            catch (Exception ex)
            {
                Log.Error("SendNotificationToiOS Error", ex);
            }
        }
        public void Send(NotificationPayload notification, IDevice device)
        {
            if (string.IsNullOrEmpty(device.Token))
            {
                return;
            }

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

            Console.WriteLine(apnsNotification.ToString());

            ApnsServiceBroker apnsBroker = new ApnsServiceBroker(config);

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

            apnsBroker.Start();
            apnsBroker.QueueNotification(apnsNotification);
            apnsBroker.Stop();
        }
        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.Equal(attempted, succeeded);
            Assert.Equal(0, failed);
        }
Beispiel #4
0
        private void InitApnsBroker(GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment)
        {
            if (string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificatePassword) ||
                string.IsNullOrWhiteSpace(globalSettings.Push.ApnsCertificateThumbprint))
            {
                return;
            }

            var apnsCertificate = CoreHelpers.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();
        }
Beispiel #5
0
        public PushNotifications(bool ProductionEnvironment)
        {
            try
            {
                //Enterprise.IOS.APNSDistributionCertificateName = ConfigurationManager.AppSettings["APNSEnterpriseDistributionCertificateName"];
                //Enterprise.IOS.APNSDevelopmentCertificateName = ConfigurationManager.AppSettings["APNSEnterpriseDistributionCertificateName"];

                initializeConfiguration();

                FCMConfig        = new GcmConfiguration(GCMProjectID, GCMWebAPIKey, Enterprise.Android.PackageName);
                FCMConfig.GcmUrl = GCMURL;

                //By default, Enterprise settings.
                ApnsConfig = new ApnsConfiguration(
                    (ProductionEnvironment) ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                    (ProductionEnvironment) ?
                    AppDomain.CurrentDomain.BaseDirectory + Enterprise.IOS.APNSDistributionCertificateName :
                    AppDomain.CurrentDomain.BaseDirectory + Enterprise.IOS.APNSDevelopmentCertificateName,
                    APNSFilePasswordKey);
            }
            catch (Exception ex)
            {
                Utility.LogError(ex);
            }
        }
Beispiel #6
0
 public NotificationManager()
 {
     _sendTo = new List <NotificationModel>();
     try
     {
         _gcm = GoogleConfig;
     }
     catch
     {
         // ignored
     }
     try
     {
         _apn = AppleConfig;
     }
     catch
     {
         // ignored
     }
     try
     {
         _wns = WindowsConfig;
     }
     catch
     {
         // ignored
     }
 }
Beispiel #7
0
        public void StartServer()
        {
            config     = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "OOPush.p12", "edifier");
            apnsBroker = new ApnsServiceBroker(config);

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

            apnsBroker.Start();
        }
Beispiel #8
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
            server.Start();

            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);
        }
Beispiel #9
0
        static void SendiOS()
        {
            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               "PushSharp-Sandbox.p12", "!Ulises31@2011");

            // 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 MY_DEVICE_TOKENS = new string[1];

            MY_DEVICE_TOKENS[0] = "8EB31300771663950212827E212F7B7FB2B34CA26A2D4F3927AC37E5F7E5DB15";
            // MY_DEVICE_TOKENS[1] = "55EE2DF878CAB0D9A0C3B679C9722CC6E600B86AEDF71CDD853FB4CC5AEC9718";

            foreach (var deviceToken in MY_DEVICE_TOKENS)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse("{\"aps\":{\"badge\":90,\"alert\":\"Jerónimo!!\", \"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();
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Console.WriteLine($"PushVoIP");
            var certificate          = AppDomain.CurrentDomain.BaseDirectory + @"you certificate.p12";
            ApnsConfiguration config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, File.ReadAllBytes(certificate), "you certificate password", false);
            var apnsBroker           = new ApnsServiceBroker(config);

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

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

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

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

            Console.ReadKey();
        }
Beispiel #11
0
        public bool Send(IEnumerable <string> deviceIdList, string message)
        {
            // Configuration (NOTE: .pfx can also be used here)
            //var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "push-cert.p12", "push-cert-pwd");
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, context.AppleCertFileName, context.AppleCertPassword);


            // 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 notificationException)
                    {
                        // 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 deviceIdList)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse("{\"aps\":{\"badge\":7}}")
                });
            }

            // 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(false);
        }
Beispiel #12
0
        public void Send(string APNSToken)
        {
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, @"E:\Projects\Personal\WebAPINikhil\IndianChopstix\IndianChopstix\IC.WebApp\Content\Certificates_Dis.p12", "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;

                        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();

            string MY_DEVICE_TOKENS = "";

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

            // 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();
        }
        private static void SendApplePushNotification(List <string> ApplePushTokens, PushNotification Payload)
        {
            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
                                               PushCertificate, PushCertificatePassword);

            // 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 PushToken in ApplePushTokens)
            {
                // Queue a notification to send
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = PushToken,
                    Payload     = JObject.Parse("{\"aps\" : { \"alert\" : \"Test Notification\" }}")
                });
            }

            // 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();
        }
Beispiel #14
0
        private void ConfigureApnsBroker()
        {
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "E:\\KAZ-Source\\Dhobi\\Dhobi\\Dhobi.Service.Implementation\\calldobi-user-dev-cer.p12", "123456");

            _apnsBroker = new ApnsServiceBroker(config);
            _apnsBroker.OnNotificationFailed    += NotificationFailedApns;
            _apnsBroker.OnNotificationSucceeded += NotificationSent;
        }
        protected override void InitializeService()
        {
            var apnsConfig = new ApnsConfiguration(
                ApnsAppConfiguration.CertificateType == "production" ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                ApnsAppConfiguration.CertificatePath,
                ApnsAppConfiguration.CertificatePwd);

            _apnsServiceBroker = new ApnsServiceBroker(apnsConfig);
        }
Beispiel #16
0
        public static void Main(string[] args)
        {
            Console.WriteLine("starting");

            var config = new ApnsConfiguration(
                ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                "path_to_cert.p12", // in dev mode place the cert in /bin/debug
                "");                // set the password to the cert here if applicable

            Console.WriteLine("Configuring Broker");
            var apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                aggregateEx.Handle(ex =>
                {
                    // See what kind of exception it was to further diagnose
                    var exception = ex as ApnsNotificationException;
                    if (exception != null)
                    {
                        var notificationException = exception;

                        // 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!");
            };

            Console.WriteLine("Starting Broker");
            apnsBroker.Start();

            Console.WriteLine("Queueing Notification");
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = DeviceToken,
                // Say "Hello World", No badge, Use the default system sound
                Payload = JObject.Parse("{\"aps\":{\"alert\": \"Hello World!\", \"badge\":0, \"sound\":\"default\"}}")
            });

            Console.WriteLine("Stopping Broker");
            apnsBroker.Stop();
        }
Beispiel #17
0
        static void PushiOS(string deviceid)
        {
            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               Constants.APNS_P12FILENAME, Constants.PUSH_CERT_PWD);

            // 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 notificationException)
                    {
                        // 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();

            string sendMessage = File.ReadAllText("iOS.json", System.Text.Encoding.UTF8);

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

            // 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();
        }
Beispiel #18
0
        //Envio de notificaciones en iOS
        private bool SendIosNotifications(string title, string message, IEnumerable <PushRegistration> elements, string rootPath)
        {
            var res = true;

            try
            {
                //Obtención de los datos de configuración
                var pathCert = Path.Combine(rootPath, _settings.Value.IOSCertificatePath);
                var pass     = _settings.Value.IOSPassCertificate;
                var type     = _settings.Value.IOSTypeCertificate;
                ApnsConfiguration.ApnsServerEnvironment typeofCert = ApnsConfiguration.ApnsServerEnvironment.Production;
                if (type.ToUpper().Equals("SANDBOX"))
                {
                    typeofCert = ApnsConfiguration.ApnsServerEnvironment.Sandbox;
                }
                var config     = new ApnsConfiguration(typeofCert, pathCert, pass);
                var apnsBroker = new ApnsServiceBroker(config);
                apnsBroker.Start();

                JObject jsonObject;

                //Payload de iOS
                jsonObject = JObject.Parse("{ \"aps\" : { \"alert\" : {\"title\" : \"" + title + "\", \"body\" :\"" + message + "\"} }}");


                foreach (var pushRegistration in elements)
                {
                    //Envio de notificación
                    apnsBroker.QueueNotification(new ApnsNotification
                    {
                        DeviceToken = pushRegistration.Token,
                        Payload     = jsonObject
                    });

                    //Gestión de errores
                    apnsBroker.OnNotificationFailed += (notification, exception) =>
                    {
                        Debug.WriteLine(exception);
                    };

                    //Gestión de exito
                    apnsBroker.OnNotificationSucceeded += (notification) =>
                    {
                        Debug.WriteLine(notification);
                    };
                }
                apnsBroker.Stop();
            }

            catch (Exception e)
            {
                res = false;
            }
            return(res);
        }
        private bool SendNotification(string deviceToken, LoginNotificationModel model)
        {
            // Configuration(NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               _apnsConfiguration.Value.CertificatePath,
                                               _apnsConfiguration.Value.CertificatePassword);

            // 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 notificationException)
                    {
                        // 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 json = model.ToAPNSNotification();
            var test = JObject.Parse("{\"aps\":{ \"alert\":\"Authentication Request\" },\"ApplicationName\":\"Sample .Net App\",\"UserName\": \"[email protected]\",\"ClientIp\": \"192.168.1.10\",\"GeoLocation\": \"Harrisonburg, VA, USA\",\"TransactionId\": \"ea690fa5-8454-4909-902f-3f1b69db9119\",\"Timestamp\": 1577515106.505353}");

            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = deviceToken,
                Payload     = json
                              //Payload = JObject.Parse("{\"aps\":{ \"alert\":\"Authentication Request\" },\"ApplicationName\":\"Sample .Net App\",\"UserName\": \"[email protected]\",\"ClientIp\": \"192.168.1.10\",\"GeoLocation\": \"Harrisonburg, VA, USA\",\"TransactionId\": \"ea690fa5-8454-4909-902f-3f1b69db9119\",\"Timestamp\": 1577515106.505353}")
            });

            // 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(false);
        }
Beispiel #20
0
        public static async Task ApnsPushOne(DeviceMsg device)
        {
            var dataService        = new DataService();
            var apnsServer         = ConfigHelper.GetConfigString("ApnsServer");
            var certificateFile    = ConfigHelper.GetConfigString("ApnspCertificateFile");
            var certificateFilePwd = ConfigHelper.GetConfigString("ApnsCertificateFilePwd");
            var server             = ApnsConfiguration.ApnsServerEnvironment.Sandbox;//0

            if (apnsServer == "1")
            {
                server = ApnsConfiguration.ApnsServerEnvironment.Production;
            }
            var config = new ApnsConfiguration(server, certificateFile, certificateFilePwd);
            // 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 = ex as ApnsNotificationException;
                        var apnsNotification      = notificationException.Notification;
                        var statusCode            = notificationException.ErrorStatusCode;
                        LoggerHelper.IOSPush($"3.Apple Notification Failed!{Environment.NewLine}ID={apnsNotification.Identifier}{Environment.NewLine} Code={statusCode}{Environment.NewLine}Uid={device.uid}{Environment.NewLine}DeviceToken={notification.DeviceToken}{Environment.NewLine}deviceMsgId={device.id}");
                        //Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                    }
                    else
                    {
                        LoggerHelper.IOSPush($"4.Apple Notification Failed for some unknown reason : {ex.InnerException}{Environment.NewLine}deviceMsgId={device.id}");
                    }
                    return(true);
                });
            };

            apnsBroker.OnNotificationSucceeded += (notification) => {
                //LoggerHelper.IOSPush($"Apple Notification Sent!, Uid={device.uid},DeviceToken=" + notification.DeviceToken);
                //发送成功后,需要将msgcount 加1
                var b = dataService.UpdateUserDeviceTokenMsgcount(notification.DeviceToken);

                LoggerHelper.IOSPush($"2.给【{device.uid}】推送的【{device.id}】消息返回结果为:{b}");
            };
            // Start the broker
            apnsBroker.Start();
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = device.devicetoken,
                //Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + device.title + "\",\"badge\":" + device.msgcount + ",\"sound\":\"default\"},\"type\":" + device.msgtype + ",\"content\":" + device.msgcontent + ",\"createdate\":\"" + device.msgtime + "\"}"),
                //将alert分为title和body字段
                Payload = JObject.Parse("{\"aps\":{\"alert\":{\"title\":\"" + device.title + "\",\"body\" : \"" + device.body + "\"},\"badge\":" + device.msgcount + ",\"sound\":\"default\"},\"type\":" + device.msgtype + ",\"content\":" + device.msgcontent + ",\"createdate\":\"" + device.msgtime + "\"}")
            });
            apnsBroker.Stop();
        }
Beispiel #21
0
        public void SendAppleNotification(string deviceToken, string message)
        {
            ////TODO: make relative path
            string pathToCert = @"D:\MyApps\ExpensesWriter\ExpensesWriter.WebApi\Certificates\sergiyExpensesWriter_sandboxCertificate.p12";

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, pathToCert, "se15rge", true);

            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 notificationException)
                    {
                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        Trace.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) => {
                Trace.WriteLine("Apple Notification Sent!");
            };

            // Start the broker
            apnsBroker.Start();

            //foreach (var deviceToken in MY_DEVICE_TOKENS)
            //{
            // Queue a notification to send
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = deviceToken,
                Payload     = JObject.Parse("{ \"aps\" : { \"alert\" : \"" + message + "\", \"badge\" : 1, \"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();
        }
Beispiel #22
0
        public static Task SendAsync(string identifier, JObject payload)
        {
            // https://github.com/Redth/PushSharp
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,
                                               "ApnsCert.p12", "SimplePassword");

            var broker = new ApnsServiceBroker(config);

            var taskCompletionSource = new TaskCompletionSource <bool>();

            // Wire up events
            broker.OnNotificationFailed += (notification, aggregateEx) => {
                aggregateEx.Handle(ex => {
                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException notificationException)
                    {
                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;

                        Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
                        taskCompletionSource.SetException(new Exception($"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}");
                        taskCompletionSource.SetException(new Exception($"Apple Notification Failed for some unknown reason : {ex.InnerException}"));
                    }

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

            broker.OnNotificationSucceeded += (notification) => {
                Console.WriteLine("Apple Notification Sent!");
                taskCompletionSource.SetResult(true);
            };

            // Start the broker
            broker.Start();

            // Queue a notif to send
            broker.QueueNotification(new ApnsNotification()
            {
                DeviceToken = identifier.Replace(" ", ""),
                Payload     = payload
            });

            broker.Stop();

            return(taskCompletionSource.Task);
        }
Beispiel #23
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            ConfigureAuth(app);

            GlobalConfiguration.Configure(WebApiConfig.Register);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            GlobalConfiguration.Configure(SerializationConfig.Register);
            string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/CertificatesLive.p12");

            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
                                               path, "12345", true);

            PushNotifications.Apple = new ApnsServiceBroker(config);
            //PushNotifications.Apple.QueueNotification(new ApnsNotification
            //{
            //DeviceToken = "B770A67EB55213735B65A4AAB9A0D2CC86D7BCE280B33C61BA841C2E0955E28E",
            //Payload = JObject.Parse("{\"aps\":{\"alert\":\"You Just share a media\",\"sound\":\"default\"}}")
            //Payload = JObject.Parse(String.Format("{\"aps\":{\"alert\":\"{0}\",\"badge\":1}}", "myasdasdasd"))
            //});


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

            PushNotifications.Apple.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);
                });
            };

            PushNotifications.Apple.Start();
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter to push notification...");
            Console.ReadKey();

            var config     = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "cert", "password");
            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!");
            };


            apnsBroker.Start();

            // Queue a notification to send
            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = "device-token-should-be-received-from-mobile-device",
                Payload     = JObject.Parse("{\"aps\":{\"badge\":7}}")
            });

            // 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();

            Console.ReadKey();
        }
Beispiel #25
0
        public static void SendWithApns(string deviceToken, string message, int badges)
        {
            var isProduction = string.Compare("true", ConfigurationManager.AppSettings.Get("apns:debug"), StringComparison.OrdinalIgnoreCase) != 0;
            var env          = isProduction ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox;
            var certFileName = ConfigurationManager.AppSettings.Get("apns:certname");
            var file         = HttpContext.Current.Server.MapPath("~/Certs/" + certFileName);
            var certKey      = ConfigurationManager.AppSettings.Get("apns:certkey");
            var config       = new ApnsConfiguration(env, file, certKey);

            var apnsBroker = new ApnsServiceBroker(config);

            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;
                        var error            = ex.InnerException;
                        while (error.InnerException != null)
                        {
                            error = error.InnerException;
                        }
                        Logger.Error($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}, Device={apnsNotification.DeviceToken}, Reason={ex.Message},{error.Message}");
                    }
                    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!");
            };

            apnsBroker.Start();

            apnsBroker.QueueNotification(new ApnsNotification
            {
                DeviceToken = deviceToken,
                Payload     = JObject.Parse($"{{\"aps\":{{\"alert\":\"{message}\",\"badge\":{badges},\"sound\":\"default\"}},\"data\":{{}}}}")
            });
            apnsBroker.Stop();
        }
        private static iOSNotificationEndPoint Create(byte[] certificate, string certificatePassword, ApnsConfiguration.ApnsServerEnvironment environment)
        {
            Throw.IfArgumentNull(certificate, nameof(certificate));
            Throw.IfArgumentNullOrWhitespace(certificatePassword, nameof(certificatePassword));

            iOSNotificationEndPoint endPoint      = new iOSNotificationEndPoint();
            ApnsConfiguration       configuration = new ApnsConfiguration(environment, certificate, certificatePassword);

            endPoint.SetConnection(new ApnsServiceConnection(configuration));

            return(endPoint);
        }
Beispiel #27
0
        static public void PushNotification(Notification pushNotification, List <string> tokens)
        {
            String certificate = System.IO.Directory.GetCurrentDirectory( );

            certificate = certificate + "/Security/Certificates.p12";


            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, certificate, "marcmicha");

            var apnsBroker = new ApnsServiceBroker(config);

            apnsBroker.Start( );

            foreach (var deviceToken in tokens)
            {
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,

                    Payload = pushNotification.Payload( )
                });
            }

            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($"\n!!!!!!!!!!!!!! Apple Notification Sent! {notification.DeviceToken}");
            };


            apnsBroker.Stop( );
        }
Beispiel #28
0
        public static string SendIOSNotify(List <string> devicetokens, IDictionary <string, object> ios, ApnsConfiguration.ApnsServerEnvironment environment, string cetificatePath, string cetificatePwd)
        {
            List <int>    result  = new List <int>();
            var           config  = new ApnsConfiguration(environment, cetificatePath, cetificatePwd);
            var           broker  = new ApnsServiceBroker(config);
            StringBuilder erromsg = new StringBuilder();

            // Wire up events
            broker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                aggregateEx.Handle(ex =>
                {
                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException notificationException)
                    {
                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode       = notificationException.ErrorStatusCode;
                        result.Add((int)statusCode);
                    }
                    else
                    {
                        // Inner exception might hold more useful information like an ApnsConnectionException
                        result.Add(10086);
                        Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
                    }

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

            broker.OnNotificationSucceeded += (notification) =>
            { result.Add(0); };


            // Start the broker
            broker.Start();
            foreach (var deviceToken in devicetokens)
            {
                var paload = Newtonsoft.Json.JsonConvert.SerializeObject(ios);
                broker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload     = JObject.Parse(paload),
                    Expiration  = DateTime.Now.AddDays(2)
                });
            }
            broker.Stop();
            var response = new { ret_code = 0, result = Newtonsoft.Json.JsonConvert.SerializeObject(result) };

            return(Newtonsoft.Json.JsonConvert.SerializeObject(response));
        }
Beispiel #29
0
        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();
        }
        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();
        }