Ejemplo n.º 1
0
    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();
    }
Ejemplo n.º 2
0
        /// <summary>
        /// Queue notification to android GCM reigsteration ids
        /// </summary>
        /// <param name="registerationID"></param>
        /// <param name="message"></param>
        /// <param name="title"></param>
        public void QueueGcmNotification(List <string> registerationIDs, string message, string title, int?unSeenNotificationsCount, Dictionary <string, object> addedData, List <NotificationActionModel> actions, bool withAlert = true)
        {
            //set notification data
            var data = new Dictionary <string, object>();

            if (withAlert)
            {
                data.Add("message", message);
                data.Add("title", title);
                data.Add("soundName", "ringtone");
            }
            // if no count sent don't send the badge number
            if (unSeenNotificationsCount != null)
            {
                data.Add("count", unSeenNotificationsCount.ToString());
            }

            //to fire on notification event while the application on background
            data.Add("content-available", "1");

            //add action buttons if exist
            if (actions != null)
            {
                //object[] x ={ new { icon = "emailGuests", title = "ACCEPT", callback = "window.acceptCallbackName", foreground = false},
                //        new{ icon = "snooze", title = "REJECT", callback = "window.rejectCallbackName", foreground = true}
                //        };

                data.Add("actions", actions);
            }
            //additional data to send with notification
            if (addedData != null)
            {
                foreach (var item in addedData)
                {
                    if (data.ContainsKey(item.Key))//update the value to last one
                    {
                        data[item.Key] = item.Value;
                    }
                    else//add it
                    {
                        data.Add(item.Key, item.Value);
                    }
                }
            }

            var    javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string jsonString           = javaScriptSerializer.Serialize(data);

            foreach (var regId in registerationIDs)
            {
                // Queue a notification to send
                gcmBroker.QueueNotification(new GcmNotification
                {
                    RegistrationIds = new List <string> {
                        regId
                    },
                    Data = JObject.Parse(jsonString)
                });
            }
        }
Ejemplo n.º 3
0
        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();
        }
Ejemplo n.º 4
0
    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();
    }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        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, "プッシュ通知で例外が発生しました");
            }
        }
Ejemplo n.º 7
0
        public override void Send(List <NeeoUser> receiverList, NotificationModel notificationModel)
        {
            if (receiverList == null || receiverList.Count == 0)
            {
                LogManager.CurrentInstance.ErrorLogger.LogError(
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
                    "receiverList is either null or empty.");
                return;
            }

            Parallel.ForEach(receiverList, (item) =>
            {
                var payload = new GcmPayload().Create(item, notificationModel);

                if (item.PnSource == PushNotificationSource.Pushy)
                {
                    var pushyRequest = new PushyPushRequest(payload, new string[] { item.DeviceToken });
                    PushyClient.SendPush(pushyRequest);
                    return;
                }

                var notification = new GcmNotification()
                {
                    RegistrationIds = new List <string> {
                        item.DeviceToken
                    },
                    Priority = GcmNotificationPriority.High,
                    Data     = JObject.FromObject(payload)
                };
                _gcmServiceBroker.QueueNotification(notification);
            });
        }
Ejemplo n.º 8
0
        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);
        }
Ejemplo n.º 9
0
        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();
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
    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);
    }
Ejemplo n.º 12
0
 private void QueueNotofication(ICollection <string> registrationIds, dynamic notificationData, GcmServiceBroker gcmBroker)
 {
     // Queue a notification to send
     gcmBroker.QueueNotification(new GcmNotification
     {
         RegistrationIds = registrationIds.ToList(),
         Data            = JObject.Parse(JsonConvert.SerializeObject(notificationData))
     });
 }
Ejemplo n.º 13
0
        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);
            }
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
 public void Send(PushDto dto)
 {
     // Queue a notification to send
     Thread.Sleep(2000); //Hide application in smartphone and wait for notification
     _broker.QueueNotification(new GcmNotification
     {
         RegistrationIds = new List <string>
         {
             dto.DeviceToken
         },
         Notification = JObject.Parse("{ \"body\" : \"This is body of notification\", \"title\" : \"This is title\" }")
     });
 }
Ejemplo n.º 16
0
        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();
        }
Ejemplo n.º 17
0
 public static void Send()
 {
     using (var contexto = new CafeDBContext())
     {
         var ids = contexto.PushDevices.Select(a => a.Endpoint).ToList();
         foreach (var regId in ids)
         {
             // Queue a notification to send
             gcmBroker.QueueNotification(new GcmNotification
             {
                 RegistrationIds = new List <string> {
                     regId
                 }
             });
         }
     }
 }
