Beispiel #1
0
        public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
            : base(pushChannelFactory ?? new ApplePushChannelFactory(), channelSettings, serviceSettings)
        {
            var appleChannelSettings = channelSettings;

            cancelTokenSource = new CancellationTokenSource();

            //allow control over feedback call interval, if set to zero, don't make feedback calls automatically
            if (appleChannelSettings.FeedbackIntervalMinutes > 0)
            {
                feedbackService = new FeedbackService();
                feedbackService.OnFeedbackReceived  += feedbackService_OnFeedbackReceived;
                feedbackService.OnFeedbackException += (Exception ex) => this.RaiseServiceException(ex);

                if (timerFeedback == null)
                {
                    timerFeedback = new Timer(new TimerCallback((state) =>
                    {
                        try { feedbackService.Run(channelSettings as ApplePushChannelSettings, this.cancelTokenSource.Token); }
                        catch (Exception ex) { base.RaiseServiceException(ex); }

                        //Timer will run first after 10 seconds, then every 10 minutes to get feedback!
                    }), null, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(appleChannelSettings.FeedbackIntervalMinutes));
                }
            }

            //Apple has documented that they only want us to use 20 connections to them
            base.ServiceSettings.MaxAutoScaleChannels = 20;
        }
        public ApplePushService(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(new ApplePushChannelFactory(channelSettings), serviceSettings)
        {
            var appleChannelSettings = channelSettings;
            cancelTokenSource = new CancellationTokenSource();
            feedbackService = new FeedbackService();
            feedbackService.OnFeedbackReceived +=
                this.feedbackService_OnFeedbackReceived;

            // allow control over feedback call interval, if set to zero, don't make feedback calls automatically
            if (appleChannelSettings.FeedbackIntervalMinutes > 0)
            {
                timerFeedback = new Timer(
                    state =>
                        {
                            try
                            {
                                this.feedbackService.Run(
                                    channelSettings, this.cancelTokenSource.Token);
                            }
                            catch (Exception ex)
                            {
                                this.Events.RaiseChannelException(ex, PlatformType.Apple);
                            }

                            // Timer will run first after 10 seconds, then every 10 minutes to get feedback!
                        },
                    null,
                    TimeSpan.FromSeconds(10),
                    TimeSpan.FromMinutes(appleChannelSettings.FeedbackIntervalMinutes));

            }
        }
Beispiel #3
0
		public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
			: base(pushChannelFactory ?? new ApplePushChannelFactory(), channelSettings, serviceSettings)
		{
			var appleChannelSettings = channelSettings;
			cancelTokenSource = new CancellationTokenSource();

			//allow control over feedback call interval, if set to zero, don't make feedback calls automatically
			if (appleChannelSettings.FeedbackIntervalMinutes > 0)
			{
				feedbackService = new FeedbackService();
				feedbackService.OnFeedbackReceived += feedbackService_OnFeedbackReceived;
				feedbackService.OnFeedbackException += (Exception ex) => this.RaiseServiceException (ex);

				if (timerFeedback == null)
				{
					timerFeedback = new Timer(new TimerCallback((state) =>
					{
						try { feedbackService.Run(channelSettings as ApplePushChannelSettings, this.cancelTokenSource.Token); }
						catch (Exception ex) { base.RaiseServiceException(ex); }

						//Timer will run first after 10 seconds, then every 10 minutes to get feedback!
					}), null, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(appleChannelSettings.FeedbackIntervalMinutes));
				}
			}

			//Apple has documented that they only want us to use 20 connections to them
			base.ServiceSettings.MaxAutoScaleChannels = 20;
		}
Beispiel #4
0
        private void CreateApplePushSettings()
        {
            if (needApplePush == false)
            {
                return;
            }
            // Check config file first, then database.
            string fname = ConfigurationManager.AppSettings["ApplePushKeyFileName"];

            string filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fname.Trim());

            if (File.Exists(filename) == false)
            {
                filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\" + fname.Trim());
                if (File.Exists(filename) == false)
                {
                    throw new Exception("File not found: " + filename);
                }
            }
            Console.WriteLine("Using Apple Push Key File: {0}", filename);
            string applePushKeyFilePwd = ConfigurationManager.AppSettings["ApplePushKeyFilePassword"];

            var certBuf = File.ReadAllBytes(filename);
            var cert    = new X509Certificate2(certBuf, applePushKeyFilePwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            bool isProduction = Convert.ToBoolean(ConfigurationManager.AppSettings["ApplePushIsProduction"]);

            Console.WriteLine("Apple Push is production: {0}", isProduction);
            applePushChannelSettings = new PushSharp.Apple.ApplePushChannelSettings(isProduction, cert);

            push.RegisterAppleService(applePushChannelSettings);
        }
        public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
            : base(pushChannelFactory ?? (IPushChannelFactory) new ApplePushChannelFactory(), (IPushChannelSettings)channelSettings, serviceSettings)
        {
            ApplePushService         applePushService    = this;
            ApplePushChannelSettings pushChannelSettings = channelSettings;

            this.cancelTokenSource = new CancellationTokenSource();
            if (pushChannelSettings.FeedbackIntervalMinutes > 0)
            {
                this.feedbackService = new FeedbackService();
                this.feedbackService.OnFeedbackReceived  += new FeedbackService.FeedbackReceivedDelegate(this.feedbackService_OnFeedbackReceived);
                this.feedbackService.OnFeedbackException += (FeedbackService.FeedbackExceptionDelegate)(ex => applePushService.RaiseServiceException(ex));
                if (this.timerFeedback == null)
                {
                    this.timerFeedback = new Timer((TimerCallback)(state =>
                    {
                        try
                        {
                            applePushService.feedbackService.Run(channelSettings, applePushService.cancelTokenSource.Token);
                        }
                        catch (Exception ex)
                        {
                            applePushService.RaiseServiceException(ex);
                        }
                    }), (object)null, TimeSpan.FromSeconds(10.0), TimeSpan.FromMinutes((double)pushChannelSettings.FeedbackIntervalMinutes));
                }
            }
            this.ServiceSettings.MaxAutoScaleChannels = 20;
        }
Beispiel #6
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
            {
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                {
                    certificates.Add(addlCert);
                }
            }

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null) : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
            {
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                {
                    certificates.Add(addlCert);
                }
            }

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Beispiel #8
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));
        }
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Beispiel #10
0
 public void Run(ApplePushChannelSettings settings)
 {
     try
     {
         Run(settings, (new CancellationTokenSource()).Token);
     }
     catch (Exception ex)
     {
         this.RaiseFeedbackException(ex);
     }
 }
