/// <summary>
 ///
 /// </summary>
 public NotificationManager()
 {
     if (_push == null)
     {
         Console.WriteLine("Constructor fired.");
         LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Notification constructor is running.");
         try
         {
             _push = new PushBroker();
             //Registring events.
             _notificationMsgLength             = 0;
             _push.OnNotificationSent          += NotificationSent;
             _push.OnChannelException          += ChannelException;
             _push.OnServiceException          += ServiceException;
             _push.OnNotificationFailed        += NotificationFailed;
             _push.OnNotificationRequeue       += NotificationRequeue;
             _push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
             _push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
             _push.OnChannelCreated            += ChannelCreated;
             _push.OnChannelDestroyed          += ChannelDestroyed;
             var appleCertificate =
                 File.ReadAllBytes(ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePath]);
             var channelSettings = new ApplePushChannelSettings(true, appleCertificate,
                                                                ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePwd]);
             channelSettings.ConnectionTimeout = 36000;
             _push.RegisterAppleService(channelSettings);
             _push.RegisterGcmService(
                 new GcmPushChannelSettings(ConfigurationManager.AppSettings[NeeoConstants.GoogleApiKey]));
         }
         catch (Exception exception)
         {
             Console.WriteLine(exception);
         }
     }
 }
Пример #2
0
 private void EnsureiOS()
 {
     if (!m_started_ios)
     {
         ApplePushChannelSettings setting = new ApplePushChannelSettings(!m_config.iOSuseSandboxServer, m_config.iOScertificate, m_config.iOScertificatePassword);
         Service.StartApplePushService(setting, serviceSettings);
         m_started_ios = true;
     }
 }
Пример #3
0
        private static void ReceiveFeedback()
        {
            FeedbackService fs = new FeedbackService();

            fs.OnFeedbackReceived += Fs_OnFeedbackReceived;

            //			var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Resources/PushSharp.Apns.Sandbox.p12"));
            //			ApplePushChannelSettings appleSettings = new ApplePushChannelSettings (false, appleCert, "Lize4Rune");

            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Resources/OLBPhoneSandboxCertificate.p12"));
            ApplePushChannelSettings appleSettings = new ApplePushChannelSettings(false, appleCert, "0lbSandb0x");

            fs.Run(appleSettings);
        }
Пример #4
0
        public void Start()
        {
            // Register IPhone Service
#if DEBUG
            bool isProduction      = false;
            var  iPhoneCertificate = Resources.Shared.Dev_Certificates;
#else
            bool isProduction      = true;
            var  iPhoneCertificate = Resources.Shared.Etejah_Pro_Certificates;
#endif
            this._iphoneChannelSettings = new ApplePushChannelSettings(isProduction, iPhoneCertificate,
                                                                       Resources.Shared.Apple_Certification_Password);
            this._pushBroker.RegisterAppleService(this._iphoneChannelSettings, IPhoneAppName); //Extension method
        }
Пример #5
0
        void ConfigureIos(NotiConfig config, string basePath)
        {
            this.HasIos = config.HasIos;
            if (this.HasIos)
            {
                try
                {
                    var path    = Path.Combine(basePath, config.ApnCertFile);
                    var bytes   = File.ReadAllBytes(path);
                    var setting = new ApplePushChannelSettings(config.ApnProduction, bytes, config.ApnCertPassword);
                    pushBroker.RegisterAppleService(setting);
                }
                catch (Exception ex)
                {
                    logger.Error("Error when adding iOS", ex);

                    this.HasIos = false;
                }
            }
        }
