public static async Task <bool> SendPushNotification(FcmMessage fcmMessage)
        {
            bool sent = false;

            if (fcmMessage != null)
            {
                //Object to JSON STRUCTURE => using Newtonsoft.Json;
                string jsonMessage = JsonConvert.SerializeObject(fcmMessage);

                //Create request to Firebase API
                var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);

                request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
                request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");

                HttpResponseMessage result;
                using (var client = new HttpClient())
                {
                    result = await client.SendAsync(request);

                    sent = sent && result.IsSuccessStatusCode;
                }
            }

            return(sent);
        }
Exemplo n.º 2
0
        public async Task <Result <bool> > SendToUserAsync(int userId, FcmMessage message, CancellationToken cancellationToken = default)
        {
            message.Message.Token = await FcmUserTokenRepository.GetUserTokenAsync(userId, cancellationToken);
            await SendAsync(message, cancellationToken);

            return(new Result <bool>(true));
        }
Exemplo n.º 3
0
        public JsonResult Notify(int sensorId, Dictionary <string, string> data)
        {
            if (sensorId <= 0 || data == null)
            {
                return(Json(new ApiError("Invalid request parameters.")));
            }

            try
            {
                using (SensorContext db = new SensorContext())
                {
                    Sensor     sensor   = db.Sensors.Single(s => s.ID == sensorId);
                    FcmMessage msg      = new FcmMessage(data, sensor.GetNotificationIds().ToArray());
                    var        response = FirebaseClient.instance.Notify(msg);

                    if (response.IsSuccessStatusCode)
                    {
                        return(Json(new { succeeded = true }));
                    }
                    else
                    {
                        return(Json(new ApiError("Message wasn't sent.")));
                    }
                }
            }
            catch (Exception e)
            {
                return(Json(new ApiError("An error occured.")));
            }
        }
Exemplo n.º 4
0
        public async Task <Result <bool> > SendToAllAsync(FcmMessage message, CancellationToken cancellationToken = default)
        {
            message.Message.Topic = "all";
            await SendAsync(message, cancellationToken);

            return(new Result <bool>(true));
        }
        public void Post([FromBody] string value)
        {
            var settings = FileBasedFcmClientSettings.CreateFromFile("pushnotificationpoc-6a4f2", @"E:\New folder\Navvis\codebase\CoreoHome\Push Notification\serviceAccountKey.json");

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                // The Message should be sent to the News Topic:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Token        = "fnHz7NZ-aqA:APA91bE_6vHTd1NqiOthIHEzkZ_WyMJcDRN6TZdBfnHMjo12kGr1GIGLb3yInkTcRssDmT2kialO6We2yYe-lm5qON3nO9oe1mIa94U76tGR12h_8K4aFb5kggyLrqiGTQ21XBl2AjuDhUxlsaB6B5QlzgwPNaCRjA",
                        Notification = new Notification
                        {
                            Title = "Hiiii",
                            Body  = value
                        }
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();


                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                Console.WriteLine("Message ID = {0}", result.Name);
            }
        }
Exemplo n.º 6
0
        public async Task <FcmMessageResponse> SendAsync(FcmMessage message, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            string url = $"https://fcm.googleapis.com/v1/projects/{settings.Project}/messages:send";

            // Construct the HTTP Message:
            HttpRequestMessageBuilder httpRequestMessageBuilder = new HttpRequestMessageBuilder(url, HttpMethod.Post)
                                                                  .SetStringContent(serializer.SerializeObject(message), Encoding.UTF8, MediaTypeNames.ApplicationJson);

            try
            {
                return(await httpClient.SendAsync <FcmMessageResponse>(httpRequestMessageBuilder, cancellationToken).ConfigureAwait(false));
            }
            catch (FcmHttpException exception)
            {
                // Get the Original HTTP Response:
                var response = exception.HttpResponseMessage;

                // Read the Content:
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // Parse the Error:
                var error = serializer.DeserializeObject <FcmMessageErrorResponse>(content);

                // Throw the Exception:
                throw new FcmMessageException(error, content);
            }
        }
