@manhng

Welcome to my blog!

FCM (C#)

April 21, 2019 17:07

Firebase Cloud Messaging (FCM) in .NET (C#) (edit)

Introduction To Firebase Cloud Messaging (FCM)

https://www.c-sharpcorner.com/article/introduction-to-firebase-cloud-messaging-fcm/

Snippet

Snippet
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
 
namespace Fago.FCM
{
 
    class Program
    {
        /// <summary>
        /// https://www.c-sharpcorner.com/article/introduction-to-firebase-cloud-messaging-fcm/
        /// </summary>
        /// <param name="args"></param>
 
        static void Main(string[] args)
        {
            Console.WriteLine("Started.");
 
            var result = (new FCMPushNotification()).SendNotification(
                 _title: "0982411958"
                , _message: "Anh Manh ban Notification. Neu nhan duoc thi alo cho anh nhe!"
                , _topic: "OK"
                , deviceId: MySecretKeys.DeviceToken
                );
 
            Console.WriteLine("Finished.");
 
            Console.ReadKey();
        }
    }
 
    public static class MySecretKeys
    {
        public static string ServerKey = "YourServerKey";
 
        public static string DeviceToken = "YourDeviceToken";
 
        public static string SenderId = "YourSenderId";
    }
    public class FCMPushNotification
    {
        public FCMPushNotification()
        {
            // TODO: Add constructor logic here  
        }
        public bool Successful
        {
            get;
            set;
        }
        public string Response
        {
            get;
            set;
        }
        public Exception Error
        {
            get;
            set;
        }
        public FCMPushNotification SendNotification(string _title, string _message, string _topic, string deviceId)
        {
            FCMPushNotification result = new FCMPushNotification();
            try
            {
                result.Successful = true;
                result.Error = null;
                // var value = message;  
                string serverKey = MySecretKeys.ServerKey; //"Your server key";
                string senderId = MySecretKeys.SenderId; //"your sender id";
                var requestUri = "https://fcm.googleapis.com/fcm/send";
                WebRequest webRequest = WebRequest.Create(requestUri);
                webRequest.Method = "POST";
                webRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                webRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                webRequest.ContentType = "application/json";
                var data = new
                {
                    to = deviceId, // this if you want to test for single device  
                    //                        to = "/topics/" + _topic, // this is for topic  
                    priority = "high",
                    notification = new
                    {
                        title = _title,
                        body = _message,
                        show_in_foreground = "True",
                        icon = "myicon"
                    }
                };
                var serializer = new JavaScriptSerializer();
                var json = serializer.Serialize(data);
                Byte[] byteArray = Encoding.UTF8.GetBytes(json);
                webRequest.ContentLength = byteArray.Length;
                using (Stream dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = webResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                                result.Response = sResponseFromServer;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Successful = false;
                result.Response = null;
                result.Error = ex;
            }
            return result;
        }
    }
}

Categories

Recent posts