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, "プッシュ通知で例外が発生しました"); } }
void InitializeGoogleBroker() { if (GcmBroker != null) { return; } if (Config.Get("PushNotification:Google:SenderId").IsEmpty()) { return; } var config = new GcmConfiguration(Config.Get("PushNotification:Google:SenderId"), Config.Get("PushNotification:Google:AuthToken"), null) { GcmUrl = "https://fcm.googleapis.com/fcm/send" }; GcmBroker = new GcmServiceBroker(config); GcmBroker.OnNotificationFailed += (notification, aggregateEx) => HandleError(GcmBroker, aggregateEx); GcmBroker.OnNotificationSucceeded += notification => { Logger.Debug("Notification has been sent successfully: " + notification); }; GcmBroker.Start(); }
static void InitializeGoogleBroker() { if (GcmBroker != null) { return; } if (!Config.IsDefined("PushNotification:Google:SenderId")) { return; } var config = new GcmConfiguration(Config.Get("PushNotification:Google:SenderId"), Config.Get("PushNotification:Google:AuthToken"), null) { GcmUrl = "https://fcm.googleapis.com/fcm/send" }; GcmBroker = new GcmServiceBroker(config); GcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { LogError(GcmBroker, ex); return(true); // Mark it as handled }); }; GcmBroker.OnNotificationSucceeded += notification => { Olive.Log.For <PushNotificationService>().Debug("Notification has been sent successfully: " + notification); }; GcmBroker.Start(); }
public void Send(NotificationPayload notification, IDevice device) { // Configuration var config = new GcmConfiguration(senderId, authToken, packageName); // Make the broker use Firebase config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += onFailure; gcmBroker.OnNotificationSucceeded += onSuccess; var payload = new AndroidNotification(notification); // Start the broker gcmBroker.Start(); // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { To = device.Token, Data = JObject.FromObject(payload) }); // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public void Gcm_Send_Single () { var succeeded = 0; var failed = 0; var attempted = 0; var config = new GcmConfiguration (Settings.Instance.GcmSenderId, Settings.Instance.GcmAuthToken, null); var broker = new GcmServiceBroker (config); broker.OnNotificationFailed += (notification, exception) => { failed++; }; broker.OnNotificationSucceeded += (notification) => { succeeded++; }; broker.Start (); foreach (var regId in Settings.Instance.GcmRegistrationIds) { attempted++; broker.QueueNotification (new GcmNotification { RegistrationIds = new List<string> { regId }, Data = JObject.Parse ("{ \"somekey\" : \"somevalue\" }") }); } broker.Stop (); Assert.AreEqual (attempted, succeeded); Assert.AreEqual (0, failed); }
private void sendPushToAndroid(string deviceID, string message) { var config = new GcmConfiguration("1034425131442", "AIzaSyDlrjgMMYo5Om11e-F5vxZFfif37v0iLlo", null); var broker = new GcmServiceBroker(config); broker.OnNotificationFailed += new PushSharp.Core.NotificationFailureDelegate <GcmNotification>(_pushBroker_OnNotificationFailed); //broker.OnNotificationSucceeded += (notification) => //{ // succeeded++; //}; broker.Start(); foreach (var device in _unitOfWork.DeviceRepository.All.ToList()) { broker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { device.RegistrationId }, Data = JObject.Parse("{ \"message\" : \"" + message + "\" }") }); } broker.Stop(); }
public void RunPushNotificationAll(List <Volunteer> userList, JObject data, JObject notification_) { List <string> registrationIDs = new List <string>(); foreach (var item in userList) { //ignore nulls if (item.RegId != "" && item.RegId != "errorKey") { registrationIDs.Add(item.RegId); } } // Configuration var config = new GcmConfiguration("AIzaSyDQfirNkIkUKNy9B2irYhb8CV6pYpIVBOQ"); config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { //Console.WriteLine("GCM Notification Failed!"); }; gcmBroker.OnNotificationSucceeded += (notification) => { //Console.WriteLine("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); if (notification_ == null) { gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = registrationIDs, Data = data }); } else { gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = registrationIDs, Notification = notification_, Data = data }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public void Gcm_Send_Single() { var succeeded = 0; var failed = 0; var attempted = 0; var config = new GcmConfiguration(Settings.Instance.GcmSenderId, Settings.Instance.GcmAuthToken, null); var broker = new GcmServiceBroker(config); broker.OnNotificationFailed += (notification, exception) => { failed++; }; broker.OnNotificationSucceeded += (notification) => { succeeded++; }; broker.Start(); foreach (var regId in Settings.Instance.GcmRegistrationIds) { attempted++; broker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = JObject.Parse("{ \"somekey\" : \"somevalue\" }") }); } broker.Stop(); Assert.AreEqual(attempted, succeeded); Assert.AreEqual(0, failed); }
public void RunPushNotificationAll(List <User> userList, myPushNot pushNot) { List <string> registrationIDs = new List <string>(); foreach (var item in userList) { //ignore nulls if (item.PushKey != "" && item.PushKey != "no-reg-id") { registrationIDs.Add(item.PushKey); } } // Configuration var config = new GcmConfiguration("AIzaSyALPWklqgv9OjE5KcZTG-yFi5UznpXD7fE"); config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { Console.WriteLine("GCM Notification Failed!"); }; gcmBroker.OnNotificationSucceeded += (notification) => { Console.WriteLine("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var regId in registrationIDs) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = JObject.Parse( "{" + "\"title\" : \"" + pushNot.Title + "\"," + "\"message\" : \"" + pushNot.Message + "\"," + "\"info\" : \" Optional \"," + "\"content-available\" : \"" + "1" + "\"" + "}") }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
private void AndroidSend(List <Lizay.dll.entity.USERS> users, string Message, string Header, string Url) { var task = Task.Factory.StartNew( state => { var context = (HttpContext)state; var token = ConfigurationManager.AppSettings["GoogleKeyForParent"]; if (users.Count <= 0) { return; } var config = new GcmConfiguration("", token, null); var gcmBroker = new GcmServiceBroker(config); gcmBroker.Start(); foreach (var item in users) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { item.DEVICE_ID }, Data = JObject.Parse("{\"alert\":\"" + Message + "\",\"badge\":0,\"sound\":\"sound.caf\",\"Header\":\"" + Header + "\",\"Text\":\"" + Message + "\",\"Url\":\"" + Url + "\"}") }); } gcmBroker.Stop(); }, HttpContext.Current); }
public static string SendPushNotificationAndroidOld(string DeviceToken, string Title, string Message) { string result = string.Empty; try { var config = new GcmConfiguration(null, AndroidAppKey, null); var gcmbroker = new GcmServiceBroker(config); gcmbroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; var gcmNotification = notificationException.Notification; var description = notificationException.Description; result = $"Android Notification Failed: ID={ gcmNotification.MessageId}, Desc={ description}"; } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; //foreach(var SucceededNotification in multicastException.Succeeded) //{ } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; result = $"Android Notification Failed: ID={ n.MessageId}"; } } else { result = $"Notification failed with unknown reason"; } return(true); }); }; gcmbroker.OnNotificationSucceeded += (notification) => { result = "Success"; }; gcmbroker.Start(); gcmbroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { DeviceToken }, Data = JObject.Parse(("{\"aps\": {\"badge\": 1, \"sound\": \"oven.caf\", \"alert\":\"" + (Message + "\"}}"))) }); gcmbroker.Stop(); } catch (Exception ex) { result = ex.Message; } return(result); }
public IssueController(ApplicationDbContext context, IHubContext <IndexHub> hub) { this.hub = hub; this.context = context; var config = new GcmConfiguration("915208635165-f4kbjf9f2hrc8t5p5rncbim11465j2hg", "AIzaSyDP4et_tj70DN-lihb3xGwKlOuSRIImtFI", null); // Create a new broker var gcmBroker = new GcmServiceBroker(config); gcmBroker.Start(); }
public PushService() { _config = new GcmConfiguration(gcmSenderId, authToken, null); _broker = new GcmServiceBroker(_config); // Wire up events _broker.OnNotificationSucceeded += (notification) => { Console.WriteLine("Notification Sent!"); }; _broker.Start(); }
public void SendAndroidNotification(string deviceToken, string message) { GcmConfiguration configuration = new GcmConfiguration("AAAAByfoliw:APA91bH3Av2zEoMHQsQiSphktNSxOnyyU4hC2sT7A9PBA8iAM0I-qt527Cx7vdOM-8tAGmd2t8oJVJ1bX3kELi-IDmO1wX2AgUbb_miqR6m6TR6-DbSJEf_rgKI68moqhHYAgWymWCx8"); configuration.GcmUrl = "https://fcm.googleapis.com/fcm/send"; var gcmBroker = new GcmServiceBroker(configuration); GcmNotification notif = new GcmNotification(); notif.Notification = JObject.Parse("{ \"data\" : {\"message\":\"" + "From " + "SergeUser" + ": " + message + "\"}}"); notif.RegistrationIds = new List <string>() { deviceToken }; // Wire up events gcmBroker.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($"Android Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}"); } else { // Inner exception might hold more useful information like an ApnsConnectionException Console.WriteLine($"Android Notification Failed for some unknown reason : {ex.InnerException}"); } // Mark it as handled return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { Trace.WriteLine("Android Notification Sent!"); }; gcmBroker.Start(); gcmBroker.QueueNotification(notif); gcmBroker.Stop(); //.ForDeviceRegistrationId(deviceToken).WithJson(JsonConvert.SerializeObject(message)); //_push.QueueNotification(notif); }
public async Task Notify <T>(IEnumerable <string> registrationIds, T notificationData, string notificationType = null) where T : class { brokerService.Start(); foreach (var regId in registrationIds) { // Queue a notification to send brokerService.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = (JObject)JToken.FromObject(notificationData) }); } brokerService.Stop(); }
public void PushNotification(ICollection <string> registrationIds, dynamic notificationData) { var config = new GcmConfiguration(this._gcmSenderId, this._authToken, null); //Create our push services broker var gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationSucceeded += GcmBroker_OnNotificationSucceeded; gcmBroker.OnNotificationFailed += GcmBroker_OnNotificationFailed; // Start the broker gcmBroker.Start(); this.QueueNotofication(registrationIds, notificationData, gcmBroker); gcmBroker.Stop(); }
public void SendFCMNotification(List <string> registerationIDs, string message, string title, int?notificationsCount, Dictionary <string, object> addedData, List <NotificationActionModel> actions, bool withAlert = true) { //initialize the broker InitializeGcmBroker(); //Wire Up Events WireUpGCMEvents(); // Start the broker gcmBroker.Start(); //prepare data QueueGcmNotification(registerationIDs, message, title, notificationsCount, addedData, actions, withAlert); // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public async Task SendWebGCMPushNotification(List <AdminTokens> adminTokens, string Title, string Text, string click_action) { try { if (adminTokens.Count() == 0)//it means their is no device no need to run the below code { return; } NotificationWebModel msgModel = new NotificationWebModel(); foreach (var device in adminTokens.Where(x => x.IsActive)) { GcmServiceBroker gcmBroker; msgModel.body = Text; msgModel.title = Title; msgModel.click_action = click_action; gcmBroker = new GcmServiceBroker(FCMWebConfig); gcmBroker.OnNotificationFailed += FCMWebNotificationFailed; gcmBroker.OnNotificationSucceeded += FCMWebNotificationSuccess; gcmBroker.Start(); gcmBroker.QueueNotification( new GcmNotification { RegistrationIds = new List <string> { device.Token }, Priority = GcmNotificationPriority.High, Data = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(msgModel)) }); gcmBroker.Stop(); gcmBroker.OnNotificationFailed -= FCMWebNotificationFailed; gcmBroker.OnNotificationSucceeded -= FCMWebNotificationSuccess; } } catch (Exception ex) { Utility.LogError(ex); } }
private void InitGcmBroker(GlobalSettings globalSettings) { if (string.IsNullOrWhiteSpace(globalSettings.Push.GcmSenderId) || string.IsNullOrWhiteSpace(globalSettings.Push.GcmApiKey) || string.IsNullOrWhiteSpace(globalSettings.Push.GcmAppPackageName)) { return; } var gcmConfig = new GcmConfiguration(globalSettings.Push.GcmSenderId, globalSettings.Push.GcmApiKey, globalSettings.Push.GcmAppPackageName); _gcmBroker = new GcmServiceBroker(gcmConfig); _gcmBroker.OnNotificationFailed += GcmBroker_OnNotificationFailed; _gcmBroker.OnNotificationSucceeded += (notification) => { Debug.WriteLine("GCM Notification Sent!"); }; _gcmBroker.Start(); }
public void RunPushNotificationOne(User user, JObject data) { // Configuration var config = new GcmConfiguration("AIzaSyALPWklqgv9OjE5KcZTG-yFi5UznpXD7fE"); config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { //Console.WriteLine("GCM Notification Failed!"); }; gcmBroker.OnNotificationSucceeded += (notification) => { //Console.WriteLine("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { user.PushKey }, Data = data }); // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public static void EnviarNotificacionPushFCM(List <DtoDispositivo> dispositivos, string titulo, string mensaje) { // Configuration GCM (use this section for GCM) var config = new GcmConfiguration("AIzaSyCiLge3SyEbl29Qo0B5fLriG1JWrnELANY", "AAAA5bNhwuU:APA91bExp8oylCzDRjFq5qN0OpmNjslf4m_R3jbIWNN_j9kbhCdpCx_tUXnmiRc6GnwbCAi7z5Q2ougftKfuawSZSUfEdImHVBvfdtmmJAK3ykix7CS6wjxS3DbwvbHzKTIDGInmT_RC", null); // Configuration FCM (use this section for FCM) // var config = new GcmConfiguration("APIKEY"); // config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // var provider = "FCM"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationSucceeded += (notification) => { Console.WriteLine("{provider} Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var regId in dispositivos) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId.TokenPush }, Notification = JObject.Parse("{ \"body\":\"" + mensaje + "\",\"title\": \"" + titulo + "\",\"sound\": \"default\",\"silent\":false,\"content_available\" : true }"), Data = JObject.Parse("{ \"message\" : \"my_custom_value\",\"other_key\" : true,\"body\":\"test\" }") }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public void Send(NotificationPayload notification, IEnumerable <IDevice> devices) { // Configuration var config = new GcmConfiguration(senderId, authToken, packageName); // Make the broker use Firebase config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += onFailure; gcmBroker.OnNotificationSucceeded += onSuccess; var payload = new AndroidNotification(notification); // Make chuncks of 1000 devices that is the max quote supported var chuncks = devices.ToList().ChunkBy(1000); // Start the broker gcmBroker.Start(); foreach (var chunck in chuncks) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = devices.Select(d => d.Token).ToList <string>(), Data = JObject.FromObject(payload) }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
/// <summary> /// Send push message with custom json. /// </summary> /// <param name="userGCMKey">GCM registration key</param> /// <param name="collapseKey">Unique Id that identify the push desination page.</param> /// <param name="json">JSON for extra fields including message</param> /// <param name="callback">callback function</param> public void SendWithJSon(string userGCMKey, string collapseKey, string message, string json, Action <Result> callback) { try { var config = new GcmConfiguration(SenderID, AuthToken, null); var broker = new GcmServiceBroker(config); broker.OnNotificationFailed += (notification, exception) => { callback(new Result { status = "FAIL", message = exception.Message }); }; broker.OnNotificationSucceeded += (notification) => { callback(new Result { status = "Success", message = "" }); }; broker.Start(); broker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { userGCMKey }, Data = JObject.Parse("{\"message\":\"" + message + "\",\"payload\":" + json + "}"), CollapseKey = collapseKey, TimeToLive = 108, DelayWhileIdle = true }); broker.Stop(); } catch (Exception ex) { callback(new Result { status = "FAIL", message = ex.Message }); } }
private void RegisterGcmChannel() { try { var gcmKey = ConfigurationManager.AppSettings["gcmKey"]; if (!string.IsNullOrEmpty(gcmKey)) { Log.DebugFormat("Start GCM channel with key {0}", gcmKey.Substring(0, 5)); gcm = new GcmServiceBroker(new GcmConfiguration(gcmKey)); gcm.OnNotificationFailed += Gcm_OnNotificationFailed; gcm.OnNotificationSucceeded += Gcm_OnNotificationSucceeded; gcm.Start(); } else { Log.Warn("GCM channel has not started due to configuration"); } } catch (Exception e) { Log.Error("Failed to start GCM channel", e); gcm = null; } }
private async Task <bool> SendNotificationToAndroidDevice(Notification notification) { var devices = await _deviceStausRepository.GetDeviceStatus(notification.ReceiverUserId, (int)DeviceOs.Android); if (devices == null || devices.Count < 1) { return(false); } var payloadToSend = JsonConvert.SerializeObject(new NotificationBasicInformation { Type = notification.Type, message = notification.Text, title = notification.Title, MessageId = notification.MessageId }); ConfigureGcmBroker(); _gcmBroker.Start(); SendAndroidNotification(devices.Select(s => s.RegistrationId).ToList(), payloadToSend); var updated = await _notificationRepository.UpdateNotificationStatus(notification.NotificationId, (int)NotificationStatus.Sent); _gcmBroker.Stop(); return(true); }
private static void SendAndroidPushNotification(List <string> AndroidPushTokens, PushNotification Payload) { // Configuration var config = new GcmConfiguration("GCM-SENDER-ID", "AIzaSyByUHzXZY1lWQU34ssv3a9R3BSxJJALkqk", null); // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; // Deal with the failed notification var gcmNotification = notificationException.Notification; var description = notificationException.Description; Console.WriteLine($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { Console.WriteLine($"GCM Notification Succeeded: ID={succeededNotification.MessageId}"); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; Console.WriteLine($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Message}"); } } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; Console.WriteLine($"Device RegistrationId Expired: {oldId}"); if (!string.IsNullOrWhiteSpace(newId)) { // If this value isn't null, our subscription changed and we should update our database Console.WriteLine($"Device RegistrationId Changed To: {newId}"); } } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date Console.WriteLine($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); } else { Console.WriteLine("GCM Notification Failed for some unknown reason"); } // Mark it as handled return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { Console.WriteLine("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var PushToken in AndroidPushTokens) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { PushToken }, Data = JObject.Parse(JsonConvert.SerializeObject(Payload)) }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
private void SendToGcm(string token, string message) { try { var gcmBroker = new GcmServiceBroker(_gcm); gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { var exception = ex as GcmNotificationException; if (exception != null) { var notificationException = exception; var gcmNotification = notificationException.Notification; var description = notificationException.Description; throw new Exception(JsonConvert.SerializeObject(new { GcmMessageId = gcmNotification.MessageId, Description = description })); } var resultException = ex as GcmMulticastResultException; if (resultException != null) { var multicastException = resultException; foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; throw new Exception(JsonConvert.SerializeObject(new { GcmMessageId = n, Description = e })); } } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; throw new Exception(JsonConvert.SerializeObject(new { Description = $"GCM ID Changed : old-{oldId}\t new-{newId}" })); } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; throw new Exception(JsonConvert.SerializeObject(new { Description = $"Limitation Exceeds!! Please try after {retryException.RetryAfterUtc.ToLocalTime()}" })); } else { throw new Exception(JsonConvert.SerializeObject(new { Description = "Unknown Error Occurs !!!" })); } return(true); }); }; gcmBroker.OnNotificationSucceeded += notification => { }; gcmBroker.Start(); gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { token }, Data = JObject.Parse(message) }); gcmBroker.Stop(); } catch (Exception e) { throw new Exception(e.Message, e); } }
//Envio de notificaciones en Android private bool SendAndroidNotification(string title, string message, IEnumerable <PushRegistration> elements) { var res = true; try { var config = new GcmConfiguration(null, _settings.Value.AndroidToken, null) { GcmUrl = "https://fcm.googleapis.com/fcm/send" }; var gcmBroker = new GcmServiceBroker(config); //Evento de errores gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; // Deal with the failed notification var gcmNotification = notificationException.Notification; var description = notificationException.Description; Console.WriteLine($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { Console.WriteLine($"GCM Notification Succeeded: ID={succeededNotification.MessageId}"); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; Console.WriteLine($"GCM Notification Failed: ID={n.MessageId}, Desc={message}"); } } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; Console.WriteLine($"Device RegistrationId Expired: {oldId}"); if (!string.IsNullOrWhiteSpace(newId)) { // If this value isn't null, our subscription changed and we should update our database Console.WriteLine($"Device RegistrationId Changed To: {newId}"); } } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date Console.WriteLine($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); } else { Console.WriteLine("GCM Notification Failed for some unknown reason"); } // Mark it as handled return(true); }); }; //Evento de Success gcmBroker.OnNotificationSucceeded += (notification) => { Console.WriteLine("GCM Notification Sent!"); }; gcmBroker.Start(); //Payload de Android var jsonObject = JObject.Parse( "{" + "\"title\" : \"" + title + "\"," + "\"body\" : \"" + message + "\"," + "\"sound\" : \"mySound.caf\"" + "}"); foreach (var element in elements) { // Envio de notificación gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { element.Token }, Notification = jsonObject }); } gcmBroker.Stop(); } catch (Exception) { res = false; } return(res); }
public void Android_PushNotification(List <string> deviceIds, string message) { //Send message to devices // Configuration var SENDER_ID = System.Configuration.ConfigurationManager.AppSettings["GCM-SENDER-ID"]; var AUTH_TOKEN = System.Configuration.ConfigurationManager.AppSettings["AUTH-TOKEN"]; var config = new GcmConfiguration(SENDER_ID, AUTH_TOKEN, null); config.GcmUrl = "https://android.googleapis.com/gcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; // Deal with the failed notification var gcmNotification = notificationException.Notification; var description = notificationException.Description; //Console.WriteLine($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { //Console.WriteLine($"GCM Notification Failed: ID={succeededNotification.MessageId}"); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; //Console.WriteLine($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Message}"); } } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; //Console.WriteLine($"Device RegistrationId Expired: {oldId}"); if (!string.IsNullOrWhiteSpace(newId)) { // If this value isn't null, our subscription changed and we should update our database //Console.WriteLine($"Device RegistrationId Changed To: {newId}"); } } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date //Console.WriteLine($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); } else { //Console.WriteLine("GCM Notification Failed for some unknown reason"); } // Mark it as handled return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { //Console.WriteLine("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var regId in deviceIds) { if (!string.IsNullOrEmpty(regId)) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = JObject.Parse("{\"Message\" : \"" + message + "\", \"IsDriver\" : \"false\", \"Create_At\": \"" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + "\"}"), Priority = GcmNotificationPriority.High, TimeToLive = 108, DelayWhileIdle = true }); } } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public AndroidPushMessageSender(ApplicationType?appType) { if (appType == ApplicationType.Tablet) { config = new GcmConfiguration(Options.GCMSenderIdTablet, Options.DeviceAuthTokenTablet, null); } else { config = new GcmConfiguration(Options.GCMSenderIdMobile, Options.DeviceAuthTokenMobile, null); } gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; var gcmNotification = notificationException.Notification; var description = notificationException.Description; notificationService.Unsubscribe(devToken, userId); log.Error(string.Format("GCM Notification Failed: ID={0}, Desc={1}", gcmNotification.MessageId, description)); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { log.Error(string.Format("GCM Notification Failed: ID={0}", succeededNotification.MessageId)); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; log.Error(string.Format("GCM Notification Failed: ID={0}, Desc={1}", n.MessageId, e.InnerException)); } notificationService.Unsubscribe(devToken, userId); } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; log.Error(string.Format("Device RegistrationId Expired: {0}", oldId)); log.Error(string.Format("Device RegistrationId Changed To: {0}", newId)); if (!string.IsNullOrWhiteSpace(newId)) { notificationService.Unsubscribe(oldId, userId); log.Error(string.Format("Device RegistrationId Changed To: {0}", newId)); } else { notificationService.Unsubscribe(oldId, userId); } } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; log.Error(string.Format("GCM Rate Limited, don't send more until after {0}", retryException.RetryAfterUtc)); } else { log.Error("GCM Notification Failed for some unknown reason"); } log.Error("Failed for:" + string.Join(",", notification.RegistrationIds)); return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { log.Info("Success for:" + string.Join(",", notification.RegistrationIds)); }; gcmBroker.Start(); }
private void InitGcmBroker(GlobalSettings globalSettings) { if(string.IsNullOrWhiteSpace(globalSettings.Push.GcmSenderId) || string.IsNullOrWhiteSpace(globalSettings.Push.GcmApiKey) || string.IsNullOrWhiteSpace(globalSettings.Push.GcmAppPackageName)) { return; } var gcmConfig = new GcmConfiguration(globalSettings.Push.GcmSenderId, globalSettings.Push.GcmApiKey, globalSettings.Push.GcmAppPackageName); _gcmBroker = new GcmServiceBroker(gcmConfig); _gcmBroker.OnNotificationFailed += GcmBroker_OnNotificationFailed; _gcmBroker.OnNotificationSucceeded += (notification) => { Debug.WriteLine("GCM Notification Sent!"); }; _gcmBroker.Start(); }
private static void sendGCM(string[] deviceTokens, string text, string type) { // Configuration var config = new GcmConfiguration("GCM-SENDER-ID", "AUTH-TOKEN", null); // Create a new broker var gcmBroker = new GcmServiceBroker(config); // Wire up events gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { /*aggregateEx.Handle (ex => { * * // See what kind of exception it was to further diagnose * if (ex is GcmNotificationException) { * var notificationException = (GcmNotificationException)ex; * * // Deal with the failed notification * var gcmNotification = notificationException.Notification; * var description = notificationException.Description; * * Console.WriteLine ($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); * } else if (ex is GcmMulticastResultException) { * var multicastException = (GcmMulticastResultException)ex; * * foreach (var succeededNotification in multicastException.Succeeded) { * Console.WriteLine ($"GCM Notification Failed: ID={succeededNotification.MessageId}"); * } * * foreach (var failedKvp in multicastException.Failed) { * var n = failedKvp.Key; * var e = failedKvp.Value; * * Console.WriteLine ($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Description}"); * } * * } else if (ex is DeviceSubscriptionExpiredException) { * var expiredException = (DeviceSubscriptionExpiredException)ex; * * var oldId = expiredException.OldSubscriptionId; * var newId = expiredException.NewSubscriptionId; * * Console.WriteLine ($"Device RegistrationId Expired: {oldId}"); * * if (!string.IsNullOrWhitespace (newId)) { * // If this value isn't null, our subscription changed and we should update our database * Console.WriteLine ($"Device RegistrationId Changed To: {newId}"); * } * } else if (ex is RetryAfterException) { * var retryException = (RetryAfterException)ex; * // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date * Console.WriteLine ($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); * } else { * Console.WriteLine ("GCM Notification Failed for some unknown reason"); * } * * // Mark it as handled * return true; * });*/ }; gcmBroker.OnNotificationSucceeded += (notification) => { //Console.WriteLine ("GCM Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var regId in deviceTokens) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = JObject.Parse("{ \"message\" : \"" + text + "\" }") }); } // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker gcmBroker.Stop(); }
public AndroidPushMessageSender(ApplicationType? appType) { if (appType == ApplicationType.Tablet) config = new GcmConfiguration(Options.GCMSenderIdTablet, Options.DeviceAuthTokenTablet, null); else config = new GcmConfiguration(Options.GCMSenderIdMobile, Options.DeviceAuthTokenMobile, null); gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { if (ex is GcmNotificationException) { var notificationException = (GcmNotificationException)ex; var gcmNotification = notificationException.Notification; var description = notificationException.Description; notificationService.Unsubscribe(devToken, userId); log.Error(string.Format("GCM Notification Failed: ID={0}, Desc={1}", gcmNotification.MessageId, description)); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { log.Error(string.Format("GCM Notification Failed: ID={0}", succeededNotification.MessageId)); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; log.Error(string.Format("GCM Notification Failed: ID={0}, Desc={1}", n.MessageId, e.InnerException)); } notificationService.Unsubscribe(devToken, userId); } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; log.Error(string.Format("Device RegistrationId Expired: {0}", oldId)); log.Error(string.Format("Device RegistrationId Changed To: {0}", newId)); if (!string.IsNullOrWhiteSpace(newId)) { notificationService.Unsubscribe(oldId, userId); log.Error(string.Format("Device RegistrationId Changed To: {0}", newId)); } else notificationService.Unsubscribe(oldId, userId); } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; log.Error(string.Format("GCM Rate Limited, don't send more until after {0}", retryException.RetryAfterUtc)); } else { log.Error("GCM Notification Failed for some unknown reason"); } log.Error("Failed for:" + string.Join(",", notification.RegistrationIds)); return true; }); }; gcmBroker.OnNotificationSucceeded += (notification) => { log.Info("Success for:" + string.Join(",", notification.RegistrationIds)); }; gcmBroker.Start(); }