public async Task <bool> SenderToFirebaseAsync2(String dataJson)
        {
            bool bStatus  = true;
            var  ind      = dataJson.IndexOf("Index");
            var  indexVal = dataJson.Substring(ind, 10);

            Console.WriteLine("Processing Messsage " + indexVal);

            var       registrationId = "dARiEevCnFo:APA91bFTev5UB_plXxXKmYTrkx79isGzjIeCSy0UST-KNaVQsnGICoF7qgbEYyFu-3n1y807iPNmFI5IbzIlNLpJQ6q-OMqAZmWZeEURmoO3TIlA2TmR9ZSL4Bq4INzHqPmtRsAIxg0Y";
            var       serverKey      = "AAAAkwlfmpI:APA91bElre6S3XNPQUzrLjhF5zPgUJFFWHrzblzNxcIpxAgzVEoay_RdS9wTbW-99Gq8KMvd9ecimKgBjJLh_Zjbrv4wQ-Hjl_gFEOYeGNzPUjxWljH7lIwVwyXvn3QCMFEvFF-Jh9_Q";
            FCMClient client         = new FCMClient(serverKey);
            var       message        = new Message
            {
                To           = registrationId,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                    Icon  = "myIcon"
                }
            };

            try{
                DownstreamMessageResponse result = (DownstreamMessageResponse)await client.SendMessageAsync(message);

                Console.WriteLine("After FCMClient: SendMessageAsync");
                Console.WriteLine($"Success: {result.Success} " + " Message" + indexVal);
            }catch (Exception error)
            {
                Console.WriteLine($"Text: '{error.Message}'");
            }
            return(bStatus);
        }