Пример #6
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "<specify your .p12 file here>"));

            string iphoneToken = "<PUT YOUR DEVICE TOKEN HERE>";

            var settings = new ApplePushChannelSettings(cert, "pushdemo");

            push.RegisterAppleService(settings);

            var Notification = new AppleNotification()
                               .ForDeviceToken(iphoneToken)
                               .WithAlert("欢迎来到中国移动者开发大会!")
                               .WithSound("sound.caf")
                               .WithBadge(4);

            push.QueueNotification(Notification);
            Console.WriteLine("Waiting for Queue to Finish...");



            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();

            //GCM



            var RegID_emulator = "<PUT YUOR REGISTER ID HERE>";

            push.RegisterGcmService(new GcmPushChannelSettings("<PUT YOUR GOOGLE API SERVER KEY HERE>"));

            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID_emulator)
                                   .WithJson("{\"alert\":\"欢迎来到中国移动者开发大会!\",\"badge\":7,\"sound\":\"sound.caf\"}"));


            push.StopAllServices();
        }
Пример #7
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "PushDemo.p12"));
            string ipadtoken   = "6f22cc6eaff02281125092987dd6b9dc1242722bb455253ff308f71dab296169";
            string iphoneToken = "5477ac3de431bcf89982c569cb33846285565b7f62b235ad10d8737754b8b81a";

            var settings = new ApplePushChannelSettings(cert, "pushdemo");

            push.RegisterAppleService(settings);

            var Notification = new AppleNotification()
                               .ForDeviceToken(iphoneToken)
                               .WithAlert("欢迎来到Visual Studio 2013新功能会议!")
                               .WithSound("sound.caf")
                               .WithBadge(4);

            push.QueueNotification(Notification);
            Console.WriteLine("Waiting for Queue to Finish...");



            Console.WriteLine("Queue Finished.....");

            //GCM


            var RegID_phone    = "APA91bEHi1O4JzS3tmtAY5zycJCTcUZyxvDgwKRjHdvvp02DfEGsC433d5xN0Naf8BF1-l1Q9kQra_GpslhXuB-D_lyiJdLWlCKehwgAsNdVhUcLIeHp7-aElC_kol62yBZ1ZJtInwq7";
            var RegID_emulator = "APA91bFj1aE5r6TjypnfvAKzTBK19eYGLfuBpKldIhMCwn5YiubfmUFLJg54Pw2tFvvZnC0w4QIR35Wlrf6phzuKS1L8r0YfVHbYfo8tNlQNmQ9WjMHUgam5rC2HrApQDQrLJyhXAcwj";

            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyARS7ie-GIeCSGAx_bxq9yQk6l9xgl_2IM"));

            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID_emulator)
                                   .WithJson("{\"alert\":\"欢迎来到Visual Studio 2013新功能会议!\",\"badge\":7,\"sound\":\"sound.caf\"}"));


            push.StopAllServices();
        }
Пример #8
0
        public static void Main(string[] args)
        {
            var pushBroker = new PushBroker();


            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.
                                                      BaseDirectory, "idbCert.p12"));



            var appleSettings = new ApplePushChannelSettings(cert, "idbmobile");



            var n = new AppleNotification().ForDeviceToken("7ced312b754878f6971c1169f02fcec3e33bc6b92ccade4921b54961fa03f93b")
                    .WithAlert("IDB Push Test").WithBadge(3);

            pushBroker.RegisterAppleService(appleSettings);


            pushBroker.QueueNotification(n);

            pushBroker.StopAllServices();
        }
