コード例 #1
0
ファイル: AppPushDemo.cs プロジェクト: yellowjime/Examples
        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);
        }
コード例 #2
0
ファイル: PushNotify.cs プロジェクト: HyggeMail/DevHygge
        public void NotifyIOSUser(string token, string json, NotificationType type)
        {
            ////Fluent construction of an iOS notification
            ////IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            ////  for registered for remote notifications is called, and the device token is passed back to you
            //------------------------- // 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(HostingEnvironment.MapPath(APNSCerticateFile));

            //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')
            if (_pushBroker == null)
            {
                _pushBroker = new PushBroker();
            }

            _pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, APNSCerticateFilePassword, true));

            _pushBroker.QueueNotification(new AppleNotification()
                                          .ForDeviceToken(token)
                                          .WithAlert(json)
                                          .WithCategory(type.ToString())
                                          .WithSound("sound.caf"));
        }
コード例 #3
0
        public void PushWarnToApple(string user, string sendMessage)
        {
            var push = new PushBroker();

            push.OnNotificationSent          += NotificationSent;
            push.OnChannelException          += ChannelException;
            push.OnServiceException          += ServiceException;
            push.OnNotificationFailed        += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated            += ChannelCreated;
            push.OnChannelDestroyed          += ChannelDestroyed;

            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Push\\PushSharp.PushCert.Development.p12"));

            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "123456")); //Extension method

            DataTable dt = this.warningDal.GetDeviceTokenByUser(user);

            foreach (var dataRow in dt.AsEnumerable())
            {
                string deviceToken = dataRow.Field <string>("DeviceToken");
                log.Error(deviceToken);
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(deviceToken)
                                       .WithAlert(sendMessage)
                                       .WithBadge(1)
                                       .WithSound("sound.caf")
                                       );
            }

            push.StopAllServices();
        }
コード例 #4
0
        private static PushBroker CreateBroker()
        {
            var broker = new PushBroker();

            broker.OnNotificationSent          += NotificationSent;
            broker.OnChannelException          += ChannelException;
            broker.OnServiceException          += ServiceException;
            broker.OnNotificationFailed        += NotificationFailed;
            broker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            broker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            broker.OnChannelCreated            += ChannelCreated;
            broker.OnChannelDestroyed          += ChannelDestroyed;

            foreach (var channel in PushBo.Instance.ActiveChannels)
            {
                if (channel.PlatformType == PlatformType.Apple)
                {
                    broker.RegisterAppleService(new ApplePushChannelSettings(ConfigHelp.Production, channel.Cert, channel.CertPassword), channel.ApplicationId);
                }
                else if (channel.PlatformType == PlatformType.Beyondbit)
                {
                    broker.RegisterPushClientService(new BeyondBitPushChannelSettings(channel.ApplicationId));
                }
                else
                {
                    throw new NotImplementedException();
                }
            }

            return(broker);
        }
コード例 #5
0
        private PushBroker createPushBrokerObject(bool isProduction)
        {
            var appleCert = LoadAppleCertificate(isProduction);

            if (appleCert == null)
            {
                TraceHelper.TraceInfo("Could not load Apple certificate!");
            }

            var pushBroker = new PushBroker();

            pushBroker.OnNotificationFailed += pushBroker_OnNotificationFailed;
            pushBroker.OnNotificationSent   += pushBroker_OnNotificationSent;
            pushBroker.OnServiceException   += pushBroker_OnServiceException;

            if (isProduction)
            {
                pushBroker.StopAllServices(); // just in case
            }
            if (appleCert != null)
            {
                pushBroker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(isProduction, appleCert));
            }

            string googleApiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GoogleMessagingAPIkey"];

            pushBroker.RegisterGcmService(new PushSharp.Android.GcmPushChannelSettings(googleApiKey));

            return(pushBroker);
        }
コード例 #6
0
        public static ResultPush Ios(IosMessage iosMessage)
        {
            ResultPush       resultPush  = new ResultPush();
            X509Certificate2 certificate = new X509Certificate2(File.ReadAllBytes(GetConfig.Certificate.IOS), GetConfig.Certificate.IOSPassword);

            var        appleCert = File.ReadAllBytes(GetConfig.Certificate.IOS);
            PushBroker push      = Pusher(resultPush);

            push.RegisterAppleService(new ApplePushChannelSettings(false, certificate));

            AppleNotificationPayload appleNotificationPayload = new AppleNotificationPayload(iosMessage.Alert, iosMessage.Badge.Value, iosMessage.Sound.ToString());

            var appleNotification = new AppleNotification()
                                    .ForDeviceToken(iosMessage.DeviceToken)
                                    .WithPayload(appleNotificationPayload);


            if (iosMessage.Sound.HasValue)
            {
                appleNotification.WithSound(iosMessage.Sound.ToString());
            }

            if (iosMessage.Badge.HasValue)
            {
                appleNotification.WithBadge(iosMessage.Badge.Value);
            }

            push.QueueNotification(appleNotification);

            return(resultPush);
        }
コード例 #7
0
        static void Main(string[] args)
        {
            //Create our service
            var push = new PushBroker();

            //Wire up the events
            push.OnNotificationSent   += NotificationSent;
            push.OnNotificationFailed += NotificationFailed;

            //-------------------------
            // 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, "../../id4test_push_aps_development.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')
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "WEIWEI")); //Extension method
            //Fluent construction of an iOS notification
            //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            //  for registered for remote notifications is called, and the device token is passed back to you
            push.QueueNotification(new AppleNotification()
                                   .ForDeviceToken("cde6d75a0fc144b2bd30e10e15855376e4b53d793e6ccf9495787df19ace48d4")
                                   .WithAlert("Hello World!")
                                   .WithBadge(7)
                                   .WithSound("sound.caf"));
            //Console.ReadKey();
            Console.ReadLine();
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: Allen-Wei/PushSharp
        static void Main(string[] args)
        {
            //Create our push services broker
            var push = new PushBroker();
            var cert = File.ReadAllBytes(@"E:\Projects\PushMessage\Ysd.ApplicationInterface\App_Data\ApplePushCertDev.p12");
            push.RegisterAppleService(new ApplePushChannelSettings(false, cert, "your password"));

            var payload = new AppleNotificationPayload()
            {
                Badge = 7,
                Alert = new AppleNotificationAlert()
                {
                    Body = "Hello " + Guid.NewGuid(),
                    Title = "my title",
                    LocalizedArgs = new List<object> { "Jenna", "Frank" }
                },
                Sound = "chime.aiff"
            };

            push.QueueNotification(
                new AppleNotification("74b14f0ff695f71bb0a34925aada53f6eadcfe824bf461959403851e5f85b43d", payload));

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #9
0
ファイル: Utils.cs プロジェクト: NimalanNR/MobieCommuters
        public void SendPushNotification(int DeviceType, string DeviceToken, string Message, string Data, Guid ID)
        {
            var push = new PushBroker();

            if (DeviceType == 1)
            {
                var obj        = new { message = Message, data = Data, Id = ID };
                var serializer = new JavaScriptSerializer();
                var json       = serializer.Serialize(obj);
                push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyC-TbyCQ9HdAuYAJm0-gJZFQG4kTgBJ4Dg"));
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(DeviceToken)
                                       .WithJson(json)
                                       );
            }
            else if (DeviceType == 2)
            {
                var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/mobie_development.p12"));
                push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "mobie1234"));
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(DeviceToken)
                                       .WithAlert(Message)
                                       .WithBadge(1)
                                       .WithSound("sound.caf")
                                       .WithCustomItem("data", Data)
                                       .WithCustomItem("message", Message)
                                       .WithCustomItem("Id", ID)

                                       );
            }
        }