Example #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="registerationId"></param>
        /// <param name="body"></param>
        /// <param name="title"></param>
        /// <param name="icon"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <param name="firebaseServerKey"></param>
        /// <param name="isRedirect"></param>
        /// <param name="notificationSubType"></param>
        /// <param name="customReferenceId"></param>
        /// <returns></returns>
        public async Task <bool> AndroidPushNotificationBulk(List <string> registerationId, string body, string title, string icon, string data, string type, string firebaseServerKey, bool isRedirect, string notificationSubType, int customReferenceId)
        {
            if (!string.IsNullOrEmpty(firebaseServerKey))
            {
                FCMClient client  = new FCMClient(firebaseServerKey);
                var       message = new Message()
                {
                    RegistrationIds = registerationId,
                    Notification    = new AndroidNotification()
                    {
                        Body = body, Title = title, Icon = data, ClickAction = ".ClientDashboardActivity"
                    },
                    Data = new Dictionary <string, string> {
                        { "data", data }, { "notificationType", type }, { "accountType", "2" }, { "IsRedirect", isRedirect.ToString() }, { "NotificationSubType", notificationSubType }, { "CustomReferenceId", customReferenceId.ToString() }
                    }
                };
                try
                {
                    await client.SendMessageAsync(message);

                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_topic_message_with_data_AND_optional_fields_set_AND_notification_set_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To           = "/topics/android",
                CollapseKey  = "score_update",
                TimeToLive   = 108,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vss Denmark",
                    Icon  = "myIcon"
                },
                Data = new Dictionary <string, string>
                {
                    { "score", "5x1" },
                    { "time", "15:10" }
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <TopicMessageResponse>(result);
        }
Example #4
0
        public FcmService(IConfiguration config)
        {
            this.config = config;
            var apiKey = config.GetValue <string>("FCMKey");

            this.fcmClient = new FCMClient(apiKey);
        }
Example #5
0
        public async Task <IHttpActionResult> Post([FromBody] Alert value)
        {
            var client = new FCMClient("AIzaSyChp172E9Q9oWg14_Ejy7H6Zr3x1SUCqwA");

            if (value.IsAndroid)
            {
                var info = new Dictionary <string, string>();
                info["Body"]  = JsonConvert.SerializeObject(value);
                info["Title"] = "Alert";
                var message = new Message()
                {
                    To = "GENERAL",

                    Data = info
                };

                var result = await client.SendMessageAsync(message);
            }
            else
            {
                var message = new Message()
                {
                    To           = "GENERAL",
                    Notification = new IOSNotification()
                    {
                        Body  = JsonConvert.SerializeObject(value),
                        Title = "Alert"
                    }
                };

                var result = await client.SendMessageAsync(message);
            }
            return(Ok());
        }
Example #6
0
        /// <summary>
        /// Send Push Android.
        /// </summary>
        /// <param name="registerationId"></param>
        /// <param name="body"></param>
        /// <param name="title"></param>
        /// <param name="icon"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <param name="firebaseServerKey"></param>
        /// <returns></returns>
        public async Task <bool> AndroidPushNotification(string registerationId, string body, string title, string icon, string data, string type, string firebaseServerKey)
        {
            if (!string.IsNullOrEmpty(firebaseServerKey))
            {
                FCMClient client  = new FCMClient(firebaseServerKey);
                var       message = new Message()
                {
                    To           = registerationId,
                    Notification = new AndroidNotification()
                    {
                        Body = body, Title = title, Icon = data, ClickAction = ".ClientDashboardActivity"
                    },
                    Data = new Dictionary <string, string> {
                        { "data", data }, { "NotificationType", type }, { "AccountType", "2" }
                    }
                };
                try
                {
                    await client.SendMessageAsync(message);

                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
        public async void SenderToFirebaseAsync(String msg)
        {
            var       registrationId = "dARiEevCnFo:APA91bFTev5UB_plXxXKmYTrkx79isGzjIeCSy0UST-KNaVQsnGICoF7qgbEYyFu-3n1y807iPNmFI5IbzIlNLpJQ6q-OMqAZmWZeEURmoO3TIlA2TmR9ZSL4Bq4INzHqPmtRsAIxg0Y";
            var       serverKey      = "AAAAkwlfmpI:APA91bElre6S3XNPQUzrLjhF5zPgUJFFWHrzblzNxcIpxAgzVEoay_RdS9wTbW-99Gq8KMvd9ecimKgBjJLh_Zjbrv4wQ-Hjl_gFEOYeGNzPUjxWljH7lIwVwyXvn3QCMFEvFF-Jh9_Q";
            FCMClient client         = new FCMClient(serverKey);
            var       message        = new Message
            {
                To           = registrationId,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                    Icon  = "myIcon"
                }
            };

            try{
                var result = await client.SendMessageAsync(message);

                Console.WriteLine("After FCMClient: SendMessageAsync");
            }catch (Exception error)
            {
                Console.WriteLine($"Text: '{error.Message}'");
            }
        }
Example #8
0
        /// <summary>
        /// Pulls the messaged from pub sub.
        /// </summary>
        /// <param name="ct">The ct.</param>
        protected static async Task <bool> PullMessagedFromPubSubAsync(CancellationToken ct)
        {
            bool bStatus = true;

            FirebaseTestSender.Init();
            var       firebasenet = new FirebaseTestSender();
            Stopwatch stopWatch   = new Stopwatch();

            long length = 0;

            lock (_redisOperationLock){
                length = _redisDB.ListLength(PendingQueue);
            }
            long       numOfMsg = length - 1;
            RedisValue message  = new RedisValue();
            FCMClient  client   = new FCMClient(serverKey);

            while (length > 0)
            {
                lock (_redisOperationLock){
                    length = _redisDB.ListLength(PendingQueue);

                    if (length >= 1)
                    {
                        message = _redisDB.ListRightPop(PendingQueue);
                    }
                }
                if (length >= 1)
                {
                    Dictionary <String, String> convertedMessage = null;
                    String[] recievedRegistration_ids;
                    bool     converted = ConvertMessageWithTokens(message, out convertedMessage, out recievedRegistration_ids);

                    firebasenet.SenderDataPayloadToFirebaseAsync(convertedMessage, recievedRegistration_ids, client);
                }

                lock (_redisOperationLock){
                    length = _redisDB.ListLength(PendingQueue);
                }
            }

            while (true)
            {
                bool isFinished = CheckMessagesStatus();
                if (isFinished)
                {
                    break;
                }
                Thread.Sleep(50);
            }


            return(bStatus);
        }
        public static async Task SendMessage(User recipient, IDictionary <string, string> data = null)
        {
            var client = new FCMClient(FcmServerKey);

            var message = new Message()
            {
                To   = recipient.FirebaseToken,
                Data = data
            };

            await client.SendMessageAsync(message);
        }
Example #10
0
        /// <summary>
        /// Pulls the messaged from pub sub.
        /// </summary>
        /// <param name="ct">The ct.</param>
        protected static async Task <bool> PullMultiMessagedAsync(CancellationToken ct)
        {
            bool bStatus = true;

            FirebaseTestSender.Init();
            FCMClient client    = new FCMClient(serverKey);
            Stopwatch stopWatch = new Stopwatch();

            long length = 0;

            lock (_redisOperationLock){
                length = _redisDB.ListLength(PendingQueue);
            }
            long       numOfMsg = length - 1;
            RedisValue message  = new RedisValue();
            //RedisValue[] msgCollection = new RedisValue[1];
            long start = 0, end = 0;
            long step = length / 5;


            var msgCollection1 = _redisDB.ListRange(PendingQueue, 0, 999);
            var msgCollection2 = _redisDB.ListRange(PendingQueue, 1000, 1999);
            var msgCollection3 = _redisDB.ListRange(PendingQueue, 2000, 2999);
            var msgCollection4 = _redisDB.ListRange(PendingQueue, 3000, 3999);
            var msgCollection5 = _redisDB.ListRange(PendingQueue, 4000, 5000);

            _redisDB.ListTrimAsync(PendingQueue, 0, 0, CommandFlags.HighPriority);
            _redisDB.ListRightPopAsync(PendingQueue);

            Parallel.Invoke(() => DoSomeWork(msgCollection1, client), () => DoSomeWork(msgCollection2, client)
                            , () => DoSomeWork(msgCollection3, client), () => DoSomeWork(msgCollection4, client), () => DoSomeWork(msgCollection5, client));


            lock (_redisOperationLock){
                length = _redisDB.ListLength(PendingQueue);
            }



            while (true)
            {
                bool isFinished = CheckMessagesStatus();
                if (isFinished)
                {
                    break;
                }
                Thread.Sleep(50);
            }


            return(bStatus);
        }
Example #11
0
        private static void DoSomeWork(RedisValue[] msgCollection, FCMClient client)
        {
            var firebasenet = new FirebaseTestSender();

            foreach (var m in msgCollection)
            {
                Dictionary <String, String> convertedMessage = null;
                String[] recievedRegistration_ids;
                bool     converted = ConvertMessageWithTokens(m, out convertedMessage, out recievedRegistration_ids);
                firebasenet.SenderDataPayloadToFirebaseAsync(convertedMessage, recievedRegistration_ids, client);
            }
            ;
        }
Example #12
0
        public Task NotificacionTerminarPedido(string token)
        {
            var client  = new FCMClient(FirebaseToken);
            var message = new Message()
            {
                To           = token,
                Notification = new AndroidNotification()
                {
                    Title = "Su pedido está listo",
                    Body  = "El mozo le estará trayendo su pedido en unos momentos"
                }
            };

            return(client.SendMessageAsync(message));
        }
Example #13
0
        public Task NotificacionGenerarBoleta(string token)
        {
            var client  = new FCMClient(FirebaseToken);
            var message = new Message()
            {
                To           = token,
                Notification = new AndroidNotification()
                {
                    Title = "Su boleta está lista",
                    Body  = "El mozo le estará trayendo su boleta en unos momentos o puede acercarse a caja"
                }
            };

            return(client.SendMessageAsync(message));
        }
Example #14
0
        public static async Task <IFCMResponse> foo()
        {
            FCMClient client  = new FCMClient("YOUR_APP_SERVER_KEY"); //as derived from https://console.firebase.google.com/project/
            var       message = new Message()
            {
                To           = "DEVICE_ID_OR_ANY_PARTICULAR_TOPIC", //topic example /topics/all
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                }
            };
            var result = await client.SendMessageAsync(message);

            return(result);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_downstream_message_with_data_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To   = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
                Data = new Dictionary <string, string>
                {
                    { "score", "5x1" },
                    { "time", "15:10" }
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <DownstreamMessageResponse>(result);
        }
Example #16
0
        static void Main(string[] args)
        {
            var fcmServerKey = "<ADD THIS>";
            var client       = new FCMClient(fcmServerKey);


            var registrationToken = "<ADD THIS>";
            var message           = "Test";

            var builder = new FCMMessageBuilder();

            builder.SetMessage(message);
            builder.SetRegistrationToken(registrationToken);

            var msg = builder.Build();


            client.PostMessage(msg).Wait();
        }
        static void Main(string[] args)
        {
            var deviceToken1 = "";
            var deviceToken2 = "";

            var deviceTokens = new string[] { deviceToken1, deviceToken2 };

            var client = new FCMClient(serverKey);

            var message = new Message()
            {
                RegistrationIds = deviceTokens,

                Notification = new AndroidNotification()
                {
                    Body  = "Привет:)",
                    Title = "Заголовок",
                },
            };

            var result = client.Send(message);

            if (result.Exception == null)
            {
                Console.WriteLine($"Успешных отправок {result.MessageResult.SuccessfulTokens.Count}");
                foreach (var token in result.MessageResult.SuccessfulTokens)
                {
                    Console.WriteLine($"Успешные токены: {token}");
                }

                Console.Write($"Неудачных отправок: {result.MessageResult.FailedTokens.Count}");
                foreach (var token in result.MessageResult.FailedTokens)
                {
                    Console.WriteLine($"Неудачные токены: {token}");
                }
            }
            else
            {
                Console.WriteLine($"Ошибка отправки push-соощения: {result.Exception.Message}");
            }

            Console.ReadKey();
        }
        public async Task Given_an_invalid_server_key_THEN_I_must_get_an_FCM_exception()
        {
            FCMClient client = new FCMClient("foo");

            var message = new Message()
            {
                DryRun       = true,
                To           = "1213",
                Notification = new AndroidNotification()
                {
                    Title = "Title",
                    Body  = "body",
                }
            };

            var result = await Assert.ThrowsAsync <FCMUnauthorizedException>(() => client.SendMessageAsync(message));

            Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_topic_message_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                DryRun       = true,
                To           = "/topics/android",
                Notification = new AndroidNotification()
                {
                    Title = "Title",
                    Body  = "body",
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <TopicMessageResponse>(result);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_downstream_message_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To           = "deviceid",
                Notification = new AndroidNotification()
                {
                    Title = "Message title",
                    Body  = "Notification body",
                    Color = "#000000"
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <DownstreamMessageResponse>(result);
        }
Example #21
0
        private static int SendFcmBatchMessages(string body, List <NotificationUser> users) // restricted to 1000
        {
            FCMClient client  = new FCMClient(GetServerKey());
            var       message = new FirebaseNet.Messaging.Message()
            {
                RegistrationIds = users.Select(x => x.FcmToken).ToList(),
                Data            = new Dictionary <string, string>
                {
                    { "app-action", @"new-message" },
                    { "message", body }
                }
            };
            var res         = new List <DownstreamMessageResponse>();
            var response    = client.SendMessageAsync(message);
            var contiuation = response.ContinueWith(t => res.Add((DownstreamMessageResponse)t.Result));

            Notification.UpdateUnreadNotificationCountOfUsers(users.Select(x => x.AppUserId).ToList());
            contiuation.Wait();
            return((int)res.Sum(x => x.Success));
        }
Example #22
0
 private static async Task SendFcmMessage(string pushName, string body, NotificationUser user, string token)
 {
     FCMClient client  = new FCMClient(GetServerKey());
     var       message = new FirebaseNet.Messaging.Message()
     {
         To   = token,
         Data = new Dictionary <string, string>
         {
             { "badge", (user.UnreadNotificationCount + 1).ToString() },
             { "app-action", @"new-message" },
             { "message", body }
         }
     };
     var response = client.SendMessageAsync(message);
     await response.ContinueWith(t =>
     {
         var results = t.Result as DownstreamMessageResponse;
         _logQueue.Enqueue(@" ------------" + DateTime.Now + "--------------------" + '\n' + "sent to  " + user.AppUserId + " is success : " + results.Success + '\n' + "errors : " + String.Join(" , ", results.Results.Select(x => x.Error)));
     });
 }
Example #23
0
        public async Task <IHttpActionResult> Post([FromBody] Alert value)
        {
            var client = new FCMClient("AAAAJk2sCkg:APA91bGEr-eF3mxVqfr_-bo9JFiStCDVTVaKCIbvJGEDmEEgqXQL59-JbcpCStyG2mkUlt4KchuT0_85U0Vo1-yOTgwFv6sObO_YCzmyZI7ct8wh19YCExsO1SokTc11lE4BLgqsh_Jv");

            //await NotifyAsync("/topics/general", value.Title, JsonConvert.SerializeObject(value));
            if (value.IsAndroid)
            {
                var info = new Dictionary <string, string>();
                info["Body"]  = JsonConvert.SerializeObject(value);
                info["Title"] = value.Title;
                var message = new Message()
                {
                    /* Notification = new AndroidNotification()
                     * {
                     *   Body = JsonConvert.SerializeObject(value),
                     *   Title = value.Title
                     * },*/
                    To   = "/topics/general",
                    Data = info
                };

                var result = await client.SendMessageAsync(message);
            }
            else
            {
                var message = new Message()
                {
                    To           = "/topics/general",// "/topics/all",
                    Notification = new IOSNotification()
                    {
                        Body  = JsonConvert.SerializeObject(value),
                        Title = "Alert"
                    }
                };

                var result = await client.SendMessageAsync(message);
            }//*/
            return(Ok());
        }
        public static async Task SendMessage(User recipient, string title, string body,
                                             IDictionary <string, string> data = null, string clickAction = null, string sound = "default",
                                             string icon = "default")
        {
            var client = new FCMClient(FcmServerKey);

            var message = new Message()
            {
                To           = recipient.FirebaseToken,
                Notification = new AndroidNotification()
                {
                    Body        = body,
                    Title       = title,
                    Icon        = icon,
                    ClickAction = clickAction,
                    Sound       = sound,
                },
                Data = data
            };

            await client.SendMessageAsync(message);
        }