Beispiel #11
0
 public void Run(ApplePushChannelSettings settings)
 {
     try
     {
         Run(settings, (new CancellationTokenSource()).Token);
     }
     catch (Exception ex)
     {
         this.RaiseFeedbackException (ex);
     }
 }
Beispiel #12
0
		public ApplePushChannel(ApplePushChannelSettings channelSettings)
		{
			Log.Debug("Creating ApplePushChannel instance " + _channelInstanceId);

			_cancelToken = _cancelTokenSource.Token;

			_appleSettings = channelSettings;

			ConfigureCertificates();

			StartCleanupTimer();
		}
Beispiel #13
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            Log.Debug("Creating ApplePushChannel instance " + _channelInstanceId);

            _cancelToken = _cancelTokenSource.Token;

            _appleSettings = channelSettings;

            ConfigureCertificates();

            StartCleanupTimer();
        }
Beispiel #14
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);
        }
Beispiel #15
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null) : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Beispiel #16
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Beispiel #17
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 ApplePushChannel(ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
            : base(channelSettings, serviceSettings)
        {
            this.appleSettings = channelSettings;

            //Need to load the private key seperately from apple
            // Fixed by [email protected] :
            //      The default is UserKeySet, which has caused internal encryption errors,
            //      Because of lack of permissions on most hosting services.
            //      So MachineKeySet should be used instead.
            certificate = new X509Certificate2(this.appleSettings.CertificateData, this.appleSettings.CertificateFilePassword,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            //Start our cleanup task
            taskCleanup = new Task(() => Cleanup(), TaskCreationOptions.LongRunning);
            taskCleanup.ContinueWith((t) => { var ex = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
            taskCleanup.Start();
        }
Beispiel #19
0
 public ApplePushChannel(ApplePushChannelSettings channelSettings)
 {
     this.cancelToken   = this.cancelTokenSrc.Token;
     this.appleSettings = channelSettings;
     this.certificate   = (X509Certificate)this.appleSettings.Certificate;
     this.certificates  = new X509CertificateCollection();
     if (this.appleSettings.AddLocalAndMachineCertificateStores)
     {
         this.certificates.AddRange((X509CertificateCollection) new X509Store(StoreLocation.LocalMachine).Certificates);
         this.certificates.AddRange((X509CertificateCollection) new X509Store(StoreLocation.CurrentUser).Certificates);
     }
     this.certificates.Add(this.certificate);
     if (this.appleSettings.AdditionalCertificates != null)
     {
         foreach (X509Certificate additionalCertificate in this.appleSettings.AdditionalCertificates)
         {
             this.certificates.Add(additionalCertificate);
         }
     }
     this.timerCleanup = new Timer((TimerCallback)(state => this.Cleanup()), (object)null, TimeSpan.FromMilliseconds(1000.0), TimeSpan.FromMilliseconds(1000.0));
 }
Beispiel #20
0
        public ApplePushChannel(ApplePushChannelSettings channelSettings)
        {
            cancelToken = cancelTokenSrc.Token;

            appleSettings = channelSettings;

            certificate = this.appleSettings.Certificate;

            certificates = new X509CertificateCollection();

            if (appleSettings.AddLocalAndMachineCertificateStores)
            {
                var store = new X509Store(StoreLocation.LocalMachine);
                certificates.AddRange(store.Certificates);

                store = new X509Store(StoreLocation.CurrentUser);
                certificates.AddRange(store.Certificates);
            }

            certificates.Add(certificate);

            if (this.appleSettings.AdditionalCertificates != null)
                foreach (var addlCert in this.appleSettings.AdditionalCertificates)
                    certificates.Add(addlCert);

            timerCleanup = new Timer(state => Cleanup(), null, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));

            if (channelSettings.IdleConnectionResetTimeout.HasValue)
            {
                this.IdleConnectionResetTimer.Interval = channelSettings.IdleConnectionResetTimeout.Value.TotalMilliseconds;
                this.IdleConnectionResetTimer.AutoReset = false;
                this.IdleConnectionResetTimer.Elapsed += (sender, e) =>
                {
                    disconnect();
                };
            }
        }
Beispiel #21
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();
        }
Beispiel #22
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();
        }
Beispiel #23
0
 public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings = null)
 {
     broker.RegisterAppleService(channelSettings, (string)null, serviceSettings);
 }
