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(); }
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(); }
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"); }
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(); }
/// <summary> /// Send push notification to APN servers /// </summary> /// <param name="notification"></param> private void SendApnPushNotification(PushNotification notification) { if (string.IsNullOrEmpty(notification.DeviceToken)) { throw new ArgumentNullException(nameof(notification.DeviceToken)); } if (string.IsNullOrEmpty(notification.Body)) { throw new ArgumentNullException(nameof(notification.Body)); } apnsServiceBroker.OnNotificationFailed += (pushNotification, aggregateEx) => { if (notification == null) { throw new ArgumentNullException(nameof(pushNotification)); } if (aggregateEx == null) { throw new ArgumentNullException(nameof(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; logger.LogError(ex, $"UserId, {notification.User.UserId}, failed to send push notification." + $"Apple Notification Failed: ID={apnsNotification.Identifier}. Exception Details: Code={statusCode}."); throw new HttpRequestException( $"There was an issue sending a request to apple push notification services. ex: ID={apnsNotification.Identifier}. Exception Details: Code={statusCode} {ex.InnerException}"); } // Inner exception might hold more useful information like an ApnsConnectionException logger.LogError(ex, $"UserId, {notification.User.UserId}, failed to send push notification. Exception details: {ex.InnerException}"); throw new HttpRequestException( $"There was an issue sending a request to apple push notification services. Exception Details: {ex.InnerException}"); }); }; apnsServiceBroker.OnNotificationSucceeded += pushNotification => { if (pushNotification == null) { throw new ArgumentNullException(nameof(pushNotification)); } logger.LogInformation($"UserId, {notification.User.UserId}, had a notification sent"); }; apnsServiceBroker.Start(); apnsServiceBroker.QueueNotification(new ApnsNotification { DeviceToken = notification.DeviceToken, Payload = CreateNotificationPayload(notification) }); apnsServiceBroker.Stop(); }
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); } } }
/// <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(); }
private void SendIOSNotification(Product product) { try { string[] TokenIds = getIOSTokenId(); foreach (var deviceToken in TokenIds) { //8FA978DB52FC2B09D79F039C9928BF4867A01B106689232F8D75234F37D04396 //Get Certificate var certicatePath = (ConfigurationManager.AppSettings["ProdCertificate"]); 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.Sandbox, appleCert, ""); //var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, ""); // 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); //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\":{\"alert\":{\"body\":\"The price lists of " + product.Title + " has been changed.\",\"title\":\"Press Fit Price Lists\"},\"mutable-content\":1},\"sound\":\"default\",\"media-url\":\"" + string.Empty + "\"}"); //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; } }
/// <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; } }
/// <summary> /// Send PushNotification For iOSAndriod app /// </summary> public bool SendPushNotificationForiOS(string deviceToken, string notificationMessage, string notificationType, int totalpendingNotification, byte[] certificateData, int totalbudget, int teamjoinUserID) { StringBuilder traceLog = null; //------------------------------------------------ //IMPORTANT NOTE about Push Service Registrations //------------------------------------------------ ApnsServiceBroker _pushBroker = null; ApnsConfiguration config = null; try { traceLog = new StringBuilder(); traceLog.AppendLine("Start: SendPushNotificationForiOS()"); //------------------------- // APPLE NOTIFICATIONS config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, certificateData, string.Empty); // Create a new broker _pushBroker = new ApnsServiceBroker(config); string urlString = string.Empty; // Wire up events _pushBroker.OnNotificationFailed += NotificationFailed; _pushBroker.OnNotificationSucceeded += NotificationSent; bool isSoundNotify = true; // Start the broker _pushBroker.Start(); // Queue a notification to send _pushBroker.QueueNotification(new PushSharp.Apple.ApnsNotification { DeviceToken = deviceToken, Payload = JObject.Parse("{\"aps\":{" + "\"alert\" : \"" + notificationMessage + "\"," + "\"NotificationType\" : \"" + notificationType + "\"," + "\"TotalPendingChallenges\" : \"" + totalpendingNotification + "\"," + "\"UserID\" : \"" + teamjoinUserID + "\"," + "\"badge\":" + totalbudget + (isSoundNotify ? ",\"sound\":\"sound.caf\"" : "") + "}" + ",\"url\":\"" + urlString + "\"}") }); // Stop the broker, wait for it to finish _pushBroker.Stop(); System.Threading.Thread.Sleep(2000); return(true); } catch (Exception ex) { certificateData = null; config = null; _pushBroker = null; LogManager.LogManagerInstance.WriteErrorLog(ex); return(false); } finally { traceLog.AppendLine("End:SendPushNotificationForiOS --- " + DateTime.Now.ToLongDateString()); LogManager.LogManagerInstance.WriteTraceLog(traceLog); certificateData = null; config = null; _pushBroker = null; traceLog = null; } }
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(); }
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")); }
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); }
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; }
/// ================== 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(); }
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); }
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 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; } }
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); }
/// <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); }
public override void Start() { _apnsServiceBroker.Start(); }
/// <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); }
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 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); }
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); }
public static void Main(string[] args) { using (var db = new TransafeRxEntities()) { try { var deviceTokenUsers = db.GetAllDeviceTokensWithUser().ToList(); //Where(x => x.UserId == "3fd5b550-c517-4ff5-9825-c55b37d50175").ToList(); var allMedicationsNotTaken = db.GetAllMedicationsNotTakenWindow(61).ToList(); //Where(x => x.UserId == "3fd5b550-c517-4ff5-9825-c55b37d50175").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 medicationNotTaken in allMedicationsNotTaken) { GetAllDeviceTokensWithUser_Result user = deviceTokenUsers.Where(x => x.UserId == medicationNotTaken.UserId).FirstOrDefault(); if (user == null) { continue; } if (user.AdmissionTypeId.HasValue) { if (user.AdmissionTypeId.Value == 1) { db.AddMedicationActivityAdmitted(user.UserId, medicationNotTaken.ScheduleId, medicationNotTaken.UserMedicationId); continue; } } List <GetAllDeviceTokensWithUser_Result> users = deviceTokenUsers.Where(x => x.UserId == medicationNotTaken.UserId).ToList(); //GetAllDeviceTokensWithUser_Result deviceUser = deviceTokenUsers.Where(x => x.UserId == medicationNotTaken.UserId).Last(); foreach (var deviceUser in users) { if (!string.IsNullOrEmpty(deviceUser.Token)) { string reminder = ""; int section = 0; if (medicationNotTaken.ScheduleTime.Hours.Equals(DateTime.Now.Hour)) { section = medicationNotTaken.ScheduleTime.Hours; if (medicationNotTaken.ScheduleTime.Hours < 12) { reminder = String.Format("Time to take your {0} AM medication(s)!", medicationNotTaken.ScheduleTime.Hours); } else if (medicationNotTaken.ScheduleTime.Hours > 12 && medicationNotTaken.ScheduleTime.Hours < 24) { reminder = String.Format("Time to take your {0} PM medication(s)!", (medicationNotTaken.ScheduleTime.Hours - 12)); } else if (medicationNotTaken.ScheduleTime.Hours == 12) { reminder = String.Format("Time to take your 12 PM medication(s)!"); } else { reminder = String.Format("Time to take your {0} AM medication(s)!", (medicationNotTaken.ScheduleTime.Hours - 12)); } try { apnsBroker.QueueNotification(new ApnsNotification { DeviceToken = deviceUser.Token, Payload = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"anticipate.mp3\",\"alert\":{\"title\":\"" + "Medication Reminder" + "\",\"body\":\"" + reminder + "\"}},\"Section\":\"" + section + "\"}") }); db.AddMessage(medicationNotTaken.ScheduleId, null, deviceUser.TokenId); } catch (Exception e) { Console.WriteLine(e.StackTrace); db.AddMessage(medicationNotTaken.ScheduleId, e.StackTrace, deviceUser.TokenId); } } } } } //foreach (var user in deviceTokenUsers) //{ // List<GetAllMedicationsNotTakenWindow_Result> medicationsNotTaken = allMedicationsNotTaken.Where(x => x.UserId == user.UserId).ToList(); // if (user.AdmissionTypeId.HasValue) // { // if (user.AdmissionTypeId.Value == 1) // { // foreach (GetAllMedicationsNotTakenWindow_Result medication in medicationsNotTaken) // { // db.AddMedicationActivityAdmitted(user.UserId, medication.ScheduleId, medication.UserMedicationId); // } // break; // } // } // if (!string.IsNullOrEmpty(user.Token)) // { // string reminder = ""; // int section = 0; // if (medicationsNotTaken.Count > 0) // { // List<GetAllMedicationsNotTakenWindow_Result> MedicationsToTake = new List<GetAllMedicationsNotTakenWindow_Result>(); // foreach (var medication in medicationsNotTaken) // { // if (medication.ScheduleTime.Hours.Equals(DateTime.Now.Hour)) // { // section = medication.ScheduleTime.Hours; // if (medication.ScheduleTime.Hours < 12) // { // reminder = String.Format("Time to take your {0} AM medication(s)!", medication.ScheduleTime.Hours); // } // else if (medication.ScheduleTime.Hours > 12 && medication.ScheduleTime.Hours < 24) // { // reminder = String.Format("Time to take your {0} PM medication(s)!", (medication.ScheduleTime.Hours - 12)); // } // else if(medication.ScheduleTime.Hours == 12) // { // reminder = String.Format("Time to take your 12 PM medication(s)!"); // } // else // { // reminder = String.Format("Time to take your {0} AM medication(s)!", (medication.ScheduleTime.Hours - 12)); // } // MedicationsToTake.Add(medication); // } // } // if (MedicationsToTake.Count() > 0) // { // try // { // apnsBroker.QueueNotification(new ApnsNotification // { // DeviceToken = user.Token, // Payload = JObject.Parse("{\"aps\":{\"content-available\":\"1\",\"sound\":\"anticipate.mp3\",\"alert\":{\"title\":\"" + "Medication Reminder" + "\",\"body\":\"" + reminder + "\"}},\"Section\":\"" + section + "\"}") // }); // foreach (GetAllMedicationsNotTakenWindow_Result medication in MedicationsToTake) // { // db.AddMessage(medication.ScheduleId, null, user.TokenId); // } // } // catch (Exception e) // { // Console.WriteLine(e.StackTrace); // foreach (GetAllMedicationsNotTakenWindow_Result medication in MedicationsToTake) // { // db.AddMessage(medication.ScheduleId, e.StackTrace, user.TokenId); // } // } // } // } // } //} var fbs = new FeedbackService(config); fbs.FeedbackReceived += (string deviceToken, DateTime timestamp) => { //remove token from database //timestamp is time token was expired Console.WriteLine(String.Format("FeedbackReceived: {0} : {1}"), deviceToken, timestamp.ToString()); GetAllDeviceTokensWithUser_Result token = deviceTokenUsers.Where(x => x.Token == deviceToken).FirstOrDefault(); if (token != null) { db.UpdateDeviceTokenExpired(token.TokenId, true); } }; fbs.Check(); 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 Medication Notification Service. Please see below for details.\r\n"; message.Body += "Stack Trace: " + e.StackTrace + "\r\n"; message.Subject = "TransafeRx Medication Notification Service Error Report"; client.Send(message); message.Dispose(); } } }