I am trying to get FirebaseAdmin going in my .Net Web.Forms C# project, and I keep getting NullReferenceExceptions. I have used this link (FCM (Firebase Cloud Messaging) Push Notification with Asp.Net) for reference (the 2019 EDIT), and that didn't work. I then move the SDK initialisation to Global.asax in the Application_Start method, and tried using the DefaultInstance to send my push (I have seen that method used as well).
My code:
Global.asax
protected void Application_Start(object sender, EventArgs e)
{
// Enable firebase
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(HostingEnvironment.MapPath(@"~/App_Data/xxxx-11788e8acbe2.json"))
});
}
My class that send the push:
namespace MyApp.classes
{
public class FCM
{
public FCM() { }
private FirebaseAdmin.Messaging.Message CreateNotificationForTopic(string title, string notificationBody, string topic)
{
return new FirebaseAdmin.Messaging.Message()
{
Topic = topic,
Notification = new Notification()
{
Body = notificationBody,
Title = title
}
};
}
public async Task SendNotificationToTopic(string topic, string title, string body)
{
try
{
var result = await FirebaseMessaging.DefaultInstance.SendAsync(CreateNotificationForTopic(title, body, topic));
}
catch (Exception x)
{
string xxx = x.Message;
}
}
}
}
It's very hard to fix as I am just getting a NullReferenceException without any other information when I run SendNotificationToTopic. Anyone have any ideas at all? Would greatly appreciate it.
PS: FirebaseMessage is not null:
PS2: DefaultInstance has a value, but ProjectId is not set? Could this be it? But it exists in the Json file used when initialising the SDK?
ANSWER: Ok, so I figured it out. Many thanks to @mjwills for taking the time to help out. For some reason this thread was closed prematurely. The issue was that somehow two projects has been generated in the Service Account console, and of course, the SDK was being created facing the application that is not in use.
I created a new Service Account under the correct project, downloaded the credentials and viola, it works.