Beispiel #24
0
 public void StartApplePushService(Apple.ApplePushChannelSettings channelSettings, PushServiceSettings serviceSettings = null)
 {
     appleService = new Apple.ApplePushService(channelSettings, serviceSettings);
     appleService.Events.RegisterProxyHandler(this.Events);
 }
 public ApplePushChannel(ApplePushChannelSettings channelSettings)
     : this(channelSettings, null)
 {
 }
Beispiel #26
0
 public void SetApplePushChannelSettings(bool isProduction, X509Certificate2 certificate)
 {
     this.applePushChannelSettings = new PushSharp.Apple.ApplePushChannelSettings(isProduction, certificate);
     push.RegisterAppleService(applePushChannelSettings);
 }
Beispiel #27
0
        /*	public void Run(ApplePushChannelSettings settings)
         *      {
         *              Run(settings, (new CancellationTokenSource()).Token);
         *      }*/

        public void Run(ApplePushChannelSettings settings /*, CancellationToken cancelToken*/)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);


            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


            //Set up
            byte[]   buffer       = new byte[38];
            int      recd         = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 /*&&  !cancelToken.IsCancellationRequested*/)
            {
                try
                {
                    //Get our seconds since 1970 ?
                    byte[] bSeconds     = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(bSeconds);
                    }

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC and then get it locally
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds).ToLocalTime();

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                    {
                        timestamp = timestamp.ToLocalTime();
                    }

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64 &&
                        timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }
                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }

            try
            {
                stream.Close();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown(SocketShutdown.Both);
                client.Client.Close();
            }
            catch { }

            try { client.Close(); }
            catch { }
        }
		public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings = null)
		{
			RegisterAppleService (broker, channelSettings, null, serviceSettings);
		}