Пример #9
0
        public void TestNotifications(int toQueue, int expectSuccessful, int expectFailed, int[] idsToFail = null, bool waitForScaling = false, bool autoScale = false)
        {
            var testServer = new ApnsNodeTestServer("http://localhost:8888/");

            testServer.Reset();
            testServer.Setup(idsToFail ?? new int[] {});

            var started = DateTime.UtcNow;

            int pushFailCount    = 0;
            int pushSuccessCount = 0;

            AppleNotification.ResetIdentifier();

            var settings = new ApplePushChannelSettings(false, appleCert, "pushsharp", true);

            settings.OverrideServer("localhost", 2195);
            settings.SkipSsl = true;
            settings.MillisecondsToWaitBeforeMessageDeclaredSuccess = 5000;

            var serviceSettings = new PushServiceSettings();

            if (!autoScale)
            {
                serviceSettings.AutoScaleChannels = false;
                serviceSettings.Channels          = 1;
            }

            var push = new ApplePushService(settings, serviceSettings);

            push.OnNotificationFailed += (sender, notification1, error) => {
                Console.WriteLine("NOTIFICATION FAILED: " + ((AppleNotification)notification1).Identifier);
                pushFailCount++;
            };
            push.OnNotificationSent += (sender, notification1) => {
                pushSuccessCount++;
            };
            push.OnNotificationRequeue += (sender, e) => {
                Console.WriteLine("REQUEUE: " + ((AppleNotification)e.Notification).Identifier);
            };

            for (int i = 0; i < toQueue; i++)
            {
                var n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test");

                push.QueueNotification(n);
            }

            if (waitForScaling)
            {
                while (push.QueueLength > 0)
                {
                    Thread.Sleep(500);
                }

                Console.WriteLine("Sleeping 3 minutes for autoscaling...");
                Thread.Sleep(TimeSpan.FromMinutes(3));

                Console.WriteLine("Channel Count: " + push.ChannelCount);
                Assert.IsTrue(push.ChannelCount <= 1);
            }

            push.Stop();
            push.Dispose();

            Console.WriteLine("Avg Queue Wait Time: " + push.AverageQueueWaitTime + " ms");
            Console.WriteLine("Avg Send Time: " + push.AverageSendTime + " ms");

            var span = DateTime.UtcNow - started;

            var info = testServer.GetInfo();

            Console.WriteLine("Test Time: " + span.TotalMilliseconds + " ms");
            Console.WriteLine("Client Failed: {0} Succeeded: {1} Sent: {2}", pushFailCount, pushSuccessCount, toQueue);
            Console.WriteLine("Server Failed: {0} Succeeded: {1} Received: {2} Discarded: {3}", info.FailedIds.Length, info.SuccessIds.Length, info.Received, info.Discarded);

            //Assert.AreEqual(toQueue, info.Received, "Server - Received Count");
            Assert.AreEqual(expectFailed, info.FailedIds.Length, "Server - Failed Count");
            Assert.AreEqual(expectSuccessful, info.SuccessIds.Length, "Server - Success Count");

            Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count");
            Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count");
        }
Пример #10
0
 public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, string applicationId, IPushServiceSettings serviceSettings = null)
 {
     broker.RegisterService <AppleNotification>(new ApplePushService(channelSettings, serviceSettings), applicationId);
 }
Пример #11
0
 public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings = null)
 {
     RegisterAppleService(broker, channelSettings, null, serviceSettings);
 }
