Git Product home page Git Product logo

firebasenet's Introduction

NuGet version

firebaseNet

Client library for Firebase Cloud Messaging (FCM) written in C# / .NET.

This library provides a simple way in pure C# to send messages using the FCM HTTP connection servers. All JSON serialization/deserialization and HTTP related stuff is done automatically for you =).

Sending your first message

To send a message using the FCM C# client, first you'll need to get your project Server Key. The server key authorizes your app server for access to Google services, including sending messages via Firebase Cloud Messaging. You obtain the server key when you create your Firebase project. You can view it in the Cloud Messaging tab of the Firebase console Settings pane.

Once you have your server key, use it to initialize the FCMClient:

FCMClient client = new FCMClient("your-server-key");

Now it's time to send the message:

var message = new Message()
{
    To = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
};
var result = await client.SendMessageAsync(message);

This is the smallest possible request (a message without any parameters and just one recipient).

Tip: If you provide an invalid Server Key, the SendMessageAsync method will throw a FCMUnauthorizedException.

Message Types

With FCM, you can send two types of messages to clients:

  • Notification messages, sometimes thought of as "display messages."
  • Data messages, which are handled by the client app.

A notification message is the more lightweight option, with a 2KB limit and a predefined set of user-visible keys. Data messages let developers send up to 4KB of custom key-value pairs. Notification messages can contain an optional data payload, which is delivered when users tap on the notification.

Notification Messages

To send notification messages, set the Notification property with the necessary predefined set of key options for the user-visible part of the notification message. For example, here is a notification message in an IM app. The user can expect to see a message with the title "Portugal vs. Denmark" and text "great match!" on the device:

FCMClient client = new FCMClient(ServerApiKey);

var message = new Message()
{
    To = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    Notification = new AndroidNotification()
    {
        Body = "great match!",
        Title = "Portugal vs. Denmark",
        Icon = "myIcon"
    }
};

var result = await client.SendMessageAsync(message);

Data Messages

Set the Data property with your custom key-value pairs to send a data payload to the client app. Data messages can have a 4KB maximum payload.

For example, here is a in the same IM app as above, where the information is encapsulated in the data key and the client app is expected to interpret the content:

FCMClient client = new FCMClient(ServerApiKey);

var message = new Message()
{
    To = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
	Data = new Dictionary<string, string>
    {
        { "Nick", "Mario" },
        { "body", "great match!" },
		{ "Room", "PortugalVSDenmark" }
    }
};

var result = await client.SendMessageAsync(message);

Messages with both notification and data payloads

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.

  • When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
  • When in the foreground, your app receives a message object with both payloads available.

Here is a message containing both the Notification property Data property:

FCMClient client = new FCMClient(ServerApiKey);

var message = new Message()
{
    To = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    Notification = new AndroidNotification()
    {
        Body = "great match!",
        Title = "Portugal vss Denmark",
        Icon = "myIcon"
    },
    Data = new Dictionary<string, string>
    {
        { "score", "5x1" },
        { "time", "15:10" }
    }
};

var result = await client.SendMessageAsync(message);

More details about FCM messages can be found in the product documentation at:

More samples

You can find more samples within the project integration tests. Take a look at the test/FirebaseNet.Tests/Interation folder.

Contributing

You know how to do it! Fork it, branch it, change it, commit it, and pull-request it. We are passionate about improving this project, and glad to accept help to make it better.

firebasenet's People

Contributors

cduhn-mueller avatar tiagomtotti avatar witoong623 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebasenet's Issues

Receive

Hello, how can I receive messages over firebaseNet?

Thank you

InvalidRegistration error

Hello,

I get this error. InvalidRegistration.

Here is the response.