コード例 #10
0
        /// <summary>
        /// sending push to IoS
        /// </summary>
        /// <param name="deviceRegistrationId"></param>
        /// <param name="pushNotifyType"></param>
        /// <param name="pushInformation"></param>
        private void SendPushToIoS(PushNotificationData pushData)
        {
            var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Certificates/Certificates.p12"));

            m_broker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, ""));
            m_broker.QueueNotification(new AppleNotification().ForDeviceToken(pushData.DevicePushToken).WithAlert(pushData.Message).WithBadge(1));
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: zj960157994/ios-tips
        static void Main(string[] args)
        {
            
            //Create our service    
            var push = new PushBroker();

            //Wire up the events
            push.OnNotificationSent += NotificationSent;
            push.OnNotificationFailed += NotificationFailed;

            //-------------------------
            // 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, "../../id4test_push_aps_development.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')
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "WEIWEI")); //Extension method
            //Fluent construction of an iOS notification
            //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            //  for registered for remote notifications is called, and the device token is passed back to you
            push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken("cde6d75a0fc144b2bd30e10e15855376e4b53d793e6ccf9495787df19ace48d4")
                                       .WithAlert("Hello World!")
                                       .WithBadge(7)
                                       .WithSound("sound.caf"));
            //Console.ReadKey();
            Console.ReadLine();
        }
コード例 #12
0
 public ActionResult ApplePust(string message)
 {
     List<string> deviceToken = ViewBag.deviceTokens;
     //创建推送对象
     var pusher = new PushBroker();
     pusher.OnNotificationSent += pusher_OnNotificationSent;//发送成功事件
     pusher.OnNotificationFailed += pusher_OnNotificationFailed;//发送失败事件
     pusher.OnChannelCreated += pusher_OnChannelCreated;
     pusher.OnChannelDestroyed += pusher_OnChannelDestroyed;
     pusher.OnChannelException += pusher_OnChannelException;
     pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged;
     pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired;
     pusher.OnNotificationRequeue += pusher_OnNotificationRequeue;
     pusher.OnServiceException += pusher_OnServiceException;
     //注册推送服务
     byte[] certificateData = System.IO.File.ReadAllBytes(Server.MapPath("/PushSharpApns/PushSharp.Apns.Production.p12"));
     pusher.RegisterAppleService(new ApplePushChannelSettings(certificateData, "123"));
     foreach (string token in deviceToken)
     {
         //给指定设备发送消息
         pusher.QueueNotification(new AppleNotification()
             .ForDeviceToken(token)
             .WithAlert(message)
             .WithBadge(1)
             .WithSound("default"));
     }
     return View();
 }
コード例 #13
0
 /// <summary>
 ///
 /// </summary>
 public NotificationManager()
 {
     if (_push == null)
     {
         Console.WriteLine("Constructor fired.");
         LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Notification constructor is running.");
         try
         {
             _push = new PushBroker();
             //Registring events.
             _notificationMsgLength             = 0;
             _push.OnNotificationSent          += NotificationSent;
             _push.OnChannelException          += ChannelException;
             _push.OnServiceException          += ServiceException;
             _push.OnNotificationFailed        += NotificationFailed;
             _push.OnNotificationRequeue       += NotificationRequeue;
             _push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
             _push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
             _push.OnChannelCreated            += ChannelCreated;
             _push.OnChannelDestroyed          += ChannelDestroyed;
             var appleCertificate =
                 File.ReadAllBytes(ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePath]);
             var channelSettings = new ApplePushChannelSettings(true, appleCertificate,
                                                                ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePwd]);
             channelSettings.ConnectionTimeout = 36000;
             _push.RegisterAppleService(channelSettings);
             _push.RegisterGcmService(
                 new GcmPushChannelSettings(ConfigurationManager.AppSettings[NeeoConstants.GoogleApiKey]));
         }
         catch (Exception exception)
         {
             Console.WriteLine(exception);
         }
     }
 }
コード例 #14
0
 //This method is designed to check push notification, however without real device it's not possible
 public string HelloWorld(string device)
 {
     //create the puchbroker object
     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;         
            
     try
     {
         var appleCert = File.ReadAllBytes(Server.MapPath("certificate directory"));
                
         push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "certificate password"));
                
         push.QueueNotification(new AppleNotification()
                                             .ForDeviceToken(device)//the recipient device id
                                             .WithAlert("Hello")//the message
                                             .WithBadge(1)
                                             .WithSound("sound.caf")
                                             );
     }
     catch (Exception ex)
     {
          throw ex;
     }
      
     push.StopAllServices(waitForQueuesToFinish: true);
     return "Hello, World!";
 }
コード例 #15
0
        private static void PushIOS(string mensaje, string deviceToken)
        {
            //ejemplo de deviceToken c9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc

            // necesito: Push ssl Certificate (exportado como .p12)
            // password para abrir el certificado

            //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;

            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"../../../Resources/PushSharp.PushCert.Development.p12" ));
            push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "certPassword"));

            push.QueueNotification(
                new AppleNotification()
                .ForDeviceToken(deviceToken)
                .WithAlert(mensaje)
                //.WithSound("default")
                .WithBadge(7));

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
コード例 #16
0
        private static void RegisterApnsService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Apns.ElementInformation.IsPresent)
            {
                return;
            }

            try
            {
                Log.Debug("registering apns service");

                string certPath = config.Apns.CertificatePath;
                if (!Path.IsPathRooted(certPath))
                {
                    certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), certPath);
                }

                var appleCert = File.ReadAllBytes(certPath);
                pushBroker.RegisterAppleService(
                    new ApplePushChannelSettings(!config.Apns.IsDevelopmentMode, appleCert, config.Apns.CertificatePassword)
                {
                    FeedbackIntervalMinutes = config.Apns.FeedbackIntervalMinutes
                });
            }
            catch (Exception error)
            {
                Log.Error("couldn't register apns service", error);
            }
        }
コード例 #17
0
        static void Main(string[] args)
        {
            var push = new PushBroker();

            push.OnNotificationSent          += NotificationSent;
            push.OnChannelException          += ChannelException;
            push.OnServiceException          += ServiceException;
            push.OnNotificationFailed        += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated            += ChannelCreated;
            push.OnChannelDestroyed          += ChannelDestroyed;


            //   XmlDocument data = new XmlDocument();
            //data.Load("http://localhost:49167/Service1.svc/NotificationAll/0");
            //Notificaciones = data.GetElementsByTagName("Notification");
            //int total = Notificaciones.Count;

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

            push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "q1w2e3r4"));
            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyBbsQnPByBI484hHMLOC_FRLowkIKqlWO0"));

            //for(i = 0; i < total-1; i++)
            //{


            //if (Notificaciones[i].ChildNodes[4].InnerText == "iOS")
            //{
            //    ////  APPLE

            for (int i = 0; i <= 30; i++)
            {
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken("3290a71fec3cbb5baaf13dda7b465b82d7f4c552e9a8f69daf9f2679afb6b74d")
                                       .WithAlert("Hola Rodolfo Como estas? _" + i)
                                       .WithBadge(-1)
                                       .WithSound("sound.caf"));
            }

            //          //    }else if(Notificaciones[i].ChildNodes[4].InnerText == "Android"){


            //          for (int i = 0; i < 15; i++)
            //          {
            //              push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("APA91bF17D0nVf-bp0Le3f5mqmxfZFRYs3Pxmfn9yib0LCVCvSjgUL3sYut814rrdSmQ0xq_w_tU2livvAfIH0pNafBY6WAG-NEdKiwc1vCtFT46v4Cqw5RVXFFaoNjXonbo4uPpvNJGqEvoEq9N3gWEqNn7d2Ya")
            //                                    .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
            //              //}
            //          }
            ////          }
            Console.WriteLine("Waiting for Queue to Finish...");
            push.StopAllServices();
            Console.WriteLine("enviados: " + enviado + " perdidos: " + error);
            Console.WriteLine("Queue Finished, press return to exit...");

            Console.ReadLine();
        }
