private static RemoteNotificationResult FromGoogleNotification(GcmNotification googleNotification)
        {
            RemoteNotificationResult result = new RemoteNotificationResult();

            result.DeviceType  = Notifications.ANDROID;
            result.DeviceToken = googleNotification.RegistrationIds[0];
            return(result);
        }
Example #2
0
        public void SendInvite(List <string> registrationIds, PushNotification notificationData)
        {
            GcmNotification notification = new GcmNotification();

            notification.ForDeviceRegistrationId(registrationIds);

            notification.WithJson(Serializer.SerializeToJason <PushNotification>(notificationData));

            this.PushNotification(notification);
        }
Example #3
0
        public static void NotifyAndroidUser(string token, string json, NotificationType type)
        {
            //Fluent construction of an Android GCM Notification
            //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
            var noti = new GcmNotification();

            //noti.DryRun = true;
            // PushBroker.QueueNotification(noti.ForDeviceRegistrationId(token).WithJson("{\"alert\":\"" + "Testing Testing" + "\",\"badge\":6, \"type\":\"" + type.ToString() + "\"}"));
            PushBroker.QueueNotification(noti.ForDeviceRegistrationId(token).WithJson(json));
        }
Example #4
0
        private async Task SendNotificationAsync_SendGcmNativeNotification_GetSuccessfulResultBack()
        {
            LoadMockData();
            var notification = new GcmNotification("{\"data\":{\"message\":\"Message\"}}");

            var notificationResult = await _hubClient.SendNotificationAsync(notification, "someRandomTag1 && someRandomTag2");

            Assert.Equal(NotificationOutcomeState.Enqueued, notificationResult.State);
            RecordTestResults();
        }
        protected void Gcm_OnNotificationFailed(GcmNotification notification, AggregateException exception)
        {
            Log.ErrorFormat("GCM failed {0}: {1}", notification.Tag, exception);
            foreach (var ex in exception.InnerExceptions.OfType <DeviceSubscriptionExpiredException>())
            {
                ProcessExpiredToken(notification.Tag as string, ex);
            }
            var statusMessage = exception.Flatten().ToString();

            TrackEvent(notification.Tag, TrackingStatus.Error, statusMessage);
        }
        public static async Task SendNotificationAsync(string message)
        {
            NotificationHubClient hub = NotificationHubClient
                .CreateClientFromConnectionString(Constants.HubConnectionString, Constants.HubName);

            var notification = new GcmNotification("{ \"data\" : {\"message\":\"" + message + "\"}}");

            var r = await hub.SendNotificationAsync(notification);


        }
Example #7
0
        void gcmPush_OnNotificationFailed(GcmNotification notification, AggregateException exception)
        {
            ContadorNoEnviados++;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("================================================================================");
            sb.AppendLine("Notificacion: " + notification.ToString());
            sb.AppendLine("Error: " + exception.Message);

            EscribirEnLog(sb.ToString());
        }
Example #8
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);
        }
        public static async Task SendNotificationAsync(string title, string author, int id)
        {
            NotificationHubClient hub = NotificationHubClient
                .CreateClientFromConnectionString(Constants.HubConnectionString, Constants.HubName);

            var content = "{ \"data\" : {\"title\":\"" + title + "\", \"author\":\"" + author + "\", \"id\":\"" + id + "\" }}";

            var notification = new GcmNotification(content);

            var r = await hub.SendNotificationAsync(notification);


        }
Example #10
0
        private void gcmPush_OnNotificationSucceeded(GcmNotification notification)
        {
            string token = "";

            try
            {
                token = notification.RegistrationIds.First();
                TokensSended.Add(token);
            }
            catch
            {
            }
            ContadorEnviados++;
        }