Ejemplo n.º 18
0
        override public void SendPushNotification(string token, string message, Int64 userId)
        {
            devToken    = token;
            this.userId = userId;

            var pushObj = new
            {
                message = message,
            };

            gcmBroker.QueueNotification(new GcmNotification
            {
                RegistrationIds = new List <string> {
                    token
                },
                Data = JObject.Parse(JsonConvert.SerializeObject(pushObj))
            });
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
 private bool SendAndroidNotification(List <string> devices, string payload)
 {
     try
     {
         _gcmBroker.QueueNotification(new GcmNotification
         {
             //RegistrationIds = new List<string> {
             //    "fWeAbdnDzxw:APA91bHGQjLneuTiXRPQZiQXDpBlCn7yegWn2AYfBO7jUdy3PqVM48GgEDTKm4-aa5Lq07sljW_oziOHbUiJJofBswV_rbPtqXiYdKPEY3Fn0g1haQpQvrD9qIdK3H9_1NZkpYw8iyWM"
             //},
             //Data = JObject.Parse("{ \"title\" : \"title\", \"message\" : \"message\"}")
             RegistrationIds = devices,
             Data            = JObject.Parse(payload)
         });
         return(true);
     }
     catch (Exception ex)
     {
         //throw new Exception("Error sending notification.");
         return(false);
     }
 }
Ejemplo n.º 21
0
    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();
    }
Ejemplo n.º 22
0
        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();
        }
Ejemplo n.º 23
0
        private void SendGcmMessage(string token, Message message, string trackingId)
        {
            if (!IsGcmChannelAccessable)
            {
                Log.Warn("GCM channel is not available, notification skipped");
                return;
            }

            Log.DebugFormat("Send GCM message to token:{0}", token);
            dynamic payload = new JObject();

            payload.triggerId = message.TriggerId;
            //payload.Text = message.Text;
            payload.msg   = message.Text;
            payload.sound = message.PlaySound;
            Log.DebugFormat("Notification JSON: {0}", payload);
            gcm.QueueNotification(new GcmNotification
            {
                To   = token,
                Data = payload,
                Tag  = trackingId
            });
        }
Ejemplo n.º 24
0
        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();
        }
Ejemplo n.º 25
0
        /// <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
                });
            }
        }
Ejemplo n.º 26
0
        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();
        }
Ejemplo n.º 27
0
        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();
        }
Ejemplo n.º 28
0
        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);
            }
        }
Ejemplo n.º 29
0
        //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);
        }
Ejemplo n.º 30
0
        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();
        }
Ejemplo n.º 31
0
        public static void Run(
            [QueueTrigger(InputQueueName, Connection = InfrastructureStorageAppSetting)] PushNotification notification)
        {
            Logging.Success($"Queue trigger function executed at UTC: {DateTime.UtcNow}", FunctionName);

            var gcmBroker = new GcmServiceBroker(new GcmConfiguration("AIzaSyAJPSeYx8u2oqymW9UTsCJI3-b6UZ4HWro"));
            var provider  = "GCM";

            gcmBroker.OnNotificationFailed += (not, 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;

                        Logging.Error($"{provider} Notification Failed: ID={gcmNotification.MessageId}, Desc={description}", FunctionName, null);
                    }
                    else if (ex is GcmMulticastResultException multicastException)
                    {
                        foreach (var succeededNotification in multicastException.Succeeded)
                        {
                            Logging.Success($"{provider} Notification Succeeded: ID={succeededNotification.MessageId}", FunctionName);
                        }

                        foreach (var failedKvp in multicastException.Failed)
                        {
                            var n = failedKvp.Key;
                            var e = failedKvp.Value;

                            Logging.Error($"{provider} Notification Failed: ID={n.MessageId}, Desc={e.Message}", FunctionName, null);
                        }
                    }
                    else if (ex is DeviceSubscriptionExpiredException expiredException)
                    {
                        var oldId = expiredException.OldSubscriptionId;
                        var newId = expiredException.NewSubscriptionId;

                        Logging.Error($"Device RegistrationId Expired: {oldId}", FunctionName, null);

                        if (!string.IsNullOrWhiteSpace(newId))
                        {
                            // If this value isn't null, our subscription changed and we should update our database
                            Logging.Error($"Device RegistrationId Changed To: {newId}", FunctionName, null);
                        }
                    }
                    else if (ex is RetryAfterException retryException)
                    {
                        // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date
                        Logging.Error($"{provider} Rate Limited, don't send more until after {retryException.RetryAfterUtc}", FunctionName, null);
                    }
                    else
                    {
                        Logging.Error("{provider} Notification Failed for some unknown reason", FunctionName, null);
                    }

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

            gcmBroker.OnNotificationSucceeded += (not) => {
                Logging.Success($"{provider} Notification Sent!", FunctionName);
            };

            gcmBroker.Start();

            dynamic alert = new ExpandoObject();

            alert.message          = notification.Message;
            alert.notificationType = 7;
            alert.id = 4290;
            alert.notificationGuid = Guid.Parse("59200E96-CB00-4FFD-856D-BE23786FEEC7");
            alert.data             = new ExpandoObject();
            gcmBroker.QueueNotification(new GcmNotification
            {
                RegistrationIds = new List <string> {
                    notification.Device
                },
                Data = JObject.FromObject((object)alert)
            });
        }