コード例 #18
0
        /// <summary>
        /// Initializes Apple Push Notification Service (APNS)
        /// </summary>
        public static void InitApplePushNotificationService()
        {
            //Registering the Apple Service and sending an iOS Notification
            //byte[] appleCert = File.ReadAllBytes("ApnsSandboxCert.p12");
            byte[] appleCert         = DLLResources.AppleCertificate;
            string appleCertPassword = FWUtils.ConfigUtils.GetAppSettings().Project.AppleCertificatePassword;

            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, appleCertPassword));
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: RCortes/Notificacio
        static void Main(string[] args)
        {
            var push = new PushBroker();

            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated += ChannelCreated;
            push.OnChannelDestroyed += ChannelDestroyed;

             //   XmlDocument data = new XmlDocument();
            //data.Load("http://localhost:49167/Service1.svc/NotificationAll/0");
            //Notificaciones = data.GetElementsByTagName("Notification");
            //int total = Notificaciones.Count;

            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Certificados.p12"));
            push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "q1w2e3r4"));
            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyBbsQnPByBI484hHMLOC_FRLowkIKqlWO0"));

            //for(i = 0; i < total-1; i++)
            //{

                //if (Notificaciones[i].ChildNodes[4].InnerText == "iOS")
                //{
                //    ////  APPLE

            for (int i = 0; i <= 30; i++)
            {
                push.QueueNotification(new AppleNotification()
                                           .ForDeviceToken("3290a71fec3cbb5baaf13dda7b465b82d7f4c552e9a8f69daf9f2679afb6b74d")
                                           .WithAlert("Hola Rodolfo Como estas? _" + i)
                                           .WithBadge(-1)
                                           .WithSound("sound.caf"));

            }

              //          //    }else if(Notificaciones[i].ChildNodes[4].InnerText == "Android"){

              //          for (int i = 0; i < 15; i++)
              //          {
              //              push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("APA91bF17D0nVf-bp0Le3f5mqmxfZFRYs3Pxmfn9yib0LCVCvSjgUL3sYut814rrdSmQ0xq_w_tU2livvAfIH0pNafBY6WAG-NEdKiwc1vCtFT46v4Cqw5RVXFFaoNjXonbo4uPpvNJGqEvoEq9N3gWEqNn7d2Ya")
              //                                    .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
              //              //}
              //          }
              ////          }
            Console.WriteLine("Waiting for Queue to Finish...");
            push.StopAllServices();
            Console.WriteLine("enviados: " + enviado + " perdidos: " + error);
            Console.WriteLine("Queue Finished, press return to exit...");

            Console.ReadLine();
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: Fashionkred/ShopSenseDemo
        static void Main(string[] args)
        {
            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!



            var appleCert = @"C:\apns_prod_cert.p12";

            push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "pass1234")); //Extension method

            DateTime dt = DateTime.UtcNow;

            List <string> tokens = GetTokens();

            foreach (string token in tokens)
            {
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(token)
                                       //.WithAlert("Hello World!")
                                       .WithBadge(1));
                //.WithSound("sound.caf"));
            }
            Console.WriteLine("Waiting for Queue to Finish...");

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

            SetLastRun(dt);

            Console.WriteLine("Queue Finished, press return to exit...");
            //Console.ReadLine();
        }
コード例 #21
0
        /// <summary>
        /// constructor
        /// </summary>
        public RemoteNotification(ApnSettings apnSettings)
        {
            m_DeviceInfoByLogin = new Dictionary <string, DeviceInfo>();
            ///Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "M4_PUSH_Production.p12")
            pushBrokerIOS = new PushBroker();
            var appleCertIOS = File.ReadAllBytes(apnSettings.CertPathIOS);

            pushBrokerIOS.RegisterAppleService(new ApplePushChannelSettings(apnSettings.IsProductionIOS, appleCertIOS, apnSettings.CertPasswordIOS)); // Extension method
            pushBrokerOSX = new PushBroker();
            var appleCertOSX = File.ReadAllBytes(apnSettings.CertPathOSX);

            pushBrokerOSX.RegisterAppleService(new ApplePushChannelSettings(apnSettings.IsProductionOSX, appleCertOSX, apnSettings.CertPasswordOSX, true)); // Extension method
        }
コード例 #22
0
        public static void SendNotification(List <PushNotificationDetail> pushSettings)
        {
            if (pushSettings == null)
            {
                return;
            }
            //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;

            var appleSettings = pushSettings.Where(s => s.NotificationFor.ToLower() == "apple").ToList();

            if (appleSettings.Count > 0 && appleSettings != null)
            {
                var appleSetting = appleSettings.FirstOrDefault();

                var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, appleSetting.P12CertificatePath));
                push.RegisterAppleService(new ApplePushChannelSettings(appleCert, appleSetting.P12Password)); //Extension method
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(appleSetting.DeviceToken)
                                       .WithAlert("New campaign available")
                                       .WithBadge(appleSetting.Badge)
                                       .WithSound(appleSetting.Sound));
            }
            //---------------------------
            // ANDROID GCM NOTIFICATIONS
            //---------------------------
            var androidSettings = pushSettings.Where(s => s.NotificationFor.ToLower() == "android").ToList();

            if (androidSettings.Count > 0 && androidSettings != null)
            {
                var androidSetting = androidSettings.FirstOrDefault();
                push.RegisterGcmService(new GcmPushChannelSettings(androidSetting.GoogleAPIKey));
                //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(androidSetting.DeviceToken)
                                       .WithJson("{\"alert\":\"New campaign available\",\"badge\":" + androidSetting.Badge + ",\"sound\":\"" + androidSetting.Sound + "\"}"));
            }

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
コード例 #23
0
        public TenMsgsController()
        {
            //Wire up the events for all the services that the broker registers
            m_pushBroker.OnNotificationSent          += NotificationSent;
            m_pushBroker.OnChannelException          += ChannelException;
            m_pushBroker.OnServiceException          += ServiceException;
            m_pushBroker.OnNotificationFailed        += NotificationFailed;
            m_pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            m_pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            m_pushBroker.OnChannelCreated            += ChannelCreated;
            m_pushBroker.OnChannelDestroyed          += ChannelDestroyed;

            m_pushBroker.RegisterAppleService(new ApplePushChannelSettings(m_appleCerti, PUSH_CERTI_PWD));

            // push.StopAllServices();
        }
