public void SendBatchMessages() { // This is a list of Tokens I want to send the Batch Message to: var tokens = File.ReadAllLines(@"D:\device_tokens.txt"); // 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)) { Message message = new Message { Notification = new Notification { Title = "Notification Title", Body = "Notification Body Text" } }; // Finally send the Message and wait for the Result: CancellationTokenSource cts = new CancellationTokenSource(); // Send the Message and wait synchronously: var result = client.SendMulticastMessage(tokens, message, false, cts.Token).GetAwaiter().GetResult(); // Print the Result to the Console: foreach (var response in result.Responses) { Assert.IsNotNull(response.Name); } } }
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 async Task ExponentialBackoff503TooFewRetriesTest() { // Construct new ExponentialBackOffSettings: var exponentialBackOffSettings = new ExponentialBackOffSettings(2, TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30)); // This needs to be a valid Service Account Credentials File. Can't mock it away: var settings = FileBasedFcmClientSettings.CreateFromFile("project", @"D:\serviceAccountKey.json", exponentialBackOffSettings); // Initialize a new FcmHttpClient to send to localhost: var client = new FcmHttpClient(settings); // Construct a Fake Message: var builder = new HttpRequestMessageBuilder("http://localhost:8081/return503_UntilRequestFour", HttpMethod.Get); CancellationToken longLivingCancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(5)).Token; bool fcmHttpExceptionWasThrown = false; try { await client.SendAsync(builder, longLivingCancellationToken); } catch (FcmHttpException) { fcmHttpExceptionWasThrown = true; } Assert.IsTrue(fcmHttpExceptionWasThrown); }
public MessagingService(IMessagingQueries messagingQueries, IMessagingRepository messagingRepository) { string serviceAccountKeyPath = GlobalConfiguration.GetByKey(AppConfigs.ServiceAccountKeyPathConfigKey); var settings = FileBasedFcmClientSettings.CreateFromFile(serviceAccountKeyPath); _fcmClient = new FcmClient(settings); _messagingQueries = messagingQueries; _messagingRepository = messagingRepository; }
private static ISchedulerService CreateSchedulerService() { // lee las credenciales de este servicio var settings = FileBasedFcmClientSettings.CreateFromFile(@"C:\sample-notification-2c161-firebase-adminsdk-hjxo7-17f677fd81.json"); // contruir el cliente var client = new FcmClient(settings); return(new SchedulerService(client)); }
public FirebaseCloudMessaging(SettingsKeeper settingsKeeper) { _settingsKeeper = settingsKeeper; if (bool.Parse(settingsKeeper.GetSetting("EnableFcm").Value)) { var settings = FileBasedFcmClientSettings.CreateFromFile($"{Utils.CurrentDirectory.FullName}{Path.DirectorySeparatorChar}fcmkey.json"); _fcmClient = new FcmClient(settings); } }
private static ISchedulerService CreateSchedulerService() { // Read the Credentials from a File, which is not under Version Control: var settings = FileBasedFcmClientSettings.CreateFromFile(@"D:\serviceAccountKey.json"); // Construct the Client: var client = new FcmClient(settings); return(new SchedulerService(client)); }
public async Task ExponentialBackoff503Test() { // This needs to be a valid Service Account Credentials File. Can't mock it away: var settings = FileBasedFcmClientSettings.CreateFromFile("project", @"D:\serviceAccountKey.json"); // Initialize a new FcmHttpClient to send to localhost: var client = new FcmHttpClient(settings); // Construct a Fake Message: var builder = new HttpRequestMessageBuilder("http://localhost:8081/return503_UntilRequestFour", HttpMethod.Get); CancellationToken longLivingCancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(5)).Token; await client.SendAsync(builder, longLivingCancellationToken); }
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 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 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(); } }
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); } }
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 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); } }
private void InitFcmClient() { var settings = FileBasedFcmClientSettings.CreateFromFile(firebaseConfig.AdminSdkFile); fcmClient = new FcmClient(settings); }
public static void AddFcm <TDbContext>(this KaspDbServiceBuilder builder, string projectName, string filePath) where TDbContext : DbContext, IFcmDbContext { builder.Services.AddSingleton <IFcmClientSettings>(FileBasedFcmClientSettings.CreateFromFile(projectName, filePath)); AddServices <TDbContext>(builder); }
public PushNotificationService() { settings = FileBasedFcmClientSettings.CreateFromFile("pushnotificationpoc-6a4f2", @"E:\New folder\Navvis\codebase\CoreoHome\Push Notification\serviceAccountKey.json"); }
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 <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); }