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); }
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 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 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 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 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(); }
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 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); }
/// <summary> /// Stops and unassigns all brokers /// </summary> public static void StopBrokers() { // 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(); GcmBroker.Stop(); WnsBroker.Stop(); ApnsBroker = null; GcmBroker = null; WnsBroker = null; }
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); } }
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 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); }
//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 static void ViaPushSharp(string serverApiKey, string senderId, string deviceId, string message) { String[] MY_REGISTRATION_IDS = { deviceId }; // Configuration //var config = new GcmConfiguration("GCM-SENDER-ID", "AUTH-TOKEN", null); var config = new GcmConfiguration(senderId, serverApiKey, null); // Firebase hack config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; // Create a new broker var gcmBroker = new GcmServiceBroker(config); #region Wire up events: OnNotificationFailed, OnNotificationSucceeded 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}"); 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!"); }; #endregion // Start the broker gcmBroker.Start(); foreach (var regId in MY_REGISTRATION_IDS) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, Data = JObject.Parse("{ \"somekey\" : \"somevalue\" }") }); } // 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 bool Send(IEnumerable <string> deviceIdList, string message) { // Configuration GCM (use this section for GCM) //var config = new GcmConfiguration(context.GcmSenderId, context.GcmAuthToken, null); //var provider = "GCM"; // Configuration FCM (use this section for FCM) var config = new GcmConfiguration(context.FcmApiKey); config.GcmUrl = context.FcmUrl; var provider = "FCM"; // 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 notificationException) { // Deal with the failed notification var gcmNotification = notificationException.Notification; var description = notificationException.Description; Console.WriteLine($"{provider} Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); } else if (ex is GcmMulticastResultException multicastException) { foreach (var succeededNotification in multicastException.Succeeded) { Console.WriteLine($"{provider} Notification Succeeded: ID={succeededNotification.MessageId}"); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; Console.WriteLine($"{provider} Notification Failed: ID={n.MessageId}, Desc={e.Message}"); } } else if (ex is DeviceSubscriptionExpiredException expiredException) { 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 retryException) { // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date Console.WriteLine($"{provider} Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); } else { Console.WriteLine("{provider} Notification Failed for some unknown reason"); } // Mark it as handled return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { Console.WriteLine("{provider} Notification Sent!"); }; // Start the broker gcmBroker.Start(); foreach (var regId in deviceIdList) { // Queue a notification to send gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = new List <string> { regId }, //Data = JObject.Parse("{ \"somekey\" : \"somevalue\" }"), Notification = JObject.Parse($"{{ \"title\" : \"title\", \"body\" : \"{message}\"}}"), }); } // 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(); return(true); }
public static void GCMNotification(string DeviceID, string Message) { var config = new GcmConfiguration("843528056820", "AIzaSyDgc0QZL7W-qVem_pcg18HupuBJw-tug6g", null); var gcmBroker = new GcmServiceBroker(config); 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.Data[""]}"); } } 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(); gcmBroker.QueueNotification(new GcmNotification { //RegistrationIds = new List<string> {DeviceID}, To = DeviceID, Priority = GcmNotificationPriority.High, Notification = JObject.Parse("{\"title\" : \"FindExpert\",\"body\":\"" + Message + "\",\"icon\":\"icon\"}"), Data = JObject.Parse("{ \"somekey\" : \"somevalue\" }") }); // 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 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; }
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); } }
public static void Stop() { gcmBroker.Stop(); gcmBroker = null; }
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 static bool Notify(IEnumerable <string> registrationIds, List <string> errors, NotificationModel model) { bool succeed = false; var senderId = WebConfigurationManager.AppSettings["Android_SenderId"]; var tokken = WebConfigurationManager.AppSettings["Android_Tokken"]; // Configuration var config = new GcmConfiguration(senderId, tokken, 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; errors.Add($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); } else if (ex is GcmMulticastResultException) { var multicastException = (GcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { errors.Add($"GCM Notification Failed: ID={succeededNotification.MessageId}"); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; errors.Add($"GCM Notification Failed: ID={n.MessageId}, Desc={"Description"}"); } } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; errors.Add($"Device RegistrationId Expired: {oldId}"); if (!string.IsNullOrWhiteSpace(newId)) { // If this value isn't null, our subscription changed and we should update our database errors.Add($"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 errors.Add($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); } else { // errors.Add("GCM Notification Failed for some unknown reason"); } // Mark it as handled return(true); }); }; gcmBroker.OnNotificationSucceeded += (notification) => { succeed = true; }; // 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.FromObject(model) }); } // 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(); return(succeed); }