コード例 #24
0
        public PushService()
        {
            Broker = new PushBroker();
            Broker.OnNotificationSent          += NotificationSent;
            Broker.OnChannelException          += ChannelException;
            Broker.OnServiceException          += ServiceException;
            Broker.OnNotificationFailed        += NotificationFailed;
            Broker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            Broker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            Broker.OnChannelCreated            += ChannelCreated;
            Broker.OnChannelDestroyed          += ChannelDestroyed;
            var path      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"yourfile");
            var appleCert = File.ReadAllBytes(path);

            Broker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "yourpass", true)); //Extension method
        }
コード例 #25
0
        public Stream SendMessage(Stream messageBody)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(messageBody);

                var msg  = new PushMessage(doc, _solution.Name);
                var push = new PushBroker();

                string result = "";

                if (msg.HasGcmRecipients)
                {
                    push.RegisterGcmService(new GcmPushChannelSettings(AndroidServerKey));

                    string json = "{\"alert\":\"" + msg.Data + "\"}";
                    foreach (string token in msg.GcmTokens)
                    {
                        push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(token).WithJson(json));
                    }
                    result += "Android: ok; ";
                }

                if (msg.HasApnsRecipients)
                {
                    var appleCert = Convert.FromBase64String(IosProductionCertificate);
                    push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "h2o+c2h5oh"));
                    foreach (string token in msg.ApnsTokens)
                    {
                        push.QueueNotification(new AppleNotification()
                                               .ForDeviceToken(token)
                                               .WithAlert(msg.Data)
                                               .WithSound("sound.caf"));
                    }

                    result += "IOS: ok; ";
                }

                return(Common.Utils.MakeTextAnswer(result));
            }
            catch (Exception e)
            {
                return(Common.Utils.MakeExceptionAnswer(e));
            }
        }
コード例 #26
0
        public void SendPushNotifications(IEnumerable <string> userDeviceTokens, string alert, int badge, string customItem)
        {
            var push = new PushBroker();

            push.RegisterAppleService(new ApplePushChannelSettings(true, _appleCert, ""));

            foreach (var deviceToken in userDeviceTokens)
            {
                push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken(deviceToken)
                                       .WithAlert(alert)
                                       .WithBadge(badge)
                                       .WithSound("default")
                                       .WithCustomItem("MessageId", customItem));
            }

            push.StopAllServices();
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: hhempel/StoryboardTables
        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();
        }
コード例 #28
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AzureStorageConfig.RegisterConfiguration();

            PushBroker = new PushBroker();

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AppleAPNSCertFile"]))
            {
                byte[] appleCert = File.ReadAllBytes(ConfigurationManager.AppSettings["AppleAPNSCertFile"]);
                PushBroker.RegisterAppleService(new ApplePushChannelSettings(appleCert, ConfigurationManager.AppSettings["AppleAPNSCertPassword"]));
                IsApplePushRegistered = true;
            }
        }
コード例 #29
0
ファイル: Global.asax.cs プロジェクト: AArnott/IronPigeon
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AzureStorageConfig.RegisterConfiguration();

            PushBroker = new PushBroker();

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AppleAPNSCertFile"]))
            {
                byte[] appleCert = File.ReadAllBytes(ConfigurationManager.AppSettings["AppleAPNSCertFile"]);
                PushBroker.RegisterAppleService(new ApplePushChannelSettings(appleCert, ConfigurationManager.AppSettings["AppleAPNSCertPassword"]));
                IsApplePushRegistered = true;
            }
        }
コード例 #30
0
        //private devicePlatform type;

        public NeeoNotification()
        {
            if (_push == null)
            {
                _push = new PushBroker();

                _push.OnNotificationSent          += NotificationSent;
                _push.OnChannelException          += ChannelException;
                _push.OnServiceException          += ServiceException;
                _push.OnNotificationFailed        += NotificationFailed;
                _push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
                _push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
                _push.OnChannelCreated            += ChannelCreated;
                _push.OnChannelDestroyed          += ChannelDestroyed;
                var appleCertificate = File.ReadAllBytes("E:\\APNSDistCertificate.p12");
                _push.RegisterAppleService(new ApplePushChannelSettings(true, appleCertificate, "PowerfulP1234"));
                _push.RegisterGcmService(new GcmPushChannelSettings("YOUR Google API's Console API Access  API KEY for Server Apps HERE"));
            }
        }
コード例 #31
0
        /// <summary>
        ///
        /// </summary>

        public NotificationManager()
        {
            if (_push == null)
            {
                _push = new PushBroker();
                //Registring events.
                _push.OnNotificationSent          += NotificationSent;
                _push.OnChannelException          += ChannelException;
                _push.OnServiceException          += ServiceException;
                _push.OnNotificationFailed        += NotificationFailed;
                _push.OnNotificationRequeue       += NotificationRequeue;
                _push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
                _push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
                _push.OnChannelCreated            += ChannelCreated;
                _push.OnChannelDestroyed          += ChannelDestroyed;
                var appleCertificate = File.ReadAllBytes(ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePath]);
                _push.RegisterAppleService(new ApplePushChannelSettings(true, appleCertificate, ConfigurationManager.AppSettings[NeeoConstants.AppleCertificatePwd]));
                //_push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings[NeeoConstants.GoogleApiKey].ToString()));
            }
        }
コード例 #32
0
        void ConfigureIos(NotiConfig config, string basePath)
        {
            this.HasIos = config.HasIos;
            if (this.HasIos)
            {
                try
                {
                    var path    = Path.Combine(basePath, config.ApnCertFile);
                    var bytes   = File.ReadAllBytes(path);
                    var setting = new ApplePushChannelSettings(config.ApnProduction, bytes, config.ApnCertPassword);
                    pushBroker.RegisterAppleService(setting);
                }
                catch (Exception ex)
                {
                    logger.Error("Error when adding iOS", ex);

                    this.HasIos = false;
                }
            }
        }
コード例 #33
0
ファイル: Program.cs プロジェクト: l0vekobe0824/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();
        }
コード例 #34
0
        private void sendNotification(bool isApple, bool isAndroid, string deviceToken, string notificationText)
        {
            if (string.IsNullOrEmpty(deviceToken))
            {
                MessageBox.Show(this, "Enter device token");
                return;
            }

            var pushBroker = new PushBroker();

            pushBroker.OnNotificationFailed += pushBroker_OnNotificationFailed1;
            pushBroker.OnNotificationSent   += pushBroker_OnNotificationSent;
            pushBroker.OnServiceException   += pushBroker_OnServiceException;

            if (isApple)
            {
                var appleCert = loadAppleCertificate();
                pushBroker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(isProduction, appleCert));

                pushBroker.QueueNotification(new AppleNotification()
                                             .ForDeviceToken(this.fixAppleToken(deviceToken))
                                             .WithAlert(notificationText)
                                             .WithTag(1));
            }

            if (isAndroid)
            {
                string googleApiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GoogleMessagingAPIkey"];
                pushBroker.RegisterGcmService(new PushSharp.Android.GcmPushChannelSettings(googleApiKey));

                pushBroker.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken)
                                             .WithTag("77")
                                             .WithData(new Dictionary <string, string>()
                {
                    { "message", notificationText },
                    { "title", "Test" }
                }));
            }

            pushBroker.StopAllServices();
        }
