Wednesday, July 8, 2020

Push Notifications functions

using Newtonsoft.Json.Linq;
using PushSharp;
using PushSharp.Apple;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NOBOLO.Library.Utilities;
using System.Web.Script.Serialization;

namespace NOBOLO.Library.PushNotfication
{
    public class PushNotifications
    {
        public const string Success = "Success";
        public const string success = "success";
        public const string Failure = "Failure";
        public const string NoAccountExists = "NoAccountExists";
        protected string SetStringValue(string str)
        {
            return str.ToLower() == "null" ? string.Empty : str;
        }


        public string SendNotification_IOS(
                                            Int64 NotificationTypeID, string DeviceToken, string _Message,
                                            Int64 UserID,
                                            Int64 MessageTypeID,
                                            int BatchCount = 0,
                                            string MessageType = "Message",
                                            Int64 GroupID = 0,
                                            string sound = "default"
                                            )
        {
            try
            {
                var push = new PushBroker();
                string p12File = ConfigurationManager.AppSettings["PushNotification"];
                var appleCert = File.ReadAllBytes(p12File);
                bool APNSProduction = Convert.ToBoolean(Convert.ToInt32(ConfigurationManager.AppSettings["APNSProduction"]));
                push.RegisterAppleService(new ApplePushChannelSettings(APNSProduction, appleCert, "", true));

                JObject _CustomOb = new JObject();
                _CustomOb.Add("MessageType", MessageType);
                _CustomOb.Add("Counter", BatchCount);
                _CustomOb.Add("Message", _Message);
                _CustomOb.Add("UserID", UserID);
                _CustomOb.Add("MessageTypeID", MessageTypeID);
                _CustomOb.Add("GroupID", GroupID);
                _CustomOb.Add("NotificationTypeID", NotificationTypeID);


                push.QueueNotification(new AppleNotification()
                                        .ForDeviceToken(DeviceToken)
                                        .WithAlert(_Message)
                                        .WithBadge(BatchCount)
                                        .WithCustomItem("Message", _CustomOb)
                                        .WithSound(sound));

                push.OnChannelCreated += push_OnChannelCreated;
                push.OnChannelDestroyed += push_OnChannelDestroyed;
                push.OnChannelException += push_OnChannelException;
                push.OnDeviceSubscriptionChanged += push_OnDeviceSubscriptionChanged;
                push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
                push.OnNotificationFailed += push_OnNotificationFailed;
                //push.OnNotificationRequeue += push_OnNotificationRequeue;
                push.OnNotificationSent += push_OnNotificationSent;
                push.OnServiceException += push_OnServiceException;


                return "success";

            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return ex.ToString();
            }
        }

        public  String SendNotificationFromFirebaseCloud(string DeviceToken, string DeviceMessage,
                                                  Int64 UserID, Int64 MessageTypeID,
                                                  int BatchCount = 0,
                                                  string MessageType = "Message", string sound = "default")
        {


            try
            {
                string GoogleAppID = ConfigurationManager.AppSettings["GoogleAppID"];
                string SENDER_ID = ConfigurationManager.AppSettings["SENDER_ID"];


                var value = DeviceMessage;
                WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                tRequest.Method = "post";
                tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
                tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

                string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + DeviceToken + "";

                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                using (Stream dataStream = tRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);

                    using (WebResponse tResponse = tRequest.GetResponse())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())
                        {
                            using (StreamReader tReader = new StreamReader(dataStreamResponse))
                            {
                                String sResponseFromServer = tReader.ReadToEnd();
                               string _response = sResponseFromServer;
                            }
                        }
                    }
                }


                return "success";
            }
            catch (Exception ex)
            {
                LogHelper.CreateLog(ex);
                return ex.ToString();
            }
        }


        public string SendNotification_Android(Int64 NotificationTypeID, string DeviceToken, string DeviceMessage,
                                                 Int64 UserID, Int64 MessageTypeID,
                                                 int BatchCount = 0,
                                                 string MessageType = "Message",
                                                 Int64 GroupID = 0,
                                                 string sound = "default")
        {
            try
            {
                string GoogleAppID = ConfigurationManager.AppSettings["GoogleAppID"];
                string SENDER_ID = ConfigurationManager.AppSettings["SENDER_ID"];

                WebRequest tRequest;
                //tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");//GCM
                tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");//FCM

                tRequest.Method = "post";
                tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
                tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

                JObject _CustomOb = new JObject();
                _CustomOb.Add("MessageType", MessageType);
                _CustomOb.Add("Counter", BatchCount);
                _CustomOb.Add("Sound", sound);
                _CustomOb.Add("UserID", UserID);
                _CustomOb.Add("RequestID", MessageTypeID);
                _CustomOb.Add("GroupID", GroupID);
                _CustomOb.Add("NotificationTypeID", NotificationTypeID);
                //_CustomOb.Add("Message", DeviceMessage);
                //Sample Response
                //{
                //    "Data":{
                //        "MessageType": "NewGroup",
                //          "Counter": 24,
                //          "Sound": "default",
                //          "UserID": 16,
                //          "MessageTypeID": 0
                //           },
                //    "Message":"estwdwdwd by User: Salman Azhar"}

                //Sample Response
                //                {
                //                    "MessageType": "Message",
                //"Counter": 1,
                //"Sound": "default",
                //"UserID": 2311,
                //"RequestID": 1,
                //"GroupID": 0,
                //"NotificationTypeID": 1,
                //"Message": "My Message"
                //}


                string postedJson = "{\"Data\":" + _CustomOb + ",\"Message\":\"" + DeviceMessage + "\"}";
                //string postedJson = "{\"Data\":" + _CustomOb + ",\"Message\":\"" + DeviceMessage + "\"}";
                //string postedJson = _CustomOb.ToString();//.Replace(@"{{",@"{").Replace(@"}}", @"}").Replace(@"\r\n","");
                string postData = "time_to_live=108&delay_while_idle=1&data.message=" + postedJson + "&registration_id=" + DeviceToken;

                Console.WriteLine(postData);
                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                Stream dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse tResponse = tRequest.GetResponse();
                dataStream = tResponse.GetResponseStream();
                StreamReader tReader = new StreamReader(dataStream);
                String sResponseFromServer = tReader.ReadToEnd();

                tReader.Close();
                dataStream.Close();
                tResponse.Close();


                return "success";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        void push_OnDeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, PushSharp.Core.INotification notification)
        {
            //throw new NotImplementedException();
        }

        void push_OnDeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, PushSharp.Core.INotification notification)
        {
            //throw new NotImplementedException();
        }

        void push_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
        {
            //throw new NotImplementedException();
        }

        void push_OnChannelDestroyed(object sender)
        {
            //throw new NotImplementedException();
        }

        void push_OnChannelCreated(object sender, PushSharp.Core.IPushChannel pushChannel)
        {
            //throw new NotImplementedException();
        }

        void push_OnServiceException(object sender, Exception error)
        {
            //throw new NotImplementedException();
        }

        void push_OnNotificationSent(object sender, PushSharp.Core.INotification notification)
        {
            //throw new NotImplementedException();
        }

        void push_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
        {
            //throw new NotImplementedException();
        }
    }
}

No comments:

Post a Comment

Two Factor Authentication using .Net Core

Install Package dotnet add package GoogleAuthenticator --version 3.1.1 Model Changes public bool IsAuthenticatorReset { get; set; } public s...