コード例 #1
0
        public async Task <object> SendNotification(string token, string title, string body)
        {
            try
            {
                var result = await _messaging.SendAsync(CreateNotification(title, body, token));

                return(result);
            }
            catch (FirebaseException ex)
            {
                return(ex.Message);
            }
        }
コード例 #2
0
        public async Task <ActionResult> SendCustomNotifiation([FromBody] NotificationModel notificationModel)
        {
            try
            {
                Message message = new Message()
                {
                    Notification = new Notification
                    {
                        Title = notificationModel.Title,
                        Body  = notificationModel.Message
                    },
                    Token = notificationModel.Token
                };

                FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;
                string            result    = await messaging.SendAsync(message);

                Console.WriteLine(result);
                return(Ok());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(BadRequest());
            }
        }
コード例 #3
0
        public async Task <string> SendMessage(Message message)
        {
            var result = await firebaseMessaging.SendAsync(message);

            logger.LogInformation($"Message {result} sent successfully.");
            return(result);
        }
コード例 #4
0
        public async Task Consume(ConsumeContext <PublishMessage> context)
        {
            var contextMessage = context.Message;

            if (contextMessage.EndpointType != EndpointType.Fcm)
            {
                return;
            }

            var cancellationToken = context.CancellationToken;

            var endpoint = FcmEndpoint.FromPublishMessage(contextMessage);

            const string title = "Free TON Notification";
            var          msg   = new Message {
                Notification = new Notification {
                    Title = title,
                    Body  = contextMessage.Message.Text
                },
                Token = endpoint.Token
            };

            if (_firebaseMessaging == null)
            {
                throw new NoFirebaseMessagingException("No Firebase Messaging Instance. Make sure that file firebase-key.json exists");
            }
            _logger.LogTrace("FCM Message {@Message}", msg);
            await _firebaseMessaging.SendAsync(msg, cancellationToken);
        }
コード例 #5
0
        public async Task GetMessagingWithClientFactory()
        {
            var handler = new MockMessageHandler()
            {
                Response = new FirebaseMessagingClient.SingleMessageResponse()
                {
                    Name = "test-response",
                },
            };
            var factory = new MockHttpClientFactory(handler);

            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential        = GoogleCredential.FromAccessToken("test-token"),
                HttpClientFactory = factory,
                ProjectId         = "test-project",
            });
            FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);

            Assert.NotNull(messaging);
            Assert.Same(messaging, FirebaseMessaging.GetMessaging(app));

            var response = await messaging.SendAsync(new Message()
            {
                Topic = "test-topic"
            });

            Assert.Equal("test-response", response);
            app.Delete();
        }
コード例 #6
0
        public async Task <bool> SendAsync(string registeredUserDeviceToken, string title, string body)
        {
            string result = await _firebaseMessaging.SendAsync(Notification(registeredUserDeviceToken, title, body));

            //test
            return(true);
        }
コード例 #7
0
ファイル: FirebaseServices.cs プロジェクト: Aguvar/cheeseIT
        public async Task SendNotification(string token, string title, string body)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                token = _defaultToken;
            }

            var result = await messaging.SendAsync(CreateNotification(title, body, token));
        }
コード例 #8
0
        public async ETTask <bool> SendOneNotification(string token, string title, string body)
        {
            // 使用WebApi的方式
            //if (string.IsNullOrEmpty(token))
            //{
            //    return false;
            //}
            //BsonDocument bson = new BsonDocument();
            //bson["to"] = token;
            //bson["notification"] = new BsonDocument();
            //bson["notification"]["title"] = title;
            //bson["notification"]["body"] = body;
            //bson["notification"]["icon"] = "big_icon";
            //return await Post(firebaseUrl, bson);

            if (string.IsNullOrEmpty(token))
            {
                return(false);
            }

            try
            {
                Message message = new Message();
                message.Token   = token;
                message.Android = new AndroidConfig
                {
                    Notification = new AndroidNotification
                    {
                        Icon = "big_icon",
                    },
                };
                message.Notification = new Notification
                {
                    Title = title,
                    Body  = body,
                };

                string messageId = await firebaseMessaging.SendAsync(message);

                if (string.IsNullOrEmpty(messageId))
                {
                    Log.Error($"To send firebase notification is failed!, Token: {token}");
                    return(false);
                }
                else
                {
                    Log.Info($"To send firebase notification is successful! MessageID: {messageId}");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"To send firebase notification is failed! Message: {ex.Message}, Stack: {ex.StackTrace}");
                return(false);
            }
        }
コード例 #9
0
 public Task <string> SendAsync(string token)
 {
     return(messaging?.SendAsync(new Message
     {
         Android = new AndroidConfig
         {
             Priority = Priority.High
         },
         Data = new Dictionary <string, string> {
             { "Action", "FetchMessages" }
         },
         Token = token
     }) ?? Task.FromResult(string.Empty));
 }