コード例 #35
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap data = context.JobDetail.JobDataMap;
            var certFile = data.GetString("p12");
            var certPwd = data.GetString("password");
            //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;

            //configure certificate
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certFile));
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, certPwd));
           
            QueueNotification(push,context);
            push.StopAllServices();
        }
コード例 #36
0
        public static void Send(List <string> deviceTokenList, string message, string cerficationPath, string certificatePassword)
        {
            //推送器
            push = push ?? new PushBroker();

            //订阅推送的回调事件
            push.OnNotificationSent          += NotificationSent;
            push.OnChannelException          += ChannelException;
            push.OnServiceException          += ServiceException;
            push.OnNotificationFailed        += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated            += ChannelCreated;
            push.OnChannelDestroyed          += ChannelDestroyed;

            //注册推送要用的证书
            push.RegisterAppleService(new ApplePushChannelSettings(true, File.ReadAllBytes(cerficationPath), certificatePassword),
                                      "yourAppId_production");

            //生成推送任务并放入到推送队列中
            foreach (var token in deviceTokenList)
            {
                if (token.Length == 64)
                {
                    try
                    {
                        push.QueueNotification(new AppleNotification()
                                               .ForDeviceToken(token)
                                               .WithAlert(message).WithBadge(1));
                    }
                    catch
                    {
                        continue;
                    }
                }
            }

            //等待所有的推送任务完成并停止推送服务
            push.StopAllServices();
        }
コード例 #37
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();
        }
コード例 #38
0
        public static void Notify(DeviceToken deviceToken, string message)
        {
            //Create our push services broker
            var push = new PushBroker();

            push.OnChannelException += PushOnOnChannelException;
            push.OnNotificationFailed += PushOnOnNotificationFailed;
            push.OnNotificationSent += PushOnOnNotificationSent;
            push.OnServiceException += PushOnOnServiceException;
            if (deviceToken.Device.Contains("iOS"))
            {
                //Registering the Apple Service and sending an iOS Notification
                var appleCert = File.ReadAllBytes("C:\\Certs\\Certificate.p12");
                push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "password"));
                push.QueueNotification(new AppleNotification()
                    .ForDeviceToken(deviceToken.Token)
                    .WithAlert(message)
                    .WithBadge(1)
                    .WithSound("sound.caf"));
            }
            else if (deviceToken.Device.Contains("Android"))
            {
                //Registering the GCM Service and sending an Android Notification
                push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyD8GfrF6Sgcw6WQRSVCij110rHuUmm4Zus"));
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken.Token)
                    .WithJson("{\"alert\":\"" + message + "\",\"to\":\"/topics/global\",\"badge\":1,\"sound\":\"sound.caf\"}"));
            }
            //else if (deviceToken.Device.Contains("windows"))
            //{
            //    push.QueueNotification(new WindowsPhoneToastNotification()
            //              .ForEndpointUri(new Uri(model.ChannelURI))
            //              .ForOSVersion(WindowsPhoneDeviceOSVersion.Eight)
            //              .WithBatchingInterval(BatchingInterval.Immediate)
            //              .WithNavigatePath(model.NavigatePath)
            //              .WithText1("Datadruid Push")
            //              .WithText2(message));
            //}

            push.StopAllServices();
        }
コード例 #39
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap data     = context.JobDetail.JobDataMap;
            var        certFile = data.GetString("p12");
            var        certPwd  = data.GetString("password");
            //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;

            //configure certificate
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certFile));

            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, certPwd));

            QueueNotification(push, context);
            push.StopAllServices();
        }
コード例 #40
0
        public static void SendPush(string deviceToken, string message, int badge)
        {
            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;

            var appleCert = System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("/PushCert.Development.p12"));

            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "Abc@@123")); //Extension method
            push.QueueNotification(new AppleNotification()
                                   .ForDeviceToken(deviceToken)
                                   .WithAlert(message)
                                   .WithBadge(badge));
        }
コード例 #41
0
        public void testPush()
        {
            using(var push = new PushBroker())
            {

            //**** iOS Notification ******
            //Establish the connection to your certificates. Here we make one for dev and another for production
            byte[] appleCertificate = null;
            //appleCertificate = Properties.Resources.DEV_CERT_NAME;
            //appleCertificate = Properties.Resources.PROD_CERT_NAME;

            //If the file exists, go ahead and use it to send an apple push notification
            if (appleCertificate != null)
            {

                //Give the apple certificate and its password to the push broker for processing
                push.RegisterAppleService(new ApplePushChannelSettings(appleCertificate, "password"));

                //Queue the iOS push notification
                push.QueueNotification(new AppleNotification()
                               .ForDeviceToken("DEVICE_TOKEN_HERE")
                               .WithAlert("Hello World!")
                               .WithBadge(7)
                               .WithSound("sound.caf"));
            }
            //*********************************

            //**** Android Notification ******
            //Register the GCM Service and sending an Android Notification with your browser API key found in your google API Console for your app. Here, we use ours.
            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyD3J2zRHVMR1BPPnbCVaB1D_qWBYGC4-uU"));

            //Queue the Android notification. Unfortunately, we have to build this packet manually.
            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE_REGISTRATION_ID")
                      .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
            //*********************************
            }
        }
コード例 #42
0
ファイル: Program.cs プロジェクト: mamta-bisht/VS2013Roadshow
        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();
        }
コード例 #43
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();
        }
コード例 #44
0
        public Stream SendMessage(Stream messageBody)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(messageBody);

                var msg = new PushMessage(doc, _solution.Name);
                var push = new PushBroker();

                string result = "";

                if (msg.HasGcmRecipients)
                {
                    push.RegisterGcmService(new GcmPushChannelSettings(AndroidServerKey));

                    string json = "{\"alert\":\"" + msg.Data + "\"}";
                    foreach (string token in msg.GcmTokens)
                        push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(token).WithJson(json));
                    result += "Android: ok; ";
                }

                if (msg.HasApnsRecipients)
                {
                    var appleCert = Convert.FromBase64String(IosProductionCertificate);
                    push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "h2o+c2h5oh"));
                    foreach (string token in msg.ApnsTokens)
                    {
                        push.QueueNotification(new AppleNotification()
                            .ForDeviceToken(token)
                            .WithAlert(msg.Data)
                            .WithSound("sound.caf"));
                    }

                    result += "IOS: ok; ";
                }

                return Common.Utils.MakeTextAnswer(result);

            }
            catch (Exception e)
            {
                return Common.Utils.MakeExceptionAnswer(e);
            }
        }
コード例 #45
0
ファイル: Program.cs プロジェクト: FragCoder/PushSharp
        static void Main(string[] args)
        {
            //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/PushSharp.Apns.Sandbox.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')
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "CERTIFICATE PASSWORD HERE")); //Extension method
            //Fluent construction of an iOS notification
            //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            //  for registered for remote notifications is called, and the device token is passed back to you
            push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken("DEVICE TOKEN HERE")
                                       .WithAlert("Hello World!")
                                       .WithBadge(7)
                                       .WithSound("sound.caf"));

            //---------------------------
            // 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("YOUR Google API's Console API Access  API KEY for Server Apps HERE"));
            //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("DEVICE REGISTRATION ID HERE")
                                  .WithJson("{\"alert\":\"Hello World!\",\"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();
        }
