Beispiel #1
0
 public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback)
 {
     lock (this.sentLock)
     {
         Interlocked.Increment(ref this.trackedNotificationCount);
         AppleNotification notification1 = notification as AppleNotification;
         bool   flag     = true;
         byte[] numArray = new byte[0];
         byte[] bytes;
         try
         {
             bytes = notification1.ToBytes();
         }
         catch (NotificationFailureException ex)
         {
             flag = false;
             Interlocked.Decrement(ref this.trackedNotificationCount);
             if (callback == null)
             {
                 return;
             }
             callback((object)this, new SendNotificationResult(notification, false, (Exception)ex));
             return;
         }
         try
         {
             lock (this.connectLock)
                 this.Connect();
             lock (this.streamWriteLock)
             {
                 if (!this.client.Connected || !this.client.Client.Poll(0, SelectMode.SelectWrite) || !this.networkStream.CanWrite)
                 {
                     throw new ObjectDisposedException("Connection to APNS is not Writable");
                 }
                 this.networkStream.Write(bytes, 0, bytes.Length);
                 this.networkStream.Flush();
                 this.sentNotifications.Add(new SentNotification(notification1)
                 {
                     Callback = callback
                 });
                 Thread.Sleep(1);
             }
         }
         catch (Exception ex)
         {
             this.connected = false;
             Interlocked.Decrement(ref this.trackedNotificationCount);
             Log.Error("Exception during APNS Send: {0} -> {1}", (object)notification1.Identifier, (object)ex);
             bool shouldRequeue = true;
             if (callback == null)
             {
                 return;
             }
             callback((object)this, new SendNotificationResult(notification, shouldRequeue, ex));
         }
     }
 }
Beispiel #2
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);
     }
 }
Beispiel #3
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;
			}
		}
Beispiel #4
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");
        }
Beispiel #5
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");
        }