Exemplo n.º 7
0
        public async Task SendToUserAsync(int userId, Dictionary <string, string> data, CancellationToken cancellationToken = default)
        {
            var fcmMessage = new FcmMessage {
                Data = data
            };

            await SendToUserAsync(userId, fcmMessage, cancellationToken);
        }
Exemplo n.º 8
0
        public Task <FcmMessageResponse> SendAsync(FcmMessage message, CancellationToken cancellationToken = new CancellationToken())
        {
            var content = JsonConvert.SerializeObject(message, Formatting.Indented);

            Console.WriteLine($"[{DateTime.Now}] [SendAsync] {content} ...");

            return(Task.FromResult(new FcmMessageResponse()));
        }
Exemplo n.º 9
0
        public async Task SendToAllAsync(Dictionary <string, string> data, CancellationToken cancellationToken = default)
        {
            var fcmMessage = new FcmMessage()
            {
                Data = data
            };

            await SendToAllAsync(fcmMessage, cancellationToken);
        }
Exemplo n.º 10
0
        public Task <FcmMessageResponse> SendAsync(FcmMessage message, CancellationToken cancellationToken = new CancellationToken())
        {
            if (logger.IsDebugEnabled())
            {
                var messageContent = JsonConvert.SerializeObject(message, Formatting.Indented);

                logger.LogDebug($"Sending Message with Content = {messageContent}");
            }

            return(Task.FromResult(new FcmMessageResponse()));
        }
Exemplo n.º 11
0
        public async Task <Result <bool> > SendToAllAsync(Dictionary <string, string> data, CancellationToken cancellationToken = default)
        {
            var fcmMessage = new FcmMessage {
                Message = new Message {
                    Data = data
                }
            };

            await SendToAllAsync(fcmMessage, cancellationToken);

            return(new Result <bool>(true));
        }
Exemplo n.º 12
0
        public async Task SendNotificationAsync(Topic topic, Notification notification, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = new FcmMessage
            {
                ValidateOnly = false,
                Message      = new Message
                {
                    Topic        = topic.Name,
                    Notification = ConvertNotification(notification)
                }
            };

            await client.SendAsync(message, cancellationToken);
        }
        public static void Main()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "pushnotify",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var        body          = ea.Body;
                        var        message       = Encoding.UTF8.GetString(body);
                        var        messageObject = JsonConvert.DeserializeObject <NotificationMessage>(message);
                        FcmMessage fcmMessage    = new FcmMessage()
                        {
                            ValidateOnly = false,
                            Message      = new Message()
                            {
                                Data         = messageObject.Data,
                                Token        = messageObject.Token,
                                Topic        = messageObject.Topic,
                                Condition    = messageObject.Condition,
                                Notification = new Notification()
                                {
                                    Body  = messageObject.NotificationBody,
                                    Title = messageObject.NotificationTitle
                                }
                            }
                        };
                        SendPushNotification(fcmMessage);
                        Console.WriteLine(" [x] Received {0}", message);
                    };
                    channel.BasicConsume(queue: "pushnotify",
                                         autoAck: true,
                                         consumer: consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
            }
        }
Exemplo n.º 14
0
        private async Task SendNotificationAsync(string token, Notification notification, CancellationToken cancellationToken)
        {
            var message = new FcmMessage
            {
                ValidateOnly = false,
                Message      = new Message
                {
                    Token        = token,
                    Notification = ConvertNotification(notification)
                }
            };

            await client.SendAsync(message, cancellationToken);
        }
        public void Send(string tilte, string body)
        {
            // Read the Credentials from a File, which is not under Version Control:
            var settings = FileBasedFcmClientSettings.CreateFromFile(ConfigrationHelper.FirebaseServiceFile);

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                var notification = new Notification
                {
                    Title = tilte ?? "",
                    Body  = $"تم اضافة فاعلية : {body}"
                };

                // The Message should be sent to the News Topic:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Condition    = "!('anytopicyoudontwanttouse' in topics)",
                        Notification = notification,
                        ApnsConfig   = new ApnsConfig
                        {
                            Payload = new ApnsConfigPayload
                            {
                                Aps = new Aps
                                {
                                    Sound = "default",
                                }
                            }
                        }
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                //// Print the Result to the Console:
                //Console.WriteLine("Data Message ID = {0}", result.Name);

                //Console.WriteLine("Press Enter to exit ...");
                //Console.ReadLine();
            }
        }
        public void SendPushNotification(FcmMessage message)
        {
            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();


                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                System.Console.WriteLine("Message ID = {0}", result.Name);
            }
        }