コード例 #46
0
        private static void RegisterApnsService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Apns.ElementInformation.IsPresent)
                return;

            try
            {
                Log.Debug("registering apns service");

                string certPath = config.Apns.CertificatePath;
                if (!Path.IsPathRooted(certPath))
                    certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), certPath);

                var appleCert = File.ReadAllBytes(certPath);
                pushBroker.RegisterAppleService(
                    new ApplePushChannelSettings(!config.Apns.IsDevelopmentMode, appleCert, config.Apns.CertificatePassword)
                        {
                            FeedbackIntervalMinutes = config.Apns.FeedbackIntervalMinutes
                        });
            }
            catch (Exception error)
            {
                Log.Error("couldn't register apns service", error);
            }
        }
コード例 #47
0
ファイル: Program.cs プロジェクト: lbosman/PushSharp
        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();
        }
コード例 #48
0
        private static PushBroker CreateBroker()
        {
            var broker = new PushBroker();

            broker.OnNotificationSent += NotificationSent;
            broker.OnChannelException += ChannelException;
            broker.OnServiceException += ServiceException;
            broker.OnNotificationFailed += NotificationFailed;
            broker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            broker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            broker.OnChannelCreated += ChannelCreated;
            broker.OnChannelDestroyed += ChannelDestroyed;

            foreach (var channel in PushBo.Instance.ActiveChannels)
            {
                if (channel.PlatformType == PlatformType.Apple)
                {
                    broker.RegisterAppleService(new ApplePushChannelSettings(ConfigHelp.Production, channel.Cert, channel.CertPassword), channel.ApplicationId);
                }
                else if (channel.PlatformType == PlatformType.Beyondbit)
                {
                    broker.RegisterPushClientService(new BeyondBitPushChannelSettings(channel.ApplicationId));
                }
                else throw new NotImplementedException();
            }

            return broker;
        }
