public void TestTopicMessageWithRetryDateTimeOffset() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_WithRetry"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); bool isRetryExceptionCaught = false; try { var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); } catch (FcmRetryAfterException e) { RetryConditionValue retryConditionValue = e.RetryConditionValue; Assert.IsNotNull(retryConditionValue); Assert.IsNull(retryConditionValue.Delta); // Fri, 31 Dec 1999 23:59:59 GMT Assert.AreEqual(new DateTimeOffset(1999, 12, 31, 23, 59, 59, TimeSpan.FromHours(0)), retryConditionValue.Date); isRetryExceptionCaught = true; } Assert.AreEqual(true, isRetryExceptionCaught); } }
public void TestTopicMessageWithRetryTimeSpan() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_WithRetryTimeSpan"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); bool isRetryExceptionCaught = false; try { var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); } catch (FcmRetryAfterException e) { RetryConditionValue retryConditionValue = e.RetryConditionValue; Assert.IsNotNull(retryConditionValue); Assert.IsNull(retryConditionValue.Date); // 1 Minute Delta Assert.AreEqual(retryConditionValue.Delta, TimeSpan.FromMinutes(1)); isRetryExceptionCaught = true; } Assert.AreEqual(true, isRetryExceptionCaught); } }
public void TestTopicMessageInternalServerErrorWithouRetry() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_InternalServerError_WithoutRetry"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); bool isRetryExceptionCaught = false; bool isGeneralExceptionCaught = false; try { var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); } catch (FcmRetryAfterException) { isRetryExceptionCaught = true; } catch (FcmGeneralException) { isGeneralExceptionCaught = true; } Assert.AreEqual(false, isRetryExceptionCaught); Assert.AreEqual(true, isGeneralExceptionCaught); } }
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); } }
public void TestServer() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_OK"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); Assert.AreEqual(1234, result.MessageId); Assert.AreEqual(null, result.ErrorCode); } }
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); } }
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); } }
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); } }
public void TestHttpClientWithProxy() { // Settings to be used: IFcmClientSettings settings = new FileBasedFcmClientSettings("/Users/bytefish/api.key"); // The Proxy Address: Uri proxyUri = new Uri(string.Format("{0}:{1}", "<proxy_address>", "<proxy_port>")); // Credentials for the Proxy: ICredentials proxyCredentials = new NetworkCredential( "<proxy_username>", "<proxy_password>" ); // Define the Proxy: IWebProxy proxy = new WebProxy { ProxyUri = proxyUri, Credentials = proxyCredentials }; // Now create a client handler with the Proxy settings: HttpClientHandler httpClientHandler = new HttpClientHandler() { Proxy = proxy, PreAuthenticate = true, UseDefaultCredentials = false, }; // Build the Custom FcmHttpClient: FcmHttpClient fcmHttpClient = new FcmHttpClient(settings, new HttpClient(httpClientHandler), JsonSerializer.Default); // Build the HttpClient: using (var client = new FcmClient(settings, fcmHttpClient)) { CancellationTokenSource cts = new CancellationTokenSource(); // Build the message: var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); // And send the message: var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); } }
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); } }
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(); } }
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(); } }
public void TestUnauthorized() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_Unauthorized"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); bool isAuthenticationException = false; try { var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); } catch (FcmAuthenticationException) { isAuthenticationException = true; } Assert.AreEqual(true, isAuthenticationException); } }
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(); } }
public static void Main(string[] args) { // Read the API Key from a File, which is not under Version Control: var settings = new FileBasedFcmClientSettings("/Users/bytefish/api.key"); // Construct the Client: using (var client = new FcmClient(settings)) { // Construct the Data Payload to send: var data = new { A = new { a = 1, b = 2 }, B = 2, }; // Options for the Message: var options = FcmMessageOptions.Builder() .setTimeToLive(TimeSpan.FromDays(1)) .Build(); // The Message should be sent to the News Topic: var message = new TopicUnicastMessage <dynamic>(options, new Topic("news"), 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("Result = {0}", result); } }
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); } }
public void TestAuthHeaderIsInRequest() { using (var client = new FcmClient(new IntegrationTestOptions("TopicMessage_HasAuthHeader"))) { CancellationTokenSource cts = new CancellationTokenSource(); var message = new TopicUnicastMessage <int>(new FcmMessageOptionsBuilder().Build(), new Topic("a"), 1); bool didThrow = false; try { var result = client.SendAsync(message, cts.Token).GetAwaiter().GetResult(); Assert.IsNotNull(result); } catch (Exception) { didThrow = true; } Assert.AreEqual(false, didThrow); } }
public async Task <JObject> sendMessage([FromBody] JObject input) { var id = input.Value <string>("id"); var title = input.Value <string>("title"); var message = input.Value <string>("message"); var time = input.Value <string>("time"); var channels = input.Value <JArray>("channels"); foreach (var item in channels.Children()) { int channelId = item.Value <int>("id"); _logger.LogError($"channelId:{channelId}"); string[] strDeviceTokens = item.Value <JArray>("device_token")?.ToObject <string[]>(); var channel = _dbContext.Channels.Find(channelId); if (channel == null) { continue; } _logger.LogError($"channel:{channel}"); // APP if (channel.Type == 3) { var subscriberTypes = new int[] { (int)Subscribers.Types.IOS, (int)Subscribers.Types.Android }; var subscribers = strDeviceTokens == null? _dbContext.Subscribers.Where(q => q.DeletedAt == null && q.Status == (byte)Subscribers.Statuses.Enable && subscriberTypes.Contains((int)q.Type) && q.ChannelId == channelId).ToList() : _dbContext.Subscribers.Where(q => q.DeletedAt == null && q.Status == (byte)Subscribers.Statuses.Enable && subscriberTypes.Contains((int)q.Type) && q.ChannelId == channelId && strDeviceTokens.Contains(q.DeviceToken)).ToList();; _logger.LogError($"subscribers:{subscribers.Count}"); if (subscribers.Count == 0) { continue; } _logger.LogError($"{_fir_folder}{Path.DirectorySeparatorChar}{channel.ChannelKey}"); //var settings = FileBasedFcmClientSettings.CreateFromFile($"{_fir_folder}{Path.DirectorySeparatorChar}{channel.ChannelKey}"); //var settings = new FcmClientSettings("wildmud-push", "{\"type\": \"service_account\", \"project_id\": \"wildmud-push\", \"private_key_id\": \"e37f921cee98f70c23060141e72eeedcbe9e1b4b\", \"private_key\": \"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjp+HcD59jTpV0\nSK7RtU5tZcKGpwejduRLM83qAFlI1hPON7IPxOn25r2yMEVrr5CTcrkN1i1R8rJn\nO2alxIDODnt8j+TxoSLgUCnjx4Z0PlWjXXTTTzXY1q+3KjDZUEsCp/6cu2vDl36C\ngq87L5PIsc7tkMscMkTJALrlBtTnGxNHLPP5S2025y3x1ShgLk/dFpXaqPjdEe+f\n3YaDwKil8j/nXS6t6CRaEsWFyXsGgV2B2GJBFAZzW2XagPEiAGF5LWDpXuViS328\n94/oqu+50BE4OGZiXmkJAHEgYyEUueTlrMd+8dw4kuadh6NmvY8Feric7ATZNXxF\nMev9Ds7tAgMBAAECggEAUQa8OQeVGwZb0axwvYxeLaS9uIw3KHQjWKZn80zD599y\nA94ob01Hp0Ibtn7WyBeu5Ynd3F9npdSbBqhuzHDrctnRwty9dfKZQWT/MHLne2Mn\nZFBPmJV1rAuzCOU/NUDfOovxcCkNFFRLwxMv7gZCzZFXSeCv5yBuVPRjFCSbQWYm\n5Q9ilRoo0fVAvWiYsEYBZvf0n7xR7Q3kiutKSkCVxzoyU4d6mo+hmZGzlSYYbkp5\n7ytoFe4K6C+ej6+2HT8ZGlC6TOYI3Bx42E78TMGwj2OGukrOsicRc9Lra2D6TFIp\ncb7s7X8VkF4ORjqEPvzye/K+jLUsjs9bpqLEtfITowKBgQDk3sRBrtNbsONWiDDS\n6DgK/EcRERJmzjOl1Zemhmfsbtrx2pXTm7kKDXDpRzwHI0VQzYCdMRgUv+BGCZhS\nwNCsq6GCRFIWv2WQFODnU+RjagJCbRouQC357Wh/meGsckL75bF0usTyRMgrumQ/\nIaaMbOfYmj69S6J5myjDIPWvNwKBgQC3DiMawQ+G6rjbQvTLvl8uNx3n4FCWgUEP\n6r2BHLJ74F41es4+DG88kAX/rZMV1PR7DVn1B2o7LP9WXuWZN1eBwuqXluGpFZRq\npX192Ushp5Zv6uvH3SgN6nMl6BDxj6vvPMjT++FerSefMjvblNNGC6ub8ljx2wcd\ndSLdiA4c+wKBgGhYI9PqV9RK3iraZqARXVOs1t2yEdirFCL8MWqrhn/lvo5bYMmc\nCo3JuPuyDW0XqIeBWazQ8DCtlht4TmkUHU9L5JOWgHJ8ilpZGnx84/hrIWKViUUi\n35M9qNHcH2ZWpbFgdDpK2HW35CcDkKazudH16PH4yLfW3tlgYwIrabebAoGBAJu3\n9PjfXpwAtDwhGyjuyvz/efs0gJlnXrdxkr9wcAyc8sc/ro5t+XplchTrzQF3ZHoB\nA5NDOYUZZCRPGbVatJ/39aP6gABcESMfoD8cR6NbcsfF6cjdQyODW2zVmwRCmZor\n9RMPY8osNlZgXzcNxSQC7Xr9j9g94DGY4Y3eHVNdAoGAVnPc7R1/JSxi0ZgHUGlo\nTPqIvOJaXdHa2t7kxHuZmFk6AYREnQq9tD2VmtvOQHsUAHp4+xFNITv+bfvfBk2f\nuX/8iTnyIXt73qumxh6VEdqroFqhsupirE86fr8eoYyvAxFzsgrk+xo2320dMPCb\nKuyPRjFBhPqOxRhdBxnti+g=\n-----END PRIVATE KEY-----\n\", \"client_email\": \"[email protected]\", \"client_id\": \"112247404943112944715\", \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\", \"token_uri\": \"https://oauth2.googleapis.com/token\", \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\", \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-6ov47%40wildmud-push.iam.gserviceaccount.com\"}"); var fcmKeyObject = JObject.Parse(channel.SecretKey); var projectId = fcmKeyObject.Value <string>("project_id"); var settings = new FcmClientSettings(projectId, channel.SecretKey); using (var client = new FcmClient(settings)) { var notification = new Notification { Title = title, Body = message }; foreach (var subscriber in subscribers) { try { // The Message should be sent to the News Topic: var msg = new FcmMessage() { ValidateOnly = false, Message = new Message { //Topic = "news", Token = subscriber.DeviceToken, 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(msg, cts.Token).GetAwaiter().GetResult(); _logger.LogInformation($"Data Message ID = {result.Name}"); } catch (Exception ex) { _logger.LogInformation($"Exception: {ex.ToString()}"); continue; } } //return new JObject(){ // { "code", 200}, // { "reason", "scuesss" }, // { "data", new JObject(){{ "message_id", result.Name }} } //}; } } // Line if (channel.Type == 4) { var subscriberTypes = new int[] { (int)Subscribers.Types.Line }; var subscribers = strDeviceTokens == null? _dbContext.Subscribers.Where(q => q.DeletedAt == null && q.Status == (byte)Subscribers.Statuses.Enable && subscriberTypes.Contains((int)q.Type) && q.ChannelId == channelId).ToList() : _dbContext.Subscribers.Where(q => q.DeletedAt == null && q.Status == (byte)Subscribers.Statuses.Enable && subscriberTypes.Contains((int)q.Type) && q.ChannelId == channelId && strDeviceTokens.Contains(q.DeviceToken)).ToList();; _logger.LogError($"subscribers:{subscribers.Count}"); if (subscribers.Count == 0) { continue; } foreach (var subscriber in subscribers) { try { var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {channel.SecretKey}"); var data = new { to = subscriber.DeviceToken, messages = new[] { new { type = "text", text = message, } } }; var json = JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); content.Headers.ContentLength = json.Length; var result = await client.PostAsync("https://api.line.me/v2/bot/message/push", content); _logger.LogError($"result.Content.ToString(): {result}"); } catch (Exception ex) { _logger.LogError($"Exception: {ex.ToString()}"); continue; } } } } dynamic output = new JObject(); output["message_id"] = 3345678; dynamic res = new JObject(); res.code = 200; res.reason = "success"; res.data = output; return(res); }
private void SendPushNotification(Domain.Entities.Notification dto) { try { var settings = FileBasedFcmClientSettings.CreateFromFile("alzagro-5bc7e", HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FirebaseJsonPath"])); // Construct the Client: using (var client = new FcmClient(settings)) { // Construct the Data Payload to send: var dtoData = Mapper.Map <Domain.Entities.Notification, NotificationDataDto>(dto); var data = dtoData.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .ToDictionary(prop => prop.Name, prop => prop.GetValue(dtoData, null) == null ? "" : prop.GetValue(dtoData, null).ToString()); // The Message should be sent to the News Topic: var message = new FcmMessage() { ValidateOnly = false, Message = new Message { Data = data, Token = dto.Device.Token, Notification = new FcmSharp.Requests.Notification() { Title = dtoData.Title, Body = dtoData.Message } } }; switch (dto.Device.DeviceType) { case "ios": // iOS break; case "android": // Android message.Message.AndroidConfig = new AndroidConfig { Priority = AndroidMessagePriorityEnum.HIGH, Notification = new AndroidNotification() { Title = "ALZAGRO", Body = dtoData.Title + ". " + dtoData.Message, Icon = "ic_icon", Color = "#7BA529", Sound = "default" } }; if (dto.ExpireDateTime != null) { message.Message.AndroidConfig.TimeToLive = dto.ExpireDateTime - this.timeService.LocalDateTimeNow; } break; } // 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(); } } catch (Exception e) { string str = e.Message; } }
public async Task <FcmMessageResponse> SendAsync(FcmMessage message, CancellationToken cancellationToken = default) { return(await FcmClient.SendAsync(message, cancellationToken)); }
public async Task <bool> SendPushNotification(string deviceToken, PushNotification notification, int badge = 0, bool testMode = false) { bool sent = false; // The Message should be sent to the News Topic: var message = new FcmMessage() { ValidateOnly = false, Message = new Message { Token = deviceToken, Data = notification.Data != null?notification.Data.GetDictionary() : null, AndroidConfig = new AndroidConfig { CollapseKey = notification.Data.ThreadId, Data = notification.Data != null?notification.Data.GetAndroidDictionary(notification.Title, notification.Body, badge) : null, }, ApnsConfig = new ApnsConfig { Payload = new ApnsConfigPayload { Aps = new Aps { Alert = new ApsAlert { Title = notification.Title, Body = notification.Body }, Badge = badge, Sound = "default", CustomData = notification.Data != null?notification.Data.GetData() : null, ThreadId = notification.Data.ThreadId } } } } }; var jsonBody = JsonConvert.SerializeObject(message); PushNotificationLog log = new PushNotificationLog { DeviceToken = deviceToken, Title = notification.Title, Body = notification.Body, DataJSON = jsonBody, CreatedAt = DateTime.UtcNow, Status = SendingStatus.Failed }; try { // Read the Service Account Key from a File, which is not under Version Control: var settings = FileBasedFcmClientSettings.CreateFromFile(_configuration["FCM:ProjectId"], _configuration["FCM:KeyPath"]); // 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 = await client.SendAsync(message, cts.Token); log.Status = SendingStatus.Success; sent = true; } } catch (Exception ex) { _logger.LogError($"FCM Service: {ex}"); sent = false; if (testMode) { throw; } } finally { _unitOfWork.Repository <PushNotificationLog>().Insert(log); _unitOfWork.SaveChanges(); } return(sent); }