Example #11
0
        private static async void gSendNotificationAsync(string tag)
        {
            string conf = ConfigurationManager.AppSettings["Microsoft.Azure.NotificationHubs.ConnectionString"];
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://hmihub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=3kr9bLYgGwFWAUPn6boBYw8IRiYoAkPoPbPRA849o7A=", "emeahminofificationhub");
            var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>";
            //await hub.SendWindowsNativeNotificationAsync(toast,"myTag");
            GcmNotification gcm = new GcmNotification("{\"data\":{\"message\":\"Hej Robin\"}}");

            gcm.Headers.Add("tag", tag);

            await hub.SendNotificationAsync(gcm, tag);

            //await hub.SendGcmNativeNotificationAsync(", tag);
        }
Example #12
0
        private void NotificationFailed(object sender, INotification notification, Exception error)
        {
            if (notification.GetType() == new GcmNotification().GetType())
            {
                GcmNotification gcmNotification = (GcmNotification)notification;
                var             payLoad         = JsonConvert.DeserializeObject <dynamic>(gcmNotification.GetJson());
                ResultPushData  resultPushData  = new ResultPushData(payLoad);

                if (OnNotificationFailedCallback != null)
                {
                    NotificationFailedCallback notificationFailedCallback = new NotificationFailedCallback(OnNotificationFailedCallback);
                    notificationFailedCallback.Invoke(sender, error, resultPushData);
                }
            }
        }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification        notification = null;
            ApplePushMessage    apnsPush;
            WindowsPushMessage  wnsPush;
            MpnsPushMessage     mpnsPush;
            TemplatePushMessage templatePush;

            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime?expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return(notification);
        }
        private void SendAndroidNotification(string alert, IDictionary <string, object> data, string registrationId)
        {
            var payload = new Dictionary <string, object>(data);

            payload["alert"] = alert;

            GcmNotification notification = new GcmNotification()
            {
                DelayWhileIdle = false
            };

            notification.RegistrationIds.Add(registrationId);
            notification.CollapseKey    = Guid.NewGuid().ToString();
            notification.DelayWhileIdle = false;
            notification.Data           = JObject.Parse(JsonConvert.SerializeObject(payload));

            _apps[_serverSettings.ServerData.GCM.PackageName].Gcm.QueueNotification(notification);
        }
 public bool PushNotification(Device device, JSONNotification notification)
 {
     // Check if gcm looks is valid
     if (!String.IsNullOrEmpty(device.GCM) && !String.IsNullOrWhiteSpace(device.GCM))
     {
         try {
             GcmNotification notif = new GcmNotification().ForDeviceRegistrationId(device.GCM).WithJson(JsonConvert.SerializeObject(notification));
             _push.QueueNotification(notif);
             return(true);
         } catch (Exception e) {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Example #16
0
        public GcmProvider CreateNotification(object data, params string[] registrationIds)
        {
            GcmNotification notification = new GcmNotification {
                NotificationKey = ApiKey
            };

            foreach (string id in registrationIds)
            {
                notification.RegistrationIds.Add(id);
            }

            notification.JsonData = JsonConvert.SerializeObject(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            this.Notification = notification;
            return(this);
        }
 /// <summary>
 /// Gets the device identifier.
 /// </summary>
 /// <param name="notification">The notification.</param>
 /// <returns></returns>
 private string GetDeviceId(INotification notification)
 {
     try
     {
         if (notification is GcmNotification)
         {
             GcmNotification gcmNotification = (GcmNotification)notification;
             return(gcmNotification.RegistrationIds.FirstOrDefault());
         }
         else if (notification is AppleNotification)
         {
             AppleNotification appleNotification = (AppleNotification)notification;
             return(appleNotification.DeviceToken);
         }
     }
     catch (Exception ex)
     {
         ex.ExceptionValueTracker(notification);
     }
     return(string.Empty);
 }
Example #18
0
        //Android push message to GCM server method
        #region IPushNotifier Implemented methods

        public void Invite(Event evnt, List <UserProfile> users)
        {
            List <string> registrationIds = new List <string>();

            users.ForEach(user =>
            {
                registrationIds.Add(user.GCMClientId);
            });
            GcmNotification notification = new GcmNotification();

            notification.ForDeviceRegistrationId(registrationIds);
            PushNotification notificationData = new PushNotification()
            {
                Type      = "EventInvite",
                EventId   = evnt.EventId.ToString(),
                EventName = evnt.Description
            };

            notification.WithJson(Serializer.SerializeToJason <PushNotification>(notificationData));

            this.PushNotification(notification);
        }
        public void SendMessage(string message, List <PushDeviceInfo> devices)
        {
            if (!this.isStarted)
            {
                this.Start();
            }
            this.isStarted = true;

            var androidAppList = devices.Where(x => x.Platform.ToLower() == "android").ToList();

            if (androidAppList.Any())
            {
                var firstOrDefault = androidAppList.FirstOrDefault();
                if (firstOrDefault != null)
                {
                    var a = new GcmNotification().ForDeviceRegistrationId(firstOrDefault.DeviceToken)
                            .WithJson("{\"message\":\" " + message + "\"}");
                    //.WithJson("{\"message\":\" " + message + "\",\"badge\":0,\"msgcnt\":\" " + msgcnt + "\"}");
                    //a.TimeToLive = this._timeToLive;
                    this._pushBroker.QueueNotification(a, androidAppName);
                }
            }
        }
Example #20
0
        internal static Notification BuildNotificationFromString(string notificationAsString, NotificationPlatform platform)
        {
            Notification notification = null;

            if (platform == 0)
            {
                return(BuildTemplateNotificationFromJsonString(notificationAsString));
            }
            else
            {
                switch (platform)
                {
                case NotificationPlatform.Wns:
                    notification = new WindowsNotification(notificationAsString);
                    break;

                case NotificationPlatform.Apns:
                    notification = new AppleNotification(notificationAsString);
                    break;

                case NotificationPlatform.Gcm:
                    notification = new GcmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Adm:
                    notification = new AdmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Mpns:
                    notification = new MpnsNotification(notificationAsString);
                    break;
                }
            }

            return(notification);
        }
        /// <summary>
        /// Logs the notification.
        /// </summary>
        /// <param name="notification">The notification.</param>
        private void LogNotification(INotification notification)
        {
            try
            {
                Func <AppleNotificationPayload, string, string> parseApplePayload
                    = (payload, key) => payload.CustomItems[key].FirstOrDefault().ToString();

                Func <string, string, string> parseAndroidPayload = (payload, key) =>
                {
                    var data = (JObject)JsonConvert.DeserializeObject(payload);
                    return(data[key].Value <string>());
                };

                NotificationLogModel notificationLog = new NotificationLogModel();
                if (notification is GcmNotification)
                {
                    GcmNotification gcmNotification = (GcmNotification)notification;
                    notificationLog.DeviceId          = gcmNotification.RegistrationIds.FirstOrDefault();
                    notificationLog.NotifiactionToken = parseAndroidPayload(gcmNotification.JsonData, NotificationToken);
                    notificationLog.PageItemId        = int.Parse(parseAndroidPayload(gcmNotification.JsonData, PageItemId));
                }
                else if (notification is AppleNotification)
                {
                    AppleNotification appleNotification = (AppleNotification)notification;
                    notificationLog.DeviceId          = appleNotification.DeviceToken;
                    notificationLog.NotifiactionToken = parseApplePayload(appleNotification.Payload, NotificationToken);
                    notificationLog.PageItemId        = int.Parse(parseApplePayload(appleNotification.Payload, PageItemId));
                }

                this._notificationLogDataRepository.InsertNotificationLog(notificationLog);
            }
            catch (Exception ex)
            {
                ex.ExceptionValueTracker(notification);
            }
        }
Example #22
0
        private void PushNotification(GcmNotification notification)
        {
            //Create our push services broker
            var push = new PushBroker();

            //Wire up the events for all the services that the broker registers
            push.OnNotificationSent          += NotificationSent;
            push.OnChannelException          += ChannelException;
            push.OnServiceException          += ServiceException;
            push.OnNotificationFailed        += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated            += ChannelCreated;
            push.OnChannelDestroyed          += ChannelDestroyed;

            push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["GCMAPIKey"]));
            //push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("eWy5OUaxHJY:APA91bFNfAUJN7bt7HREMjgFQ653P_Q9vsgEizLStLx4TxcTrety3W-M0RgcB1plmu8C4SLbzwZOFHiCAyWXEjaQ0yzYB7m34yua-c78nsh32rY1e6aZVphrM1HAmw_NnfoxqvZeIuOk")
            //.WithJson(@"{""alert"":""Hello World!"",""badge"":7,""sound"":""sound.caf"",""msg"":""hello""}"));

            push.QueueNotification(notification);

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification notification = null;
            ApplePushMessage apnsPush;
            WindowsPushMessage wnsPush;
            MpnsPushMessage mpnsPush;
            TemplatePushMessage templatePush;
            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime? expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return notification;
        }
 private void _pushBroker_OnNotificationFailed(GcmNotification notification, Exception exception)
 {
     throw exception;
 }
        private async void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                btnRegistrations.Enabled = false;
                btnSend.Enabled = false;
                btnRefresh.Enabled = false;
                btnCreateDelete.Enabled = false;
                btnCancelUpdate.Enabled = false;
                if (notificationHubClient == null)
                {
                    return;
                }

                Notification notification = null;
                string[] tags = null;
                string tagExpression = null;
                switch (mainTabControl.SelectedTab.Name)
                {
                    case TemplateNotificationPage:
                        var properties = NotificationInfo.TemplateProperties.ToDictionary(p => p.Name, p => p.Value);
                        if (properties.Count > 0)
                        {
                            var headers = NotificationInfo.TemplateHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.TemplateTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtTemplateTagExpression.Text;
                            notification = new TemplateNotification(properties) {Headers = headers};
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case WindowsPhoneNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(mpnsPayload))
                        {
                            var headers = NotificationInfo.MpnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.MpnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtMpnsTagExpression.Text;
                            notification = new MpnsNotification(mpnsPayload, headers);
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case WindowsNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(wnsPayload))
                        {
                            var headers = NotificationInfo.WnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.WnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtWnsTagExpression.Text;
                            notification = new WindowsNotification(wnsPayload, headers);
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case AppleNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(apnsPayload))
                        {
                            var serializer = new JavaScriptSerializer();
                            try
                            {
                                serializer.Deserialize<dynamic>(apnsPayload);
                            }
                            catch (Exception)
                            {
                                writeToLog(PayloadIsNotInJsonFormat);
                                return;
                            }
                            var headers = NotificationInfo.ApnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.ApnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtAppleTagExpression.Text;
                            notification = new AppleNotification(apnsPayload) { Headers = headers };
                        }
                        else
                        {
                            writeToLog(JsonPayloadTemplateCannotBeNull, false);
                        }
                        break;
                    case GoogleNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(gcmPayload))
                        {
                            var serializer = new JavaScriptSerializer();
                            try
                            {
                                serializer.Deserialize<dynamic>(gcmPayload);
                            }
                            catch (Exception)
                            {
                                writeToLog(PayloadIsNotInJsonFormat);
                                return;
                            }
                            var headers = NotificationInfo.GcmHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.GcmTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtGcmTagExpression.Text;
                            notification = new GcmNotification(gcmPayload) { Headers = headers };
                        }
                        else
                        {
                            writeToLog(JsonPayloadTemplateCannotBeNull, false);
                        }
                        break;
                }
                if (notification == null)
                {
                    return;
                }
                NotificationOutcome notificationOutcome;
                if (!string.IsNullOrWhiteSpace(tagExpression))
                {
                    notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tagExpression);
                    WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
                    return;
                }
                if (tags.Any())
                {
                    notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tags);
                    WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
                    return;
                }
                notificationOutcome = await notificationHubClient.SendNotificationAsync(notification);
                WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
            }
            catch (Exception ex)
            {
                writeToLog(ex.Message);
            }
            finally
            {
                btnRegistrations.Enabled = true;
                btnSend.Enabled = true;
                btnRefresh.Enabled = true;
                btnCreateDelete.Enabled = true;
                btnCancelUpdate.Enabled = true;
                Cursor.Current = Cursors.Default;
            }
        }