コード例 #49
0
ファイル: PushBid.aspx.cs プロジェクト: giangonz/GovBids
        protected void btnPush_Click(object sender, EventArgs e)
        {
            //Create our push services broker
            var push = new PushBroker();
            try
            {
                if (ddlBids.SelectedItem.Value != null && Convert.ToInt32(ddlBids.SelectedItem.Value) != 0)
                {
                    //Wire up the events for all the services that the broker registers
                    push.OnNotificationSent += NotificationSent;
                    push.OnNotificationFailed += NotificationFailed;

                    //Apple settings for push
                    string appdatafolder = Server.MapPath("~\\App_Data\\");
                    var appleCert = File.ReadAllBytes(Path.Combine(appdatafolder, ConfigurationManager.AppSettings["AppleCert"]));

                    //Development = false; Production = True
                    push.RegisterAppleService(new ApplePushChannelSettings(Convert.ToBoolean(ConfigurationManager.AppSettings["IsProduction"]), appleCert, ConfigurationManager.AppSettings["AppleCertPWD"]));

                    push.RegisterWindowsPhoneService();

                    //fetch all devices for push
                    foreach (var item in GovBidsDAL.FetchDataDeviceTokens())
                    {

                        switch (item.DeviceType)
                        {
                            case "iOS":
                                //Queue notification
                                push.QueueNotification(new AppleNotification()
                                                     .ForDeviceToken(item.DeviceToken)
                                                     .WithAlert(ConfigurationManager.AppSettings["NotificationLabel"] + " : " + GovBidsDAL.FetchDataBidByID(Convert.ToInt32(ddlBids.SelectedItem.Value)).Title)
                                                     .WithBadge(1)
                                                     .WithSound(ConfigurationManager.AppSettings["AppleSoundName"]));
                                break;
                            case "WP8":
                                push.QueueNotification(new WindowsPhoneToastNotification()
                                                     .ForEndpointUri(new Uri(item.DeviceToken))
                                                     .ForOSVersion(WindowsPhoneDeviceOSVersion.Eight)
                                                     .WithBatchingInterval(BatchingInterval.Immediate)
                                                     .WithNavigatePath("/MainPage.xaml")
                                                     .WithText1(ConfigurationManager.AppSettings["NotificationLabel"])
                                                     .WithText2(GovBidsDAL.FetchDataBidByID(Convert.ToInt32(ddlBids.SelectedItem.Value)).Title));
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //Stop and wait for the queues to drains
                try
                {
                    push.StopAllServices();
                }
                catch (Exception) { }

                push = null;
            }
        }
コード例 #50
0
ファイル: Program.cs プロジェクト: RCortes/BBVA
        static void Main(string[] args)
        {
            Process[] localAll = Process.GetProcesses();
            int p = 1;
            foreach (Process pr in localAll)
            {
                if (pr.ProcessName == "sendNotificationiOS")
                {
                    if (p > 1)
                    {
                        Console.Write("\n\n\n \"sendNotificationiOS.exe\" ya esta en ejecución... será cerrada");
                        System.Threading.Thread.Sleep(3000);
                        Environment.Exit(0);
                    }
                    p++;
                }
            }

            Console.Write("Envio de Notificaciones iOS \n\n Procesando...");

            var push = new PushBroker();

            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated += ChannelCreated;
            push.OnChannelDestroyed += ChannelDestroyed;

            SqlConnection conn = new SqlConnection(connectionString: conex);

            try
            {
                conn.Open();

                while (true)
                {
                    string type = "";

                    DateTime actual = DateTime.Parse("00:00:00");
                    DateTime start = Convert.ToDateTime("00:00:00");
                    DateTime duration = Convert.ToDateTime("00:00:00");

                    string sqlSelectSchedule = @"UPDATE dbo.NotificationType SET start = DATEADD (year, 2001 - YEAR(start), start)
                                                 UPDATE dbo.NotificationType SET start = DATEADD (month, 01 - MONTH(start), start)
                                                 UPDATE dbo.NotificationType SET start = DATEADD (day, 01 - DAY(start), start)
                                                 SELECT idNotificationType, start, duration FROM dbo.NotificationType ORDER BY start ASC";

                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

                    SqlDataAdapter daAdaptador = new SqlDataAdapter(command);
                    DataSet dtDatos = new DataSet();
                    daAdaptador.Fill(dtDatos);

                    foreach (DataRow _dr in dtDatos.Tables[0].Rows)
                    {
                        actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());
                        start = DateTime.Parse("01-01-0001 " + DateTime.Parse(_dr[1].ToString()).ToShortTimeString());
                        duration = DateTime.Parse("01-01-0001 " + DateTime.Parse(_dr[1].ToString()).ToShortTimeString()).AddMinutes(15);

                        if(DateTime.Compare(actual, start) >= 0)
                        {
                            type = _dr[0].ToString();
                        }
                    }

                    string sqlCountUser = @"SELECT COUNT(*) FROM dbo.Notification WHERE idNotificationType = @idtype";

                    command = new SqlCommand(sqlCountUser, conn);
                    command.Parameters.AddWithValue("@idtype", ConfigurationManager.AppSettings["type"]);

                    int countU = 0;
                    countU = Convert.ToInt32(command.ExecuteScalar());

                    if (countU > 0)
                    {
                        type = ConfigurationManager.AppSettings["type"];
                    }

                    if (type != "")
                    {

            //                        if (type == "8")
            //                        {

            //                            string selectHoldOver = @"SELECT * FROM HoldOver WHERE expiration >= @expiration";

            //                            command = new SqlCommand(selectHoldOver, conn);
            //                            command.Parameters.AddWithValue("@expiration", DateTime.Parse(DateTime.Now.ToShortDateString() + " 00:00:00"));

            //                            daAdaptador = new SqlDataAdapter(command);
            //                            dtDatos = new DataSet();
            //                            daAdaptador.Fill(dtDatos);

            //                            foreach (DataRow _dr in dtDatos.Tables[0].Rows)
            //                            {
            //                                string delivery = DateTime.Parse(_dr[2].ToString()).ToShortDateString() + " 00:00:00";
            //                                string ahora = DateTime.Now.ToShortDateString() + " 00:00:00";

            //                                if (DateTime.Compare(DateTime.Parse(delivery), DateTime.Parse(ahora)) < 0)
            //                                {
            //                                    try
            //                                    {
            //                                        string insertNotification = @"INSERT INTO [Notification]
            //                                                                             ([idDevice]
            //                                                                             ,[idNotificationType]
            //                                                                             ,[idPlataform]
            //                                                                             ,[creation]
            //                                                                             ,[idUsers]
            //                                                                             ,[shortText]
            //                                                                             ,[longText]
            //                                                                             ,[deliveryPossibilities]
            //                                                                             ,[expiration])
            //                                                                       VALUES
            //                                                                             (@idDevice
            //                                                                             ,@idNotificationType
            //                                                                             ,@idPlataform
            //                                                                             ,@creation
            //                                                                             ,@idUsers
            //                                                                             ,@shortText
            //                                                                             ,@longText
            //                                                                             ,@deliveryPossibilities
            //                                                                             ,@expiration)";

            //                                        command = new SqlCommand(insertNotification, conn);
            //                                        command.Parameters.AddWithValue("@idDevice", _dr[5].ToString());
            //                                        command.Parameters.AddWithValue("@idNotificationType", _dr[3].ToString());
            //                                        command.Parameters.AddWithValue("@idPlataform", _dr[6].ToString());
            //                                        command.Parameters.AddWithValue("@creation", DateTime.Parse(_dr[1].ToString()));
            //                                        command.Parameters.AddWithValue("@idUsers", _dr[4].ToString());
            //                                        command.Parameters.AddWithValue("@shortText", _dr[7].ToString());
            //                                        command.Parameters.AddWithValue("@longText", _dr[8].ToString());
            //                                        command.Parameters.AddWithValue("@deliveryPossibilities", _dr[10].ToString());
            //                                        command.Parameters.AddWithValue("@expiration", DateTime.Parse(_dr[11].ToString()));
            //                                        command.ExecuteScalar();

            //                                        string deleteHoldOver = @"DELETE FROM [Notificaciones].[dbo].[HoldOver]
            //                                                                             WHERE idHoldOver = @idHoldOver";

            //                                        command = new SqlCommand(deleteHoldOver, conn);
            //                                        command.Parameters.AddWithValue("@idHoldOver", _dr[0].ToString());
            //                                        command.ExecuteScalar();

            //                                    }
            //                                    catch (Exception ex)
            //                                    {
            //                                        //conn.Close();
            //                                        Console.Write(ex.Message);
            //                                        string body = "\n Error: " + ex.Message + " \n hora: " + DateTime.Now.ToString();
            //                                        Emails.Email.Enviarcorreo("Error envio de push iOS BBVA", "*****@*****.**", body, "Error");

            //                                    }
            //                                }
            //                            }

            //                                    try
            //                                    {
            //                                        string delete = @"DELETE FROM HoldOver WHERE expiration < @expiration";

            //                                        command = new SqlCommand(delete, conn);
            //                                        command.Parameters.AddWithValue("@expiration", DateTime.Parse(DateTime.Now.AddDays(-1).ToShortDateString() + " 00:00:00"));
            //                                        command.ExecuteScalar();
            //                                    }
            //                                    catch (Exception ex)
            //                                    {
            //                                        Console.Write(ex.Message);
            //                                        string body = "\n Error: " + ex.Message + " \n hora: " + DateTime.Now.ToString();
            //                                        Emails.Email.Enviarcorreo("Error envio de push iOS BBVA", "*****@*****.**", body, "Error");

            //                                    }
            //                        }

                        int i = 0;

                        string sql = @"SELECT * FROM dbo.Notification WHERE idPlataform = 2 AND idNotificationType = @type ORDER BY creation";

                        command = new SqlCommand(sql, conn);

                        daAdaptador = new SqlDataAdapter(command);
                        command.Parameters.AddWithValue("@type", type);
                        dtDatos = new DataSet();
                        daAdaptador.Fill(dtDatos);

                        push.StopAllServices(true);

                        var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["certificate"]));
                        //push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, ConfigurationManager.AppSettings["password"], disableCertificateCheck: true));
                        push.RegisterAppleService(new ApplePushChannelSettings(Convert.ToBoolean(ConfigurationManager.AppSettings["server"]), appleCert, ConfigurationManager.AppSettings["password"]), new PushServiceSettings() { AutoScaleChannels = false, Channels = 1, MaxAutoScaleChannels = 1, MaxNotificationRequeues = 2, NotificationSendTimeout = 5000 });

                        List<string> IDs = new List<string>();
                        foreach (DataRow _dr in dtDatos.Tables[0].Rows)
                        {
                                //string expiration = DateTime.Parse(_dr[14].ToString()).ToShortDateString() + " 00:00:00";
                                //string ahora = DateTime.Now.ToShortDateString() + " 00:00:00";

                                //if (DateTime.Compare(DateTime.Parse(expiration), DateTime.Parse(ahora)) <= 0)
                                //{
                                    push.QueueNotification(new AppleNotification()
                                                               .ForDeviceToken(_dr[1].ToString())
                                                               .WithAlert(_dr[11].ToString())
                                                               .WithBadge(1)
                                                               .WithExpiry(DateTime.Now.AddHours(1))
                                                               .WithSound("default.caf"));
                                //}

                            // push.StopAllServices();

                            try
                            {
                                string deleteNotification = @"DELETE FROM dbo.Notification WHERE idNotificacion = @idNotification";
                                command = new SqlCommand(deleteNotification, conn);
                                command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                command.ExecuteScalar();
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    string updateHistorical = @"UPDATE dbo.Notification SET idUsers = 0, idDevice = 0 WHERE idNotificacion = @idNotification";
                                    command = new SqlCommand(updateHistorical, conn);
                                    command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                    command.ExecuteScalar();

                                    string deleteNotification = @"DELETE FROM dbo.Notification WHERE idNotificacion = @idNotification";
                                    command = new SqlCommand(deleteNotification, conn);
                                    command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                    command.ExecuteScalar();

                                }
                                catch (Exception ex2)
                                {
                                    Console.Write(ex2.Message);
                                    System.Threading.Thread.Sleep(3000);
                                }

                            }
                            finally
                            {

                            }

                            actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());

                            if (DateTime.Compare(actual, duration) > 0)
                            {
                                break;
                            }
                        }

                    }
                    push.StopAllServices(true);
                    System.Threading.Thread.Sleep(5000);
                }
                conn.Close();

            }
            catch (Exception ex)
            {
                conn.Close();
                Console.Write(ex.Message);
                string body = "\n Error: " + ex.Message + " \n hora: " + DateTime.Now.ToString();
                Emails.Email.Enviarcorreo("Error envio de push iOS BBVA", "*****@*****.**", body, "Error");
                System.Threading.Thread.Sleep(7000);
                push.StopAllServices(true);
                Environment.Exit(0);
            }
        }
