public APNSNotificationMessage(AppleNotification notification)
 {
     Token = notification.DeviceToken;
     CustomItems = notification.Payload.CustomItems.ToDictionary(x => x.Key, x => x.Value.Single().ToString());
     Sound = notification.Payload.Sound;
     Category = notification.Payload.Category;
     Body = notification.Payload.Alert.Body;
     if (notification.Payload.Badge.HasValue)
         Badge = notification.Payload.Badge.Value;
 }
        public Notification ToNotification()
        {
            var notification = new AppleNotification()
                .ForDeviceToken(Token)
                .WithContentAvailable(1)
                .WithAlert(Body)
                .WithSound(Sound)
                .WithBadge(Badge)
                .WithCategory(Category);

            foreach (var item in CustomItems)
            {
                notification.WithCustomItem(item.Key, item.Value);
            }

            return notification;
        }
示例#3
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();
        }
        public bool Send(AppleApiNotificationPayLoad payLoad)
        {
            HookEvents(PushBroker);

            try
            {
                PushBroker.RegisterService<AppleNotification>(new ApplePushService(new ApplePushChannelSettings(_Settings.CertificateContents, _Settings.CertificatePassword)));

                var notification = new AppleNotification()
                    .ForDeviceToken(payLoad.Token)
                    .WithAlert(payLoad.Message)
                    .WithSound(payLoad.SoundFile)
                    .WithBadge(payLoad.BadgeNo);
                
                PushBroker.QueueNotification(notification);
            }
            finally 
            {
                StopBroker(); 
            }

            return true;
        }
示例#5
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();
        }