Exemplo n.º 17
0
        public void SendFcmMessageUsingProxyTest()
        {
            // This needs to be a valid Service Account Credentials File. Can't mock it away:
            var settings = FileBasedFcmClientSettings.CreateFromFile("your_project_id", @"D:\serviceAccountKey.json");

            // Define the Proxy URI to be used:
            var proxy = new Uri("http://localhost:8888");

            // Define the Username and Password ("1", because I am using Fiddler for Testing):
            var credentials = new NetworkCredential("1", "1");

            // Build the HTTP Client Factory:
            var httpClientFactory = new ProxyHttpClientFactory(proxy, credentials);

            // Initialize a new FcmHttpClient to send to localhost:
            var fcmHttpClient = new FcmHttpClient(settings, httpClientFactory);

            // Construct the Firebase Client:
            using (var client = new FcmClient(settings, fcmHttpClient))
            {
                // Construct the Notification Payload to send:
                var notification = new Notification
                {
                    Title = "Title Text",
                    Body  = "Notification Body Text"
                };

                // The Message should be sent to the News Topic:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Topic        = "news",
                        Notification = notification
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                Console.WriteLine(result);
            }
        }
Exemplo n.º 18
0
        public static void Main(string[] args)
        {
            // Leemos las credenciales de la cuenta de google services
            var settings = FileBasedFcmClientSettings.CreateFromFile(@"763532726491", @"C:\sample-notification-2c161-firebase-adminsdk-hjxo7-17f677fd81.json");

            // Construimos el cliente
            using (var client = new FcmClient(settings))
            {
                var notification = new Notification
                {
                    Title = "Plataforma Estudio Mobile",
                    Body  = "Notificando"
                };

                //Console.Write("Device Token: ");
                Console.Write("Ingresa el token del dispositivo: ");

                string registrationId = Console.ReadLine();

                // EL TOKEN VENCE CADA MEDIA HR MAS O MENOS. RECORDAR USAR EL METODO ON NEW TOKEN
                //  string registrationId = "";

                // Enviamos el mensaje al dispositivo correspondiente
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Token        = registrationId,
                        Notification = notification
                    }
                };

                // Enviamos el mensaje y esperamos el resultado
                CancellationTokenSource cts = new CancellationTokenSource();

                // Respuesta asincronica
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // mostrar resultado en la consola

                Console.WriteLine("Message ID = {0}", result.Name);
                Console.ReadLine();
                // Console.WriteLine("Mensaje enviado correctamente al dispositivo " + registrationId);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="deviceTokens">List of all devices assigned to a user</param>
 /// <param name="title">Title of notification</param>
 /// <param name="body">Description of notification</param>
 /// <param name="icon">Icon url of notification</param>
 /// <param name="data">Object with all extra information you want to send hidden in the notification</param>
 /// <returns></returns>
 public static async Task <bool> SendPushNotification(string[] deviceTokens, string title, string body, string icon, object data)
 {
     if (deviceTokens.Count() > 0)
     {
         var messageInformation = new FcmMessage()
         {
             notification = new FcmNotification()
             {
                 title = title,
                 body  = body,
                 icon  = icon
             },
             data             = data,
             registration_ids = deviceTokens
         };
         return(await SendPushNotification(messageInformation));
     }
     return(false);
 }
        public static void SendPushNotification(FcmMessage message)
        {
            //var settings = FileBasedFcmClientSettings.CreateFromFile("pushnotificationpoc-6a4f2", @"E:\New folder\Navvis\codebase\CoreoHome\Push Notification\serviceAccountKey.json");
            string startupPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;
            var    settings    = FileBasedFcmClientSettings.CreateFromFile("pushnotificationpoc-6a4f2", startupPath + "\\serviceAccountKey.json");

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                System.Console.WriteLine("Message ID = {0}", result.Name);
            }
        }
