public bool Send(string messageTitle, string messageBody, IEnumerable <IUserDevice> devices) { try { InitializeBrokers(); // Send to iOS devices if (ApnsBroker != null) { devices.Where(d => d.DeviceType.Equals("iOS", caseSensitive: false)).Do(d => { ApnsBroker.QueueNotification(new ApnsNotification { DeviceToken = d.PushNotificationToken, Payload = JObject.FromObject(new { aps = new { alert = new { title = messageTitle, body = messageBody } } }) }); }); } // Send to Android devices if (GcmBroker != null) { var androidDevices = devices.Where(d => d.DeviceType.Equals("Android", caseSensitive: false)).Select(d => d.PushNotificationToken).ToList(); if (androidDevices.Any()) { GcmBroker.QueueNotification(new GcmNotification { RegistrationIds = androidDevices, // This is for multicast messages Notification = JObject.FromObject(new { body = messageBody, title = messageTitle }), Data = JObject.FromObject(new { body = messageBody, title = messageTitle }) }); } } // Send to Windows devices if (WnsBroker != null) { foreach (var uri in devices.Where(d => d.DeviceType.Equals("Windows", caseSensitive: false)).Select(d => d.PushNotificationToken)) { // Queue a notification to send WnsBroker.QueueNotification(new WnsToastNotification { ChannelUri = uri, Payload = new XElement("toast", new XElement("visual", new XElement("binding", new XAttribute("template", "ToastText01"), new XElement("text", new XAttribute("id", "1"), messageBody)))) }); } } return(!(ApnsBroker == null && GcmBroker == null && WnsBroker == null)); } catch (Exception ex) { Logger.Error(ex, ex.Message); return(false); } }
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(string[] deviceTokens, object payload) { if (_config == null) { throw new NullReferenceException("Not configured"); } // instantiating services and configuring them var broker = new ApnsServiceBroker(_config); var feedbackService = new FeedbackService(_config); broker.OnNotificationFailed += NofificationFailed; feedbackService.FeedbackReceived += FeedbackReceived; // start sending notifications broker.Start(); foreach (var token in deviceTokens) { broker.QueueNotification(new ApnsNotification { DeviceToken = token, Payload = JObject.FromObject(payload) }); } broker.Stop(); // check feedback service for expired tokens feedbackService.Check(); }
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(); }
private static async Task SendAsync(MainRepository repo, string title, string message, Predicate <PushNotificationKey> predicate) { var keys = await repo.PushNotificationKey.GetAllAsync(); try { // iOS var push = new ApnsServiceBroker(new ApnsConfiguration( ApnsConfiguration.ApnsServerEnvironment.Production, "/home/sangokukmy/push_notification_product.p12", "test")); push.OnNotificationFailed += (sender, e) => { Logger?.LogError(e, "プッシュ通知送信時にエラーが発生しました"); }; push.Start(); foreach (var key in keys.Where(k => k.Platform == PushNotificationPlatform.iOS && predicate(k))) { push.QueueNotification(new ApnsNotification { DeviceToken = key.Key, Payload = JObject.Parse(@"{""aps"":{""alert"":{""title"":""" + title + @""",""body"":""" + message + @"""},""badge"":1,""sound"":""default""}}"), }); } push.Stop(); } catch (Exception ex) { Logger?.LogError(ex, "プッシュ通知で例外が発生しました"); } try { // Android var config = new GcmConfiguration(Config.Database.GcmServerKey) { GcmUrl = "https://fcm.googleapis.com/fcm/send", }; var gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { Logger?.LogError(aggregateEx, "プッシュ通知送信時にエラーが発生しました"); }; gcmBroker.Start(); gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = keys.Where(k => k.Platform == PushNotificationPlatform.Android && predicate(k)).Select(k => k.Key).ToList(), Notification = JObject.Parse(@"{""title"":""" + title + @""",""body"":""" + message + @"""}"), }); gcmBroker.Stop(); } catch (Exception ex) { Logger?.LogError(ex, "プッシュ通知で例外が発生しました"); } }
public void SendMsg() { List <string> MY_DEVICE_TOKENS = new List <string>(); using (OOContent db = new OOContent()) { db.DBUserDevice.ToList().ForEach(delegate(EUserDevice item) { MY_DEVICE_TOKENS.Add(item.DeviceToken); }); } foreach (var deviceToken in MY_DEVICE_TOKENS) { // 队列发送一个通知 apnsBroker.QueueNotification(new ApnsNotification { DeviceToken = deviceToken,//这里的deviceToken是ios端获取后传递到数据库统一记录管理的,有效的Token才能保证推送成功 Payload = JObject.Parse("{\"aps\":{\"sound\":\"default\",\"badge\":\"1\",\"alert\":\"这是一条群发广告消息推送的测试消息\"}}") }); } Console.WriteLine("Sent"); //停止代理 apnsBroker.Stop(); Console.Read(); }
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 async Task Notification() { var push = new ApnsServiceBroker(new ApnsConfiguration( ApnsConfiguration.ApnsServerEnvironment.Production, "/Users/kmy/Develop/_iOSCerts/push_notification_product.p12", "test")); push.OnNotificationFailed += (sender, e) => { var s = e.ToString(); }; push.Start(); using (var repo = MainRepository.WithRead()) { var keys = await repo.PushNotificationKey.GetAllAsync(); foreach (var key in keys) { push.QueueNotification(new ApnsNotification { DeviceToken = key.Key, Payload = JObject.Parse(@"{""aps"":{""alert"":{""title"":""放置削除ターンが進んでいます"",""body"":""コマンドを入力しないと、あなたの武将データは約 2 日後に削除されます""},""badge"":7}}"), }); } } push.Stop(); }
private void SendApnsMessage(string token, Message message, string trackingId) { if (!IsApnsChannelAccessable) { Log.Warn("APNS channel is not available, notification skipped"); return; } Log.DebugFormat("Send APNS message to token:{0}", token); var payload = new JObject { { "aps", new JObject { { "alert", message.Text }, { "sound", "sound.caf" }, } }, { "tid", message.TriggerId } }; apns.QueueNotification(new ApnsNotification(token) { Tag = trackingId, Payload = payload }); }
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); }
private void QueueAppleNotifications(UserDeviceInfo lstSplit, string pMessage, ApnsServiceBroker push) { try { String jsonPayload = "{ \"aps\" : { \"alert\" : \"" + pMessage + "\",\"badge\" : 0 }}"; _logger.Information("Inside QueueNotifications with message: " + pMessage); if (lstSplit.DeviceToken != null) { if (lstSplit.DeviceToken.Length == 64) { _logger.Information("***INFO*** Queing notification for token :" + lstSplit.DeviceToken.ToString()); push.QueueNotification(new ApnsNotification() { DeviceToken = (lstSplit.DeviceToken), Payload = JObject.Parse(jsonPayload) }); } } } catch (Exception ex) { _logger.Error("***Error***: " + this.GetType().Name + ", Method " + MethodBase.GetCurrentMethod().Name + "****** Error details :" + ex.Message); throw ex; } }
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 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); }
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 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); }
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(); }
public void NotifyDevice(Device device, IEnumerable <Transaction> transactions) { if (device == null) { throw new NullReferenceException("device"); } if (string.IsNullOrEmpty(device.Token)) { throw new ArgumentException("device.token"); } if (transactions == null || !transactions.Any()) { return; } // Get transaction type, check if we have payload content for this type var type = transactions.First().Type; if (!_contents.ContainsKey(type)) { return; } var content = _contents[type]; // Make payload and notification var payload = new Payload { Sound = content.Sound, Badge = 1 }; if (!string.IsNullOrEmpty(content.Body)) { payload.Body = content.Body; } if (!string.IsNullOrEmpty(content.Title)) { payload.Title = content.Title; } var notification = new ApnsNotification { DeviceToken = device.Token, Payload = payload.ToJObject() }; // Send it _broker.QueueNotification(notification); }
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(); }
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(); }
protected void HandleTimer() { lock (lockGuard) { var array = this.Repository.All(); if (array.Length <= 0) { return; } List <ApnsNotification> successArray = new List <ApnsNotification>(); var apnsBroker = new ApnsServiceBroker(this.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; 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!"); successArray.Add(notification); }; // Start the broker apnsBroker.Start(); foreach (var noti in array) { apnsBroker.QueueNotification(noti); } // 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(); } // end of lock return; }
/// <summary> /// 推送消息(从队列中获取待推送消息) /// </summary> public void SendMessage() { // var apnsBroker = GetApnsBroker(); try { var appleCert = File.ReadAllBytes(_appleCertpath); if (appleCert.Length <= 0) { return; } if (_messageList.Count <= 0) { return; } _apnsBroker.Start(); foreach (var item in _messageList) { if (item.Token.Length == 64) { _apnsBroker.QueueNotification(new ApnsNotification(item.Token, JObject.Parse(item.Body))); } } //推送成功,清除队列 _messageList.Clear(); } catch (Exception ex) { _log.ErrorFormat("消息推送异常:{0}", ex); } finally { if (_apnsBroker.IsCompleted) { //消息推送完毕 _apnsBroker.Stop(); _log.Info($"该批iOS端推送共{_messageList.Count}条,已完成请求"); } // 设置定时任务,每1分钟检查请求完成情况 SetTimer(StopTimerPeriod); } }
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(); }
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(); }
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(); }
//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); }
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); }
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(); }
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(); }
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( ); }
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(); }
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)); }
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 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); }