示例#6
0
文件: Program.cs 项目: Terry-Lin/MDCC
        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 void TestNotifications(int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null, bool waitForScaling = false)
        {
            var started = DateTime.UtcNow;

            testPort++;

            int pushFailCount = 0;
            int pushSuccessCount = 0;

            int serverReceivedCount = 0;
            int serverReceivedFailCount = 0;
            int serverReceivedSuccessCount = 0;
            int lastIdentifier = -1;

            AppleNotification.ResetIdentifier ();

            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;

                    if (token.StartsWith("b", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine("Failing: " + identifier);
                        return true;
                    }

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

            var waitServerFinished = new ManualResetEvent(false);

            Task.Factory.StartNew(() =>
                {
                    try
                    {
                        server.Start(testPort, len, (success, identifier, token, payload) =>
                        {
                            //Console.WriteLine("Server Received: id=" + identifier + ", payload= " + payload + ", token=" + token + ", success=" + success);

                            if (identifier - lastIdentifier > 1)

                            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.OverrideServer("localhost", 2195);
            settings.SkipSsl = true;
            //settings.MillisecondsToWaitBeforeMessageDeclaredSuccess = 60000 * 5;

            var push = new ApplePushService(settings, new PushServiceSettings() { AutoScaleChannels = false, Channels = 1 });
            push.OnNotificationFailed += (sender, notification1, error) => {
                Console.WriteLine("APPLEPUSHSERVICE NOTIFICATION FAILED: " + ((AppleNotification)notification1).Identifier);
                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);
            }

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

            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();

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

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

            var span = DateTime.UtcNow - started;

            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}", serverReceivedFailCount, serverReceivedSuccessCount, serverReceivedCount);

            //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");
        }
示例#8
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();
        }
示例#9
0
        private void EnqueueApnsNotification(Device device, PushNotification notification)
        {
            var config = PushServiceConfiguration.GetSection();
            
            string message = notification.Message;

            if (message != null && message.Length > config.Apns.MaxMessageLength)
                message = notification.ShortMessage ?? notification.Message;

            if (message != null && message.Length > config.Apns.MaxMessageLength)
            {
                _log.WarnFormat("message is larger than maximum allowed length of {0}", config.Apns.MaxMessageLength);
                return;
            }

            var apnsNotification = new AppleNotification()
                .ForDeviceToken(device.Token)
                .WithAlert(message)
                .WithBadge(device.Badge)
                .WithCustomItem("regid", device.RegistrationID);

            if (notification.Module != PushModule.Unknown && notification.Item != null)
            {
                var itemType = notification.Item.Type;
                var itemId = notification.Item.ID;

                if (notification.Item.Type == PushItemType.Subtask && notification.ParentItem != null)
                {
                    itemType = notification.ParentItem.Type;
                    itemId = notification.ParentItem.ID;
                }

                apnsNotification.WithCustomItem("itemid", itemId);
                apnsNotification.WithCustomItem("itemtype", itemType.ToString().ToLower());
            }

            if (config.IsDebug || !config.Apns.ElementInformation.IsPresent)
            {
                _log.DebugFormat("notification ({0}) prevented from sending to device {1}", apnsNotification, device.ID);
                return;
            }

            PushBrokerProvider.Instance.QueueNotification(apnsNotification);
        }
示例#10
0
 public SentNotification(AppleNotification notification)
 {
     this.Notification = notification;
     this.SentAt = DateTime.UtcNow;
     this.Identifier = notification.Identifier;
 }
示例#11
0
 public SentNotification(AppleNotification notification)
 {
     this.Notification = notification;
     this.SentAt       = DateTime.UtcNow;
     this.Identifier   = notification.Identifier;
 }
示例#12
0
 public NotificationFailureException(int errorStatusCode, AppleNotification notification) : base()
 {
     this.ErrorStatusCode = errorStatusCode;
     this.Notification    = notification;
 }
示例#13
0
		private bool TryGetNotificationData(AppleNotification appleNotification, out byte[] notificationData, out Exception failure)
		{
			try
			{
				notificationData = appleNotification.ToBytes();
				failure = null;
				return true;
			}
			catch (NotificationFailureException exception)
			{
				notificationData = null;
				failure = exception;
				return false;
			}
		}
示例#14
0
        /// <summary>
        /// Apns the s_ is payload length valid.
        /// </summary>
	    public void APNS_IsPayloadLengthValid()
	    {
            var n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test");
	    }
 public static AppleNotification WithTag(this AppleNotification n, object tag)
 {
     n.Tag = tag;
     return(n);
 }
 public static AppleNotification WithPayload(this AppleNotification n, AppleNotificationPayload payload)
 {
     n.Payload = payload;
     return(n);
 }
        /// <summary>
        /// The main processor method used to process a single push notification, checks if the processing will be an immediate single push or regular thread looping model. 
        /// Looks up for a single (or more if you wish) entity in the databae which has not been processed. 
        /// Puts the fetched unprocessed push notification entity to processing over the Push Sharp API. 
        /// Finally saves the state of processing.
        /// </summary>
        /// <param name="databaseContext">The current database context to be used for processing to the database.</param>
        /// <param name="pushNotification">A single push notification entity to be processed and saved.</param>
        /// <param name="isDirectSinglePush">Decides wethere the processing will take place immediately for the sent notification or will the method lookup from the database for a first unprocessed push notification.</param>
        /// <returns>True if all OK, false if not.</returns>
        public bool ProcessNotification(PushSharpDatabaseContext dbContext, PushNotification pushNotification = null, bool isDirectSinglePush = false)
        {
            _databaseContext = dbContext;
            _isDirectSinglePush = isDirectSinglePush;

            if (_isDirectSinglePush)
                InitBroker();

            On(DisplayMessage, "Checking for unprocessed notifications...");
            PushNotification notificationEntity = pushNotification;

            try
            {
                if (notificationEntity != null)
                {
                    // save a new immediate unprocessed push notification
                    _databaseContext.PushNotification.Add(pushNotification);
                    _databaseContext.SaveChanges();

                    // reload the entity
                    notificationEntity = _databaseContext.PushNotification
                        .Where(x => x.ID == pushNotification.ID)
                        .Include(x => x.MobileDevice)
                        .Include(x => x.MobileDevice.Client)
                        .FirstOrDefault();
                }
                else // take one latest unprocessed notification, this can be changed to take any set size instead of one
                    notificationEntity = _databaseContext.PushNotification.FirstOrDefault(s =>
                        s.Status == (int)PushNotificationStatus.Unprocessed &&
                        s.CreatedAt <= DateTime.Now);
            }
            catch (Exception ex)
            {
                On(DisplayErrorMessage, "EX. ERROR: Check for unprocessed notifications: " + ex.Message);
                SimpleErrorLogger.LogError(ex);
            }

            // Process i.e. push the push notification via PushSharp... 
            if (notificationEntity != null)
            {
                bool messagePushed = true;

                On(DisplayStatusMessage, "Processing notification...");
                On(DisplayMessage, "ID " + notificationEntity.ID + " for " + notificationEntity.MobileDevice.Client.Username + " -> " + notificationEntity.Message);

                //---------------------------
                // ANDROID GCM NOTIFICATIONS
                //---------------------------
                if (notificationEntity.MobileDevice.SmartphonePlatform == "android")
                {
                    var gcmNotif = new GcmNotification() { Tag = notificationEntity.ID };
                    string msg = JsonConvert.SerializeObject(new { message = notificationEntity.Message });

                    gcmNotif.ForDeviceRegistrationId(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                            .WithJson(msg);

                    _broker.QueueNotification(gcmNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                ////-------------------------
                //// APPLE iOS NOTIFICATIONS
                ////-------------------------
                else if (notificationEntity.MobileDevice.SmartphonePlatform == "ios")
                {
                    var appleNotif = new AppleNotification() { Tag = notificationEntity.ID };
                    var msg = new AppleNotificationPayload(notificationEntity.Message);

                    appleNotif.ForDeviceToken(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                                .WithPayload(msg)
                                .WithSound("default");

                    _broker.QueueNotification(appleNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                //----------------------
                // WINDOWS NOTIFICATIONS
                //----------------------
                else if (notificationEntity.MobileDevice.SmartphonePlatform.Equals("wp") || notificationEntity.MobileDevice.SmartphonePlatform.Equals("wsa"))
                {
                    var wNotif = new WindowsToastNotification() { Tag = notificationEntity.ID };

                    wNotif.ForChannelUri(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                        .AsToastText02("PushSharp Notification", notificationEntity.Message);

                    _broker.QueueNotification(wNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                else
                {
                    On(DisplayErrorMessage, "ERROR: Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform);

                    notificationEntity.Status = (int)PushNotificationStatus.Error;
                    notificationEntity.ModifiedAt = DateTime.Now;
                    notificationEntity.Description = "(Processor) Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform;
                    SimpleErrorLogger.LogError(new Exception("EX. ERROR: " + notificationEntity.Description));
                    messagePushed = false;
                }

                try
                {
                    // Save changes to DB to keep the correct state of messages
                    _databaseContext.SaveChanges();

                    // bubble out the single push error, else return true to continue iteration
                    if (_isDirectSinglePush)
                        return messagePushed;

                    return true;
                }
                catch (Exception ex)
                {
                    On(DisplayErrorMessage, "EX. ERROR: Updating notification, DB save failed: " + ex.Message);
                    SimpleErrorLogger.LogError(ex);

                    // bubble out the single push error, else return true to continue iteration
                    if (_isDirectSinglePush)
                        return false;

                    return true;
                }
                finally
                {
                    if (_isDirectSinglePush)
                        KillBroker(_databaseContext);
                }
            }
            else
            {
                if (_isDirectSinglePush)
                    KillBroker(_databaseContext);

                // no messages were queued, take a nap...
                return false;
            }
        }
 public AppleNotification()
 {
     this.DeviceToken = string.Empty;
     this.Payload     = new AppleNotificationPayload();
     this.Identifier  = AppleNotification.GetNextIdentifier();
 }
示例#19
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");
		}
 public static AppleNotification WithExpiry(this AppleNotification n, DateTime expiryDate)
 {
     n.Expiration = new DateTime?(expiryDate);
     return(n);
 }
示例#21
0
 public NotificationFailureException(int errorStatusCode, AppleNotification notification)
     : base()
 {
     this.ErrorStatusCode = errorStatusCode;
     this.Notification = notification;
 }
 public static AppleNotification ForDeviceToken(this AppleNotification n, string deviceToken)
 {
     n.DeviceToken = deviceToken;
     return(n);
 }
示例#23
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");
        }