angelobelchior / fcm.net Goto Github PK
View Code? Open in Web Editor NEWBiblioteca para facilitar envio de Push Notification usando o Firebase Cloud Messaging do Google
License: MIT License
Biblioteca para facilitar envio de Push Notification usando o Firebase Cloud Messaging do Google
License: MIT License
i dont know which language this can you add the read me to english
In my web app when I try to send a message second time I get this exception. This is because HttpClient is static and it is disposed after the first usage.
What is the reason to make it static?
{
class Program
{
static void Main(string[] args)
{
SendNotification();
}
private static async void SendNotification()
{
try
{
var serverKey = "XXXX";
var senderId = "XXXXX";
string registrationId = "XXXXX";
using (var sender = new Sender(serverKey, senderId))
{
var message = new Message
{
RegistrationIds = new List<string> { registrationId },
Notification = new Notification
{
Title = "Test from FCM.Net",
Body = $"Hello World@!{DateTime.Now.ToString()}"
}
};
var result = await sender.SendAsync(message);
Console.WriteLine($"Success: {result.MessageResponse.Success}");
var json = "{\"notification\":{\"title\":\"json message\",\"body\":\"works like a charm!\"},\"to\":\"" + registrationId + "\"}";
result = await sender.SendAsync(json);
Console.WriteLine($"Success: {result.MessageResponse.Success}");
}
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
}
}
}
`
Following is my code:
public async Task SendPushNotification(string deviceToken, Notification notification, object data)
{
var serverKey = _configuration["FCMServerKey"];
bool sent = false;
if (!String.IsNullOrEmpty(deviceToken))
{
using (var sender = new Sender(serverKey))
{
var message = new Message
{
To = deviceToken,
Priority = Priority.High,
ContentAvailable = true,
Notification = notification,
Data = data
};
var result = await sender.SendAsync(message);
Console.WriteLine($"Success: {result.MessageResponse.Success}");
sent = result.MessageResponse.Success == 1;
}
}
return sent;
}
And I got this error:
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication1 application) 2018-12-10 15:12:17.6160|Default|0HLIUDJT5GOSP:00000007||Microsoft.AspNetCore.Server.Kestrel|ERROR|Connection id "0HLIUDJT5GOSP", Request id "0HLIUDJT5GOSP:00000007": An unhandled exception was thrown by the application. System.OperationCanceledException: The operation was canceled. at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task
1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at FCM.Net.Sender.SendAsync(HttpContent content)
at FCM.Net.Sender.SendAsync(Message message)
at Nova.Api.Tools.FCMPushNotification.SendPushNotification(String deviceToken, Notification notification, Object data) in E:\NovaGitProjects\Nurish\Nurish\SourceCode\Server\src\Nova.Pms.Modules\Nova.Api\Tools\FCM\FCMPushNotification.cs:line 81
at Nova.Api.Controllers.PlanController.RespondActivity(RespondRequestDto request) in E:\NovaGitProjects\Nurish\Nurish\SourceCode\Server\src\Nova.Pms.Modules\Nova.Api\Controllers\PlanController.cs:line 281
sorry for my question, but I am not able to generate the registrationId, what would be the code to do that.?
Hi
I want to send notifications to about 30K users, so How many users can I notify at the same time with FCM.net ?
Hi, I'm using in my APi. It works perfectly on Android. On iOS doesn't work in version 10. I tried to send from Firebase console and RESTer. It works!!
obs: The others iOS versions are working.
Hello
The API will be updated to V1, so it will undergo some changes, will the package be updated to V1 too?
This is the link to check the update
https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=pt-br
FCM updated their api. Do you plan to update your library for new api version? Now default sounds are not supported in iOS by FCM.Net.
https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
Fala ângelo, boa tarde,
Eu tenho uma lista de mensagens personalizadas uma para cada usuário.
E ao chamar o método de envio dentro de um foreach pra enviar uma a uma, só chega pro primeiro da lista.
Tem algum tipo de restrição quando a isso?
Eu até tentei chamar no intervalo de 15 segundos e mesmo assim só chega primeiro da lista.
Me refiro na verdade, se da pra chamar o método de envio seguidas vezes ou se tem um delay para fazer a próxima chamada.
Los mensajes no llegan a dispositivos ios cuando la aplicación está cerrada. Parece un problema con la prioridad: el json que se compone incluye la prioridad con valores 1 (normal) y 0 (high) en vez de las cadenas ("normal" o "high") correspondientes. Se propone como corrección incluir la línea:
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
entre las líneas 48 y 49 del archivo FCM.Net/Code/Message.cs
Gracias. ¡estupenda librería!
The type or namespace name 'Header' could not be found (are you missing a using directive or an assembly reference?) FCM.Net.Playground D:\CSharp\FCM.Net-master\FCM.Net.Shared.Playground\Program.cs 20 Active
The HttpClient instance should be held to as mush as possible. It should have been possible to pass a HttpClient to Sender, as to prevent Sender from going out of scope and "killing" its internal HttpClient instance. Microsoft own words:
HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.
(found here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client )
There are a few ways to implement this: allow Sender to be configured with an HttpClient instance created elsewhere, make HttpClient static, create a Settings class which holds the HttpClient instance and lives outside the scope of Sender, etc.
Maybe you've created Sender to live as long as the application (just like the HttpClient), but if so then the sample code is misleading since it surrounds the instantiation of the Sender class with a using clause, suggesting it should be disposed as soon as possible (and its own HttpClient together with it).
We are facing some issues due to Microsoft.Bcl.Build when we work with the same solution having two .NET Framework (4.5.1, and 4.6.2) in two different branches of Git repository.
Currently its only FCM.Net package in our project which is having dependency of Microsoft.Bcl.Build package. Is there a possibility of releasing FCM.NET package without dependency of Bcl library?
Is There any solution for this?
Hi
First: thanks for your library!
You write in your documentation:
var serverKey = "https://console.firebase.google.com/project/MY_PROJECT/settings/cloudmessaging";
new Sender(serverKey)
This gives an error. In the playground you pass there an key instead of a URL. So it seems we have to pass the ServerKey from the FCM Project.
Maybe it would make sense to update the documentation here :)
Hi,
it would be a great heal if you could add the firebase api dpcs link (https://firebase.google.com/docs/cloud-messaging/http-server-ref) in the README.
Thanks!
E possivel ao inves de enviar , recebe uma notificação direto na minha aplicação C#
System.Net.Http.HttpRequestException
HResult=0x80131500
Message=An error occurred while sending the request.
Source=mscorlib
StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at FCM.Net.Sender.d__8.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at FCM.Net.Sender.d__7.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Pwa8CRM.frmInfomation.<bntSentMessage_ClickAsync>d__10.MoveNext() in D:\SourceCodeTest\Pwa8CRM\Pwa8CRM\frmInfomation.cs:line 128
Inner Exception 1:
WebException: The remote server returned an error: (407) Proxy Authentication Required.
how pass proxy use ?
I am trying to locate where this error is coming from to be able to debug.
I get this error without no context on what might have failed, and all my records show success.
Call Stack Trace: ErrorHandler at offset 755 in file:line:column <filename unknown>:0:0
MoveNext at offset 2357 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 104 in file:line:column <filename unknown>:0:0
SetResult at offset 163 in file:line:column <filename unknown>:0:0
MoveNext at offset 335 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 104 in file:line:column <filename unknown>:0:0
SetResult at offset 163 in file:line:column <filename unknown>:0:0
MoveNext at offset 557 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 104 in file:line:column <filename unknown>:0:0
SetResult at offset 163 in file:line:column <filename unknown>:0:0
MoveNext at offset 945 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 101 in file:line:column <filename unknown>:0:0
SetResult at offset 164 in file:line:column <filename unknown>:0:0
SetResult at offset 36 in file:line:column <filename unknown>:0:0
MoveNext at offset 386 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 101 in file:line:column <filename unknown>:0:0
SetResult at offset 164 in file:line:column <filename unknown>:0:0
SetResult at offset 36 in file:line:column <filename unknown>:0:0
MoveNext at offset 877 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 93 in file:line:column <filename unknown>:0:0
SetResult at offset 155 in file:line:column <filename unknown>:0:0
MoveNext at offset 367 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 111 in file:line:column <filename unknown>:0:0
RunOrScheduleAction at offset 99 in file:line:column <filename unknown>:0:0
FinishContinuations at offset 1024 in file:line:column <filename unknown>:0:0
TrySetResult at offset 93 in file:line:column <filename unknown>:0:0
Complete at offset 53 in file:line:column <filename unknown>:0:0
CompleteFromAsyncResult at offset 147 in file:line:column <filename unknown>:0:0
Complete at offset 86 in file:line:column <filename unknown>:0:0
ProtectedInvokeCallback at offset 202 in file:line:column <filename unknown>:0:0
CompleteUserRead at offset 93 in file:line:column <filename unknown>:0:0
ParseTrailer at offset 226 in file:line:column <filename unknown>:0:0
ProcessResponse at offset 109 in file:line:column <filename unknown>:0:0
ReadCallback at offset 118 in file:line:column <filename unknown>:0:0
Complete at offset 86 in file:line:column <filename unknown>:0:0
ProtectedInvokeCallback at offset 202 in file:line:column <filename unknown>:0:0
ProcessFrameBody at offset 328 in file:line:column <filename unknown>:0:0
ReadFrameCallback at offset 172 in file:line:column <filename unknown>:0:0
CompleteRequest at offset 62 in file:line:column <filename unknown>:0:0
CheckCompletionBeforeNextRead at offset 40 in file:line:column <filename unknown>:0:0
ReadCallback at offset 127 in file:line:column <filename unknown>:0:0
Complete at offset 86 in file:line:column <filename unknown>:0:0
RunInternal at offset 370 in file:line:column <filename unknown>:0:0
Run at offset 21 in file:line:column <filename unknown>:0:0
Run at offset 85 in file:line:column <filename unknown>:0:0
Complete at offset 149 in file:line:column <filename unknown>:0:0
ProtectedInvokeCallback at offset 202 in file:line:column <filename unknown>:0:0
CompletionPortCallback at offset 293 in file:line:column <filename unknown>:0:0
PerformIOCompletionCallback at offset 132 in file:line:column <filename unknown>:0:0
Try
Dim serverkey As String = "XXX"
Dim senderid As String = "XXX"
Dim id As String = "/topics/allDevices"
Dim Sender As New Sender(serverkey, senderid)
Dim message As New FCM.Net.Message
message.RegistrationIds = New List(Of String) From {id}
message.Notification = New FCM.Net.Notification
message.Notification.Title = "TestvomProg"
message.Notification.Body = "Hello World@!{DateTime.Now.ToString()}"
Dim result = Await Sender.SendAsync(message)
Dim json = "{""notification"":{""title"":""json message"",""body"":""works like a charm!""},""to"":""" & id & """}"
result = Await Sender.SendAsync(json)
Catch ex As Exception
MsgBox(ex.ToString, vbCritical, "FEHLER")
End Try
Grande Ângelo, tenho acompanhado diversas aulas e curso que você tem postado por ai.
Agora tentando fazer o push funcionar usando FCM ja usei varias bibliotecas entre uma delas essa sua e não chega a notificação.
O que deve está errado eu meu código? o result é este:
Na instancia da minha classe Sender passo certinho os dados abaixo, ja tentei tb sem o ID:
As defined in a sample, you can use registered Id, but can I get registered Id using this library?
And shall I send notification in bulk?
If it's possible with this library, then please provide some sample code.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.