コード例 #51
0
ファイル: Cronus.cs プロジェクト: Elders/Pushnotifications
        private static PushBroker ConfigurePushBroker(Pandora pandora)
        {
            var broker = new PushBroker();
            broker.OnNotificationSent += PushNotificationLogger.NotificationSent;
            broker.OnChannelException += PushNotificationLogger.ChannelException;
            broker.OnServiceException += PushNotificationLogger.ServiceException;
            broker.OnNotificationFailed += PushNotificationLogger.NotificationFailed;
            broker.OnDeviceSubscriptionExpired += PushNotificationLogger.DeviceSubscriptionExpired;
            broker.OnDeviceSubscriptionChanged += PushNotificationLogger.DeviceSubscriptionChanged;
            broker.OnChannelCreated += PushNotificationLogger.ChannelCreated;
            broker.OnChannelDestroyed += PushNotificationLogger.ChannelDestroyed;

            var iosCert = pandora.Get("pushnot_ios_cert");
            var iosCertPass = pandora.Get("pushnot_ios_cert_pass");

            var androidToken = pandora.Get("pushnot_android_token");

            var parseAppId = pandora.Get("pushnot_parse_app_id");
            var parseRestApiKey = pandora.Get("pushnot_parse_rest_api_key");

            string iosCertPath = Environment.ExpandEnvironmentVariables(iosCert);

            var appleCert = File.ReadAllBytes(iosCertPath);

            bool iSprod = Boolean.Parse(pandora.Get("pushnot_ios_production"));
            broker.RegisterAppleService(new ApplePushChannelSettings(iSprod, appleCert, iosCertPass, disableCertificateCheck: true));
            broker.RegisterGcmService(new GcmPushChannelSettings(androidToken));

            return broker;
        }
コード例 #52
0
ファイル: Program.cs プロジェクト: RCortes/BBVA
        static void Main(string[] args)
        {
            Process[] localAll = Process.GetProcesses();
            int p = 1;
            foreach (Process pr in localAll)
            {
                if (pr.ProcessName == "sendNotificationiOS")
                {
                    if (p > 1)
                    {
                        Console.Write("\n\n\n \"sendNotificationiOS.exe\" ya esta en ejecución... será cerrada");
                        System.Threading.Thread.Sleep(3000);
                        Environment.Exit(0);
                    }
                    p++;
                }
            }

            Console.Write("Envio de Notificaciones iOS \n\n Procesando...");

            var push = new PushBroker();

            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated += ChannelCreated;
            push.OnChannelDestroyed += ChannelDestroyed;

            SqlConnection conn = new SqlConnection(connectionString: conex);

            try
            {
                conn.Open();

                while (true)
                {
                    string type = "";

                    DateTime actual = DateTime.Parse("00:00:00");
                    DateTime start = Convert.ToDateTime("00:00:00");
                    DateTime duration = Convert.ToDateTime("00:00:00");

                    string sqlSelectSchedule = @"UPDATE dbo.NotificationType SET start = DATEADD (year, 2001 - YEAR(start), start)
                                                 UPDATE dbo.NotificationType SET start = DATEADD (month, 01 - MONTH(start), start)
                                                 UPDATE dbo.NotificationType SET start = DATEADD (day, 01 - DAY(start), start)
                                                 SELECT idNotificationType, start, duration FROM dbo.NotificationType ORDER BY start ASC";

                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

                    SqlDataAdapter daAdaptador = new SqlDataAdapter(command);
                    DataSet dtDatos = new DataSet();
                    daAdaptador.Fill(dtDatos);

                    foreach (DataRow _dr in dtDatos.Tables[0].Rows)
                    {
                        actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());
                        start = DateTime.Parse("01-01-0001 " + DateTime.Parse(_dr[1].ToString()).ToShortTimeString());
                        duration = DateTime.Parse("01-01-0001 " + DateTime.Parse(_dr[1].ToString()).ToShortTimeString()).AddMinutes(15);

                        if(DateTime.Compare(actual, start) >= 0)
                        {
                            type = _dr[0].ToString();
                        }
                    }

                    if (type != "")
                    {
                        int i = 0;
                        string sql = @"SELECT * FROM dbo.Notification WHERE idPlataform = 2 AND idNotificationType = @type";

                        command = new SqlCommand(sql, conn);

                        daAdaptador = new SqlDataAdapter(command);
                        command.Parameters.AddWithValue("@type", type);
                        dtDatos = new DataSet();
                        daAdaptador.Fill(dtDatos);

                        var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["certificate"]));
                        push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, ConfigurationManager.AppSettings["password"]));

                        List<string> IDs = new List<string>();
                        foreach (DataRow _dr in dtDatos.Tables[0].Rows)
                        {
                            push.QueueNotification(new AppleNotification()
                                                       .ForDeviceToken(_dr[1].ToString())
                                                       .WithAlert(_dr[9].ToString() + " " + _dr[10].ToString() + " " + _dr[11].ToString())
                                                       .WithBadge(1)
                                                       .WithSound("default.caf"));
                            try
                            {
                                string deleteNotification = @"DELETE FROM dbo.Notification WHERE idNotificacion = @idNotification";
                                command = new SqlCommand(deleteNotification, conn);
                                command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                command.ExecuteScalar();
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    string updateHistorical = @"UPDATE dbo.Notification SET idUsers = 0, idDevice = 0 WHERE idNotificacion = @idNotification";
                                    command = new SqlCommand(updateHistorical, conn);
                                    command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                    command.ExecuteScalar();

                                    string deleteNotification = @"DELETE FROM dbo.Notification WHERE idNotificacion = @idNotification";
                                    command = new SqlCommand(deleteNotification, conn);
                                    command.Parameters.AddWithValue("@idNotification", _dr[0].ToString());
                                    command.ExecuteScalar();

                                }
                                catch (Exception ex2)
                                {
                                    Console.Write(ex2.Message);
                                }

                            }
                            finally
                            {

                            }
                            //i++;
                            //if (i % 100 == 0)
                            //{
                            //    push.StopAllServices();
                          //  }
                            actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());

                            if (DateTime.Compare(actual, duration) > 0)
                            {
                                break;
                            }
                        }
                        push.StopAllServices();
                        System.Threading.Thread.Sleep(5000);
                    }
                }
                    conn.Close();

            }
            catch (Exception ex)
            {
                conn.Close();
                Console.Write(ex.Message);
                push.StopAllServices();
            }
        }
コード例 #53
0
        private void Form1_Load(object sender, EventArgs e)
        {
            lbStats = listBox1;
            _tbMins = tbMins;
            _tbSecs = tbSecs;

            #if DEBUG
            tbServerHost.Text = "eluderwrx.no-ip.info";
            tbPassword.Text = "ddm_0466";
            #endif

            loadListSystems();
            loadSettings();

            _timer = new System.Timers.Timer();
            _timer.Interval = 100;
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timerElapsed);

            _timerSys = new System.Timers.Timer();
            _timerSys.Interval = 1000;
            _timerSys.Elapsed += new System.Timers.ElapsedEventHandler(timerSysElapsed);

            //Create our push services broker
            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;

            //-------------------------
            // 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!
            #if DEBUG
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProScanMobile+_Dev_Certificates.p12"));
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "$N0feaR!", false)); //Extension method
            #else
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProScanMobile+_Prod_Certificates.p12"));
            push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "$N0feaR!", true)); //Extension method
            #endif
        }