Пример #12
0
        private static void SendNotification(string deviceToken, string title, string body, int badgeCount, string sound)
        {
            //Create our push services broker
            var push = new PushBroker();

            //Wire up the events for all the services that the broker registers
            push.OnNotificationSent          += NotificationSent;
            push.OnChannelException          += ChannelException;
            push.OnServiceException          += ServiceException;
            push.OnNotificationFailed        += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated            += ChannelCreated;
            push.OnChannelDestroyed          += ChannelDestroyed;


            //------------------------------------------------
            //IMPORTANT NOTE about Push Service Registrations
            //------------------------------------------------
            //Some of the methods in this sample such as 'RegisterAppleServices' depend on you referencing the correct
            //assemblies, and having the correct 'using PushSharp;' in your file since they are extension methods!!!

            // If you don't want to use the extension method helpers you can register a service like this:
            //push.RegisterService<WindowsPhoneToastNotification>(new WindowsPhonePushService());

            //If you register your services like this, you must register the service for each type of notification
            //you want it to handle.  In the case of WindowsPhone, there are several notification types!

            //-------------------------
            // APPLE NOTIFICATIONS
            //-------------------------
            //Configure and start Apple APNS
            // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to generate one for connecting to Sandbox,
            //   and one for connecting to Production.  You must use the right one, to match the provisioning profile you build your
            //   app with!
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/OLBPhoneSandboxCertificate.p12"));
            //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server
            //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
            //  If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
            //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')

            ApplePushChannelSettings appleSettings = new ApplePushChannelSettings(false, appleCert, "0lbSandb0x");

            push.RegisterAppleService(appleSettings); //Extension method

            AppleNotification notification = new AppleNotification();

            notification.ForDeviceToken(deviceToken);

            AppleNotificationAlert alert = new AppleNotificationAlert();

            if (!string.IsNullOrWhiteSpace(title))
            {
                alert.Title = title;
            }

            if (!string.IsNullOrWhiteSpace(body))
            {
                alert.Body = body;
            }

            notification.WithAlert(alert);

            if (badgeCount >= 0)
            {
                notification.WithBadge(badgeCount);
            }

            if (!string.IsNullOrWhiteSpace(sound))
            {
                notification.WithSound(sound);
            }

            push.QueueNotification(notification);

            //---------------------------
            // ANDROID GCM NOTIFICATIONS
            //---------------------------
            //Configure and start Android GCM
            //IMPORTANT: The API KEY comes from your Google APIs Console App, under the API Access section,
            //  by choosing 'Create new Server key...'
            //  You must ensure the 'Google Cloud Messaging for Android' service is enabled in your APIs Console

            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAQTRCFjVX5LQ0dOd4Gue4_mUuv3jlPMrg"));

            //Fluent construction of an Android GCM Notification
            //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
            push.QueueNotification(
                new GcmNotification().ForDeviceRegistrationId("APA91bHr5W1cNl5mcZ_iWqGKVnvcXeZwYdVGCCFjt0M8egamRAIq5lCASbUQe-3E9M74CiD8Moildh4SC8Qj6qUUpCnNOQ5v17A9go1enqDipOGSaeiDU_I3fGroneA7tL3FAMlN60nW")
                .WithJson("{\"alert\":\"Hello Leslie!\",\"badge\":7,\"sound\":\"sound.caf\"}"))
            ;


            //-----------------------------
            //			// WINDOWS PHONE NOTIFICATIONS
            //			//-----------------------------
            //			//Configure and start Windows Phone Notifications
            //			push.RegisterWindowsPhoneService();
            //			//Fluent construction of a Windows Phone Toast notification
            //			//IMPORTANT: For Windows Phone you MUST use your own Endpoint Uri here that gets generated within your Windows Phone app itself!
            //			push.QueueNotification(new WindowsPhoneToastNotification()
            //				.ForEndpointUri(new Uri("DEVICE REGISTRATION CHANNEL URI HERE"))
            //				.ForOSVersion(WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
            //				.WithBatchingInterval(BatchingInterval.Immediate)
            //				.WithNavigatePath("/MainPage.xaml")
            //				.WithText1("PushSharp")
            //				.WithText2("This is a Toast"));
            //
            //
            //			//-------------------------
            //			// WINDOWS NOTIFICATIONS
            //			//-------------------------
            //			//Configure and start Windows Notifications
            //			push.RegisterWindowsService(new WindowsPushChannelSettings("WINDOWS APP PACKAGE NAME HERE",
            //				"WINDOWS APP PACKAGE SECURITY IDENTIFIER HERE", "CLIENT SECRET HERE"));
            //			//Fluent construction of a Windows Toast Notification
            //			push.QueueNotification(new WindowsToastNotification()
            //				.AsToastText01("This is a test")
            //				.ForChannelUri("DEVICE CHANNEL URI HERE"));

            Console.WriteLine("Waiting for Queue to Finish...");

            //Stop and wait for the queues to drains
            push.StopAllServices();

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
Пример #13
0
        public static String SendAPNSBroadCast(String message, int baget, bool mute, List <String> devices)
        {
            ApplePushChannelSettings setting = new ApplePushChannelSettings(true, KEYPATH, PASS, true);
            ApplePushService         service = new ApplePushService(setting);
            AppleNotificationPayload payload = new AppleNotificationPayload();

            List <String> valids   = new List <string>();
            List <String> invalids = new List <string>();

            if (mute)
            {
                payload.Sound = "";
                payload.Alert = new AppleNotificationAlert()
                {
                    Body = ""
                };
            }
            else
            {
                payload.Sound = "default";
                payload.Alert = new AppleNotificationAlert()
                {
                    Body = message
                };
            }
            payload.Badge = baget;


            object obj   = new object();
            int    total = 0;

            service.OnNotificationFailed += (object sender, INotification notification, Exception error) =>
            {
                lock (obj)
                {
                    total++;
                    invalids.Add((String)notification.Tag);
                }
                Console.WriteLine("Fail / " + notification.Tag + "/ " + total);
            };

            service.OnNotificationSent += (object sender, INotification notification) =>
            {
                lock (obj)
                {
                    total++;
                    valids.Add((String)notification.Tag);
                }
                Console.WriteLine("Ok / " + total);
            };


            foreach (var item in devices)
            {
                AppleNotification sendNotify = new AppleNotification(item, payload);
                sendNotify.Tag = item;
                service.QueueNotification(sendNotify);
            }

            while (total != devices.Count)
            {
                ;
            }

            System.Threading.Thread.Sleep(3000);

            service.Stop();

            PushCallBack pushcallback = new APNSCallBack("iOS")
            {
                valids   = valids,
                invalids = invalids,
                success  = valids.Count,
                failure  = invalids.Count,
                Devices  = devices
            };

            return(JsonConvert.SerializeObject(pushcallback));
        }
Пример #14
0
        public void TestNotifications(int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null)
        {
            testPort++;

            int pushFailCount    = 0;
            int pushSuccessCount = 0;

            int serverReceivedCount        = 0;
            int serverReceivedFailCount    = 0;
            int serverReceivedSuccessCount = 0;

            var notification = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test");

            var len = notification.ToBytes().Length;

            var server = new TestServers.ApnsTestServer();

            server.ResponseFilters.Add(new ApnsResponseFilter()
            {
                IsMatch = (identifier, token, payload) =>
                {
                    var id = identifier;

                    Console.WriteLine("Server Received: id=" + id + ", payload= " + payload + ", token=" + token);

                    if (token.StartsWith("b", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }

                    return(false);
                },
                Status = ApnsResponseStatus.InvalidToken
            });

            var waitServerFinished = new ManualResetEvent(false);


            Task.Factory.StartNew(() =>
            {
                try
                {
                    server.Start(testPort, len, (success, identifier, token, payload) =>
                    {
                        serverReceivedCount++;

                        if (success)
                        {
                            serverReceivedSuccessCount++;
                        }
                        else
                        {
                            serverReceivedFailCount++;
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

                waitServerFinished.Set();
            }).ContinueWith(t =>
            {
                var ex = t.Exception;
                Console.WriteLine(ex);
            }, TaskContinuationOptions.OnlyOnFaulted);

            var settings = new ApplePushChannelSettings(false, appleCert, "pushsharp", true);

            settings.OverrideServer("localhost", testPort);
            settings.SkipSsl = true;


            var push = new ApplePushService(settings, new PushServiceSettings()
            {
                AutoScaleChannels = false, Channels = 1
            });

            push.OnNotificationFailed += (sender, notification1, error) => pushFailCount++;
            push.OnNotificationSent   += (sender, notification1) => pushSuccessCount++;

            for (int i = 0; i < toQueue; i++)
            {
                INotification n;

                if (indexesToFail != null && indexesToFail.Contains(i))
                {
                    n = new AppleNotification("bff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test");
                }
                else
                {
                    n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test");
                }

                push.QueueNotification(n);
            }

            push.Stop();
            push.Dispose();

            server.Dispose();
            waitServerFinished.WaitOne();

            Console.WriteLine("TEST-> DISPOSE.");

            Assert.AreEqual(toQueue, serverReceivedCount, "Server - Received Count");
            Assert.AreEqual(expectFailed, serverReceivedFailCount, "Server - Failed Count");
            Assert.AreEqual(expectSuccessful, serverReceivedSuccessCount, "Server - Success Count");

            Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count");
            Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count");
        }