Exemplo n.º 21
0
        public static void Main(string[] args)
        {
            // Read the Credentials from a File, which is not under Version Control:
            var settings = FileBasedFcmClientSettings.CreateFromFile(@"your_project_id", @"D:\serviceAccountKey.json");

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                // Construct the Data Payload to send:
                var data = new Dictionary <string, string>()
                {
                    { "A", "B" },
                    { "C", "D" }
                };

                // Get the Registration from Console:
                Console.Write("Device Token: ");

                string registrationId = Console.ReadLine();

                // The Message should be sent to the given token:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Token = registrationId,
                        Data  = data
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                Console.WriteLine("Message ID = {0}", result.Name);

                Console.ReadLine();
            }
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            // Read the Service Account Key from a File, which is not under Version Control:
            var settings = FileBasedFcmClientSettings.CreateFromFile("nlbfffdev", @"C:\Users\Tyrone\source\repos\Test1707\Test1707\nlbfffdev-c66734f845a4.json");

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                // Construct the Data Payload to send:
                var data = new Dictionary <string, string>()
                {
                    { "A", "B" },
                    { "C", "D" }
                };

                // The Message should be sent to the News Topic:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Topic = "news",
                        Data  = data
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                System.Console.WriteLine("Message ID = {0}", result.Name);

                string SFNresult = SendFCMNotification("AIzaSyCcxDhm3-hRNpb1CG4CLS0cZ_VaPUFk2u8", "455828917963", "null");

                System.Console.WriteLine("SendFCMNotification result:", SFNresult);

                System.Console.ReadLine();
            }
        }