Beispiel #29
0
 public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, string applicationId, IPushServiceSettings serviceSettings = null)
 {
     broker.RegisterService <AppleNotification>((IPushService) new ApplePushService(channelSettings, serviceSettings), applicationId, true);
 }
Beispiel #30
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 #31
0
		public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
		{
			var encoding = Encoding.ASCII;

			var certificate = settings.Certificate;

			var certificates = new X509CertificateCollection();
			certificates.Add(certificate);


			var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

			var stream = new SslStream(client.GetStream(), true,
				(sender, cert, chain, sslErrs) => { return true; },
				(sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

			stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


			//Set up
			byte[] buffer = new byte[1482];
			int bufferIndex = 0;
			int bufferLevel = 0;
			int completePacketSize = 4 + 2 + 32;
			int recd = 0;
			DateTime minTimestamp = DateTime.Now.AddYears(-1);

			//Get the first feedback
			recd = stream.Read(buffer, 0, buffer.Length);

			//Continue while we have results and are not disposing
			while (recd > 0 && !cancelToken.IsCancellationRequested)
			{
				//Update how much data is in the buffer, and reset the position to the beginning
				bufferLevel += recd;
				bufferIndex = 0;

				try
				{
					//Process each complete notification "packet" available in the buffer
					while (bufferLevel - bufferIndex >= completePacketSize)
					{
						//Get our seconds since 1970 ?
						byte[] bSeconds = new byte[4];
						byte[] bDeviceToken = new byte[32];

						Array.Copy(buffer, bufferIndex, bSeconds, 0, 4);

						//Check endianness
						if (BitConverter.IsLittleEndian)
							Array.Reverse(bSeconds);

						int tSeconds = BitConverter.ToInt32(bSeconds, 0);

						//Add seconds since 1970 to that date, in UTC
						var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

						//flag to allow feedback times in UTC or local, but default is local
						if (!settings.FeedbackTimeIsUTC)
							timestamp = timestamp.ToLocalTime();

						//Now copy out the device token
						Array.Copy(buffer, bufferIndex + 6, bDeviceToken, 0, 32);

						var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

						//Make sure we have a good feedback tuple
						if (deviceToken.Length == 64
							&& timestamp > minTimestamp)
						{
							//Raise event
							try
							{
								RaiseFeedbackReceived(deviceToken, timestamp);
							}
							catch { }
						}

						//Keep track of where we are in the received data buffer
						bufferIndex += completePacketSize;
					}
				}
				catch { }

				//Figure out how much data we have left over in the buffer still
				bufferLevel -= bufferIndex;

				//Copy any leftover data in the buffer to the start of the buffer
				if (bufferLevel > 0)
					Array.Copy(buffer, bufferIndex, buffer, 0, bufferLevel);

				//Read the next feedback
				recd = stream.Read(buffer, bufferLevel, buffer.Length - bufferLevel);
			}

			try
			{
				stream.Close ();
				stream.Dispose();
			}
			catch { }

			try 
			{
				client.Client.Shutdown (SocketShutdown.Both);
				client.Client.Dispose ();
			}
			catch { }

			try { client.Close (); } catch { }

		}
 public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
     : this(pushChannelFactory, channelSettings, (IPushServiceSettings)null)
 {
 }
 public ApplePushService(ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
     : this((IPushChannelFactory)null, channelSettings, serviceSettings)
 {
 }
Beispiel #34
0
 public void Run(ApplePushChannelSettings settings)
 {
     Run(settings, (new CancellationTokenSource()).Token);
 }
Beispiel #35
0
 public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
     : this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
 {
 }
Beispiel #36
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");
        }
Beispiel #37
0
 public void Run(ApplePushChannelSettings settings)
 {
     Run(settings, (new CancellationTokenSource()).Token);
 }
Beispiel #38
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            Encoding                  ascii              = Encoding.ASCII;
            X509Certificate2          certificate        = settings.Certificate;
            X509CertificateCollection clientCertificates = new X509CertificateCollection();

            clientCertificates.Add((X509Certificate)certificate);
            TcpClient tcpClient = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);
            SslStream sslStream = new SslStream((Stream)tcpClient.GetStream(), true, (RemoteCertificateValidationCallback)((sender, cert, chain, sslErrs) => true), (LocalCertificateSelectionCallback)((sender, targetHost, localCerts, remoteCert, acceptableIssuers) => (X509Certificate)certificate));

            sslStream.AuthenticateAsClient(settings.FeedbackHost, clientCertificates, SslProtocols.Tls, false);
            byte[]   buffer   = new byte[38];
            DateTime dateTime = DateTime.Now.AddYears(-1);

            for (int index = sslStream.Read(buffer, 0, buffer.Length); index > 0; index = sslStream.Read(buffer, 0, buffer.Length))
            {
                if (!cancelToken.IsCancellationRequested)
                {
                    try
                    {
                        byte[] numArray1 = new byte[4];
                        byte[] numArray2 = new byte[32];
                        Array.Copy((Array)buffer, 0, (Array)numArray1, 0, 4);
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse((Array)numArray1);
                        }
                        DateTime timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((double)BitConverter.ToInt32(numArray1, 0));
                        if (!settings.FeedbackTimeIsUTC)
                        {
                            timestamp = timestamp.ToLocalTime();
                        }
                        Array.Copy((Array)buffer, 6, (Array)numArray2, 0, 32);
                        string deviceToken = BitConverter.ToString(numArray2).Replace("-", string.Empty).ToLower().Trim();
                        if (deviceToken.Length == 64)
                        {
                            if (timestamp > dateTime)
                            {
                                this.RaiseFeedbackReceived(deviceToken, timestamp);
                            }
                        }
                    }
                    catch
                    {
                    }
                    Array.Clear((Array)buffer, 0, buffer.Length);
                }
                else
                {
                    break;
                }
            }
            try
            {
                sslStream.Close();
                sslStream.Dispose();
            }
            catch
            {
            }
            try
            {
                tcpClient.Client.Shutdown(SocketShutdown.Both);
                tcpClient.Client.Dispose();
            }
            catch
            {
            }
            try
            {
                tcpClient.Close();
            }
            catch
            {
            }
        }