{"multicast_id":7134642900023070392,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

Do you have any suggestions?

Thank you,

Will this work for notifying ios too?

The library seem very concise and straight forward. Thanks
I saw this code

 Notification notification = new AndroidNotification();

So, will it work for ios? I did not see an implementation difference in both.
That's why the query.

FirebaseNet.Serialization.JsonNetSerializer threw an exception

I use C# web api target .net 4.5
FirebaseNet 1.0.1
NewtonSoft.json 10.0.2

When I call a new FCM client then "The type initializer for 'FirebaseNet.Serialization.JsonNetSerializer' threw an exception."
Error:
{"Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed"}

Push Notification not received when using in Load Balanced Servers

I am not sure if I should be writing it here or not but maybe fellow developers faced it before.

I have created a DLL file of my own that wraps the firebaseNet nuget package. For simplifying I have made a Method to accept few arguments and send notification to all users [Fetched from database] in an ASP.NET application. This method works absolutely fine for me when I am using it in a single server. But if I do the same in a Load Balanced Servers [Application Request Routing (ARR)] the notification simply never reaches the client. Even though there are no errors or exceptions.

How to use BodyLocArgs with multiple arguments?

Is the correct format for BodyLocArgs to encode the json array of values?

e.g.,

BodyLocKey = "my_localized_str" // %1$s, %2$s, and %3$s
BodyLocArgs = "[\"First\", \"Second\", \"Third\"]"

Can this send messages to iPhone

There is a Notification parameter in the Message class. How could i target this to send a message to both IoS and Android phone?

Suggestion: combine AndroidNotification and IosNotification

I think this might ideal for a lot of people. The nice thing about firebase cloud messaging is that I don't have to necessarily know if the device(s) that I'm pushing a notification to are Android or iOS.

It would be nice to have a single Notification class that has fields from both Android and iOS notification classes. That's just my opinion anyhow, it's what's keeping me from using the NuGet package in my application.

The execution stops on 'client.SendMessageAsync(message)'

Hi! I am trying to use this package on a Web Api project and the message is never sent.

In fact, when forcing the method to run synchronously, the .Result never gets a reference and the execution stops.

The referred block of code below:

                        var client = new FCMClient(AppConfig.GoogleFirebaseApiKey);
                        var message = new Message()
                        {
                            To = destination_user.FirebaseToken,
                            Notification = new AndroidNotification()
                            {
                                Body = mensagem,
                                Title = fromUser.Email,
                                Icon = "MyAppIcon"
                            }
                        };

                        var r = await client.SendMessageAsync(message);

Thanks in advance for any help.

Data values is not present in the Dictionary

I try to send push with data:
Data = new Dictionary<string, string>
{
{ "key1", "Test" },
{ "key2", "Hello" }
}
But this data is not present in the received push in the app. Only message id and alert I can see

Sending an iOS message chrashes

For some reason this line just exits and quits.
No error, no response.

Android works just fine with the same message

        FCMClient client = new FCMClient("TOKENKEY");

        var firebaseMessage = new Message()
        {
            To = recipient,
            Notification = iosNotification,
            Data = message.Data
        };
        try
        {
           var result = await client.SendMessageAsync(firebaseMessage);
        }catch(Exception e)
        {

        }

Push notification without tag?

I maybe missing something but how do I push a notification without a tag? As my app does not require a tag and everyone should receive the notification.

I have left it empty but that does not seem work.

Sending notifications to a device group

From what I have seen there isn't a way to creating a device group as explained here. I believe it would be useful since you might use the result in the to when creating the message.

Or is there a way and I'm not seeing it?

NetStandard target support

I'm trying to use FirebaseNet from a .Net Core Class Library I'm planing to use in various projects inside my solution, however, FirebaseNet only supports netcoreapp1.0, net 4.5 and .net 4.6. If it instead targeted netstardard 1.1 for example, it could be used in other contexts, such as the one I'm mentioning. The issue is already fixed in #6, so it could be good to have that merged

Can't add this package to Andorid project

Hi.
When I want to add this package to my android project , I got :
can't add this package ,because its mono 7.1.
What is the problem ?
It add to Xamarin.Forms PCL , but for android , I cant add it !

my Xamarin PCL is targeted .netstandard 2.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.