コード例 #10
0
        public async Task SendNotification(string token, string notificationBody,
                                           string notificationTitle)
        {
            if (_messaging != null)
            {
                var result = await _messaging.SendAsync(CreateMessage(token, notificationBody, notificationTitle));

                _logger.LogInformation($"Sent notification result.");
            }
            else
            {
                _logger.LogError("No FCM application credentials found.");
            }
        }
コード例 #11
0
        public async Task UseAfterDelete()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = MockCredential
            });
            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;

            app.Delete();
            await Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await messaging.SendAsync(new Message()
            {
                Topic = "test-topic"
            }));
        }
コード例 #12
0
        protected async Task <bool> SendNotification(Message message, FirebaseMessaging messaging)
        {
            try
            {
                string response = await messaging.SendAsync(message);

                Logger.LogInfo(LogCategory.Processor, "sendNotif", $"Seccessfully send message: {response}");
            }
            catch (Exception ex)
            {
                Logger.LogError(LogCategory.Processor, "sendNotif", ex.ToString());
                return(false);
            }
            return(true);
        }
コード例 #13
0
        public async Task SendSuspiciousAddressesToMobileClient(List <Address> addresses)
        {
            Console.WriteLine("SendSuspiciousAddressesToMobileClient");
            FirebaseMessaging firebaseMessaging = FirebaseMessaging.GetMessaging(FirebaseApp.DefaultInstance);
            var response = await firebaseMessaging.SendAsync(new Message()
            {
                Topic        = "Suspicious",
                Notification = new Notification()
                {
                    Title = "Suspicious",
                    Body  = JsonSerializer.Serialize(addresses)
                }
            });

            Console.WriteLine(response);
        }
コード例 #14
0
        /// <summary>
        /// prepare and send message to firebase servers
        /// </summary>
        /// <param name="notification">user notification</param>
        private async Task SendMessageAsync(PushNotification notification, CancellationToken cancellation = default)
        {
            var message = new Message
            {
                Data  = notification.PushNotificationProperties.Payload,
                Token = notification.PushNotificationProperties.DeviceToken
            };

            try
            {
                await firebaseMessaging.SendAsync(message, cancellation);

                logger.LogInformation($"UserId, {notification.User.UserId}, had a notification sent.");
            }
            catch (Exception e)
            {
                logger.LogError($"User, {notification.User.UserId}, failed to send push notification. Exception details: {e.InnerException}.");
                throw new HttpRequestException(
                          $"There was an issue sending a request to firebase push notification services. exception: {e}. Exception Details: {e.InnerException}.");
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string currentDirectory = Directory.GetCurrentDirectory();
            string path             = Path.Combine(currentDirectory, "etutorapp-25808-firebase-adminsdk-exwmv-656a0fd3f9.json");

            Console.WriteLine(path);
            Console.WriteLine("\n");

            string json = File.ReadAllText(path, Encoding.UTF8);

            var firebase = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(json)
            });

            Console.WriteLine(firebase.Name);

            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;

            Message message = new Message
            {
                Notification = new Notification
                {
                    Title = "Simple Notification",
                    Body  = "Part of the body"
                },
                Token =
                    "crhm711-RDw:APA91bFtsuksmqhOzzGe7efmkRJIG7kknhZb31XsUJZszB1mkd3suKggOiTU6UShSUMKD4PT_SXz4E7VMeZDsk_kZbj1uUx005chJlcIe1dXINroX_T7tJmjNPiKuEfyVGZwCnLw2jAE"
            };

            var result = messaging.SendAsync(message);

            Task.WaitAll();

            Console.WriteLine($"RESULT MESSAGE: {result.Result}");
        }
コード例 #16
0
        public async Task <string> SendNotification(NotifyDTO notifyDTO)
        {
            var defaultApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "keys.json")),
            });

            var message = new Message()
            {
                Notification = new Notification
                {
                    Title    = notifyDTO.Title,
                    Body     = notifyDTO.Body,
                    ImageUrl = notifyDTO.ImageURL,
                },
                Condition = "!('anytopicyoudontwanttouse' in topics)"
            };
            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance ?? FirebaseMessaging.DefaultInstance;

            var result = await messaging.SendAsync(message);

            FirebaseApp.DefaultInstance.Delete();
            return(result);
        }
コード例 #17
0
        public async Task <string> SendNotificationAsync(Message message)
        {
            var result = await _firebaseMessaging.SendAsync(message, false);

            return(result);
        }
コード例 #18
0
ファイル: Notification.cs プロジェクト: haidoan9205/fnews
 public async Task SendNotification(string token, string title, string body)
 {
     var result = await messaging.SendAsync(CreateNotification(title, body, token));
 }