Beispiel #39
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                (sender, cert, chain, sslErrs) => { return true; },
                (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);

            //Set up
            byte[] buffer = new byte[38];
            int recd = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                try
                {

                    //Get our seconds since 1970 ?
                    byte[] bSeconds = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                        Array.Reverse(bSeconds);

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC and then get it locally
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds).ToLocalTime();

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                        timestamp = timestamp.ToLocalTime();

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64
                        && timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }

                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }
        }
 public ApplePushChannelFactory(ApplePushChannelSettings applePushChannelSettings)
 {
     this.applePushChannelSettings = applePushChannelSettings;
 }
		public static void RegisterAppleService(this PushBroker broker, ApplePushChannelSettings channelSettings, string applicationId, IPushServiceSettings serviceSettings = null)
		{
			broker.RegisterService<AppleNotification>(new ApplePushService(channelSettings, serviceSettings), applicationId);
		}
Beispiel #42
0
		public ApplePushService(ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
			: this(default(IPushChannelFactory), channelSettings, serviceSettings)
		{
		}
Beispiel #43
0
        private void CreateApplePushSettings()
        {
            if (needApplePush == false)
            {
                return;
            }
            // Check config file first, then database.
            string fname = ConfigurationManager.AppSettings["ApplePushKeyFileName"];

            string filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fname.Trim());
            if (File.Exists(filename) == false)
            {
                filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\" + fname.Trim());
                if (File.Exists(filename) == false)
                    throw new Exception("File not found: " + filename);
            }
            Console.WriteLine("Using Apple Push Key File: {0}", filename);
            string applePushKeyFilePwd = ConfigurationManager.AppSettings["ApplePushKeyFilePassword"];

            var certBuf = File.ReadAllBytes(filename);
            var cert = new X509Certificate2(certBuf, applePushKeyFilePwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            bool isProduction = Convert.ToBoolean(ConfigurationManager.AppSettings["ApplePushIsProduction"]);
            Console.WriteLine("Apple Push is production: {0}", isProduction);
            applePushChannelSettings = new PushSharp.Apple.ApplePushChannelSettings(isProduction, cert);

            push.RegisterAppleService(applePushChannelSettings);
        }
Beispiel #44
0
		public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
			: this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
		{
		}
Beispiel #45
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();
        }