Exemplo n.º 23
0
        public async Task <FcmResponse> Send(FcmMessage message)
        {
            var httpClient = new HttpClient();

            // Authorization key is needed to Authenticating your request
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Key={_serverKey}");
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("sender_id", _senderId);

            var dataJson = JsonConvert.SerializeObject(message,
                                                       Formatting.None,
                                                       new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
            var response = await httpClient.PostAsync(_fcmServerUrl, new StringContent(dataJson, Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <FcmResponse>(responseBody));
        }
Exemplo n.º 24
0
        public void SendFcmMessageByToken()
        {
            FcmMessage message = new FcmMessage
            {
                DryRun          = true,
                RegistrationIds = new System.Collections.Generic.List <string>()
                {
                    _deviceId.Value, _deviceId2.Value
                },
                Notification = new FcmNotification
                {
                    Title = "test using c# unit test",
                    Body  = "test"
                }
            };
            FcmSender sender   = new FcmSender(_serverKey.Value, _senderId.Value);
            var       response = sender.Send(message);

            Assert.AreNotEqual(response.Result.Results[0].Error, string.Empty);
            Assert.AreNotEqual(response.Result.Results[1].Error, string.Empty);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="to">token of a user or a topic name i.e. /topic/topice_name</param>
        /// <param name="title">Title of notification</param>
        /// <param name="body">Description of notification</param>
        /// <param name="icon">Icon url of notification</param>
        /// <param name="data">Object with all extra information you want to send hidden in the notification</param>
        /// <returns></returns>
        public static async Task <bool> SendPushNotification(string to, string title, string body, string icon, object data)
        {
            if (!string.IsNullOrEmpty(to) && !string.IsNullOrWhiteSpace(to))
            {
                //Object creation

                var messageInformation = new FcmMessage()
                {
                    notification = new FcmNotification()
                    {
                        title = title,
                        body  = body,
                        icon  = icon
                    },
                    data = data,
                    to   = to
                };
                return(await SendPushNotification(messageInformation));
            }
            return(false);
        }
Exemplo n.º 26
0
        public static void Main(string[] args)
        {
            // Read the Credentials from a File, which is not under Version Control:
            var settings = FileBasedFcmClientSettings.CreateFromFile(@"D:\serviceAccountKey.json");

            // Construct the Client:
            using (var client = new FcmClient(settings))
            {
                var notification = new Notification
                {
                    Title = "Notification Title",
                    Body  = "Notification Body Text"
                };

                // The Message should be sent to the News Topic:
                var message = new FcmMessage()
                {
                    ValidateOnly = false,
                    Message      = new Message
                    {
                        Topic        = "news",
                        Notification = notification
                    }
                };

                // Finally send the Message and wait for the Result:
                CancellationTokenSource cts = new CancellationTokenSource();

                // Send the Message and wait synchronously:
                var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult();

                // Print the Result to the Console:
                Console.WriteLine("Data Message ID = {0}", result.Name);

                Console.WriteLine("Press Enter to exit ...");
                Console.ReadLine();
            }
        }
Exemplo n.º 27
0
        public async void SendFcmMessageByGroupKey()
        {
            // Create a test group
            var groupName       = $"Group-{Guid.NewGuid().ToString()}";
            var fcmGroupHandler = new FcmGroupHandler(_serverKey.Value, _senderId.Value);
            var groupKey        = await fcmGroupHandler.AddTokenToGroup(groupName, new string[] { _deviceId.Value });

            // Send message by created group
            FcmMessage message = new FcmMessage
            {
                DryRun       = true,
                To           = groupKey,
                Notification = new FcmNotification
                {
                    Title = "test using c# unit test",
                    Body  = "test"
                }
            };
            FcmSender sender   = new FcmSender(_serverKey.Value, _senderId.Value);
            var       response = sender.Send(message);

            Assert.AreEqual(response.Result.Results, null);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Builds the <see cref="FcmMessage" /> and returns it.
        /// </summary>
        /// <returns>A sendable <see cref="FcmMessage" />-object.</returns>
        /// <exception cref="System.Exception">Thrown when the message would not be valid.</exception>
        public FcmMessage Build()
        {
            _msg.RegistrationIds = new List <string>();
            foreach (var token in _deviceTokens)
            {
                _msg.RegistrationIds.Add(token);
            }

            //Error: 400 Bad Request when registration_ids is empty!
            //Send Multiple Notifications when RegistrationIds.Count()>=1000
            var count = _msg.RegistrationIds.Count;

            if (count == 0 || count >= 1000)
            {
                throw new FcmMessageBuilderException($"FcmMessage creation failed. Invalid token count: {count}");
            }

            var msg = _msg;

            _msg = null;

            return(msg);
        }
Exemplo n.º 29
0
        public async Task SendNotification(string title, string body, string link, string icon, string topic)
        {
            if (bool.Parse(_settingsKeeper.GetSetting("EnableFcm").Value))
            {
                var notification = new Notification
                {
                    Title = title,
                    Body  = body
                };

                var fcmMessage = new FcmMessage
                {
                    Message = new Message
                    {
                        Notification  = notification,
                        Topic         = topic,
                        WebpushConfig = new WebpushConfig
                        {
                            Headers = new Dictionary <string, string>
                            {
                                { "urgency-option", "high" }
                            },
                            FcmOptions = new WebpushFcmOptions
                            {
                                Link = link
                            }
                        },
                        Data = new Dictionary <string, string>
                        {
                            { "icon", icon }
                        }
                    }
                };

                await _fcmClient.SendAsync(fcmMessage);
            }
        }
Exemplo n.º 30
0
 public async Task SendAsync(FcmMessage message, CancellationToken cancellationToken = default)
 {
     var content  = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8, "application/json");
     var response = await Client.PostAsync("send", content, cancellationToken);
 }