Beispiel #46
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");
		}
Beispiel #47
0
 public ApplePushService(ApplePushChannelSettings channelSettings, IPushServiceSettings serviceSettings)
     : this(default(IPushChannelFactory), channelSettings, serviceSettings)
 {
 }
Beispiel #48
0
 public void SetApplePushChannelSettings(bool isProduction, X509Certificate2 certificate)
 {
     this.applePushChannelSettings = new PushSharp.Apple.ApplePushChannelSettings(isProduction, certificate);
     push.RegisterAppleService(applePushChannelSettings);
 }
Beispiel #49
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            ChannelSettings = settings;

            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);


            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


            //Set up
            byte[]   buffer             = new byte[1482];
            int      bufferIndex        = 0;
            int      bufferLevel        = 0;
            int      completePacketSize = 4 + 2 + 32;
            int      recd         = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            Log.Info("{0} -> Reading for {1}", this, ChannelSettings.ApplicationId);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                Log.Info("{0} -> found some data for {1}!", this, ChannelSettings.ApplicationId);

                //Update how much data is in the buffer, and reset the position to the beginning
                bufferLevel += recd;
                bufferIndex  = 0;

                try
                {
                    //Process each complete notification "packet" available in the buffer
                    while (bufferLevel - bufferIndex >= completePacketSize)
                    {
                        //Get our seconds since 1970 ?
                        byte[] bSeconds     = new byte[4];
                        byte[] bDeviceToken = new byte[32];

                        Array.Copy(buffer, bufferIndex, bSeconds, 0, 4);

                        //Check endianness
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(bSeconds);
                        }

                        int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                        //Add seconds since 1970 to that date, in UTC
                        var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

                        //flag to allow feedback times in UTC or local, but default is local
                        if (!settings.FeedbackTimeIsUTC)
                        {
                            timestamp = timestamp.ToLocalTime();
                        }

                        //Now copy out the device token
                        Array.Copy(buffer, bufferIndex + 6, bDeviceToken, 0, 32);

                        var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                        //Make sure we have a good feedback tuple
                        if (deviceToken.Length == 64 &&
                            timestamp > minTimestamp)
                        {
                            //Raise event
                            try
                            {
                                RaiseFeedbackReceived(deviceToken, timestamp);
                            }
                            catch (Exception ex)
                            {
                                Log.Info("{0}", ex);
                            }
                        }

                        //Keep track of where we are in the received data buffer
                        bufferIndex += completePacketSize;
                    }
                }
                catch (Exception ex) {
                    Log.Info("{0}", ex);
                }

                //Figure out how much data we have left over in the buffer still
                bufferLevel -= bufferIndex;

                //Copy any leftover data in the buffer to the start of the buffer
                if (bufferLevel > 0)
                {
                    Array.Copy(buffer, bufferIndex, buffer, 0, bufferLevel);
                }

                //Read the next feedback
                recd = stream.Read(buffer, bufferLevel, buffer.Length - bufferLevel);
            }

            try
            {
                stream.Close();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown(SocketShutdown.Both);
                client.Client.Dispose();
            }
            catch { }

            try { client.Close(); } catch { }
        }
 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
 }