コード例 #1
0
        public void PushNotification(string deviceToken, string text, int badge, string appName)
        {
            switch (appName)
            {
            case "boostme-us":
            {
                _boostMeUSPushService.QueueNotification(NotificationFactory.Apple()
                                                        .ForDeviceToken(deviceToken)
                                                        .WithAlert(text)
                                                        .WithSound("sound.caf")
                                                        .WithBadge(badge));
            }
            break;

            case "boostme-il":
            {
                _boostMeILPushService.QueueNotification(NotificationFactory.Apple()
                                                        .ForDeviceToken(deviceToken)
                                                        .WithAlert(text)
                                                        .WithSound("sound.caf")
                                                        .WithBadge(badge));
            }
            break;

            case "tow":
            {
                _towPushService.QueueNotification(NotificationFactory.Apple()
                                                  .ForDeviceToken(deviceToken)
                                                  .WithAlert(text)
                                                  .WithSound("sound.caf")
                                                  .WithBadge(badge));
            }
            break;
            }
        }
コード例 #2
0
        /// <summary>
        /// Method used to send pushnotifications
        /// </summary>
        /// <param name="deviceID">The deviceID of the device the notification needs to be send to</param>
        /// <param name="message">The message that needs to be send</param>
        /// <returns></returns>
        public static bool SendPushNotification(string deviceID, string message)
        {
            bool status  = true;
            bool sandBox = true;

            if (count == null)
            {
                count = 1;
            }
            else
            {
                count++;
            }

            PushService push = new PushService();

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

            //Configure and start Apple APNS
            push.StartApplePushService(new ApplePushChannelSettings(!sandBox, appleCert, "brakel"));

            //Fluent construction of an iOS notification
            push.QueueNotification(NotificationFactory.Apple()
                                   .ForDeviceToken(deviceID)
                                   .WithAlert(message)
                                   .WithBadge(count));

            return(status);
        }
コード例 #3
0
        /// <summary>
        /// Method used to send pushnotifications
        /// </summary>
        /// <param name="deviceID">The deviceID of the device the notification needs to be send to</param>
        /// <param name="message">The message that needs to be send</param>
        /// <returns>Boolean indicating result status</returns>
        public static bool SendPushNotification(string deviceID, string message)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Sending push message WithBadge({0}), WithAlert({1}), ForDeviceToken({2})", _count, message, deviceID);
                using (var push = new PushService())
                {
                    //Configure and start Apple APNS
                    push.StartApplePushService(new ApplePushChannelSettings(!sandBox, appleCert, "brakel"));

                    //Fluent construction of an iOS notification
                    push.QueueNotification(NotificationFactory.Apple()
                                           .ForDeviceToken(deviceID)
                                           .WithAlert(message)
                                           .WithBadge(_count++));
                }
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }
                return(false);
            }
            return(true);
        }
コード例 #4
0
        static void Main(string[] args)
        {
            //Create our service
            PushService push = new PushService();

            //Wire up the events
            push.Events.OnDeviceSubscriptionExpired   += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            push.Events.OnChannelException            += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            push.Events.OnNotificationSendFailure     += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            push.Events.OnNotificationSent            += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
            push.Events.OnChannelCreated   += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
            push.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

            //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/myMood-prod-push-cert.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.StartApplePushService(new ApplePushChannelSettings(appleCert, "d1scov3r!"));

            //push.QueueNotification(NotificationFactory.Apple()
            //           .ForDeviceToken("14e9c79db41cf4aa205cb72e7d60cede573cfa1867f1427ddd7372ef19c29b3a")
            //           .WithAlert("Remember to send yourself a myMood report before handing back the iPad")
            //           .WithSound("default")
            //           );


            using (var csv = new CsvHelper.CsvReader(new StreamReader(typeof(Device).Assembly.GetManifestResourceStream(typeof(Device).Assembly.GetName().Name + ".devices.csv"))))
            {
                while (csv.Read())
                {
                    var device = csv.GetRecord <Device>();
                    //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(NotificationFactory.Apple()
                                           .ForDeviceToken(device.DeviceId)
                                           .WithAlert("Remember to send yourself a myMood report before handing back the iPad!")
                                           //.WithSound("default")
                                           );
                }
            }



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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #5
0
        public static void Notifica()
        {
            try
            {
                List <Entidades_EncuestasMoviles.TDI_Notificaciones> notifica = BLL_EncuestasMoviles.MngNegocioNotificaciones.ObtieneNotificaciones();

                if (notifica.Count > 0)
                {
                    foreach (var element in notifica)
                    {
                        string json = "{'IdNotificacion':'" + element.IdNotificacion.ToString() + "','TokenDispositivo':'" + element.TokenDispositivo + "','Periodo':'" + element.Periodo.ToString() + "','Mensaje':'" + element.Mensaje.ToString() + "','IdEncuesta':'" + element.IdEncuesta.ToString() + "','Telefono':'" + element.Telefono.ToString() + "','idDispo':'" + element.IdDispo.ToString() + "','IdEnvio':'" + element.IdEnvio.ToString() + "'}";

                        PushService PushClient = new PushService();

                        PushClient.Events.OnDeviceSubscriptionExpired   += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
                        PushClient.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
                        PushClient.Events.OnChannelException            += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
                        PushClient.Events.OnNotificationSendFailure     += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
                        PushClient.Events.OnNotificationSent            += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
                        PushClient.Events.OnChannelCreated   += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
                        PushClient.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

                        //PushClient.Events.OnNotificationSent += HandleOnNotificationSent;
                        PushClient.StartGoogleCloudMessagingPushService(
                            new GcmPushChannelSettings("248326017313", "AIzaSyBl8zK7NlLAFc0AkWtuJgsEt3VlXGNARu4", "encuestas.moviles"));
                        //idNotificacion, TokenDispositivo, Periodo, Mensaje, idEncuesta
                        //string deviceregistrationid = DeviceRegistrationID as string;
                        PushClient.QueueNotification(NotificationFactory.AndroidGcm()
                                                     .ForDeviceRegistrationId(element.TokenDispositivo)
                                                     .WithCollapseKey("NONE")
                                                     .WithJson(json)
                                                     .WithTag(element.IdNotificacion + "|" + element.TokenDispositivo + "|" + element.Periodo + "|" + element.Mensaje + "|" + element.IdEncuesta + "|" + element.Telefono + "|" + element.IdDispo));

                        Console.WriteLine("Waiting for Queue to Finish...");
                    }
                }
                else
                {
                    Console.WriteLine("NO SE REGISTRO NINGUN RESULTADO " + DateTime.Now);
                }
            }
            catch (Exception ms)
            {
                Console.WriteLine("ERROR " + ms.Message);
            }
            finally
            {
            }
        }
コード例 #6
0
        void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                THE_PUSTRAN objTran = new THE_PUSTRAN();
                objTran.DescTran          = "Se ha enviado desde el global asax";
                objTran.FechaCreaEncuesta = DateTime.Now;
                MngNegocioPushTran.GuardarTranPush(objTran);


                List <TDI_Notificaciones> notifica = MngNegocioNotificaciones.ObtieneNotificaciones();


                objTran.DescTran = "Hay " + notifica.Count + " pendientes por enviar";
                MngNegocioPushTran.GuardarTranPush(objTran);



                if (notifica.Count > 0)
                {
                    foreach (TDI_Notificaciones element in notifica)
                    {
                        PushService PushClient = new PushService();

                        PushClient.Events.OnDeviceSubscriptionExpired   += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
                        PushClient.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
                        PushClient.Events.OnChannelException            += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
                        PushClient.Events.OnNotificationSendFailure     += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
                        PushClient.Events.OnNotificationSent            += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
                        PushClient.Events.OnChannelCreated   += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
                        PushClient.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

                        //PushClient.Events.OnNotificationSent += HandleOnNotificationSent;
                        PushClient.StartGoogleCloudMessagingPushService(
                            new GcmPushChannelSettings("248326017313", "AIzaSyBl8zK7NlLAFc0AkWtuJgsEt3VlXGNARu4", "encuestas.moviles"));

                        //PushClient.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings("248326017313", "AIzaSyBl8zK7NlLAFc0AkWtuJgsEt3VlXGNARu4", "encuestas.moviles"));

                        //        PushClient.QueueNotification(NotificationFactory.AndroidGcm()
                        //.ForDeviceRegistrationId("APA91bFKLIddkts8DxU-qlLdrlOw3fhrIiPiWHIBsNRv8f0HosWF_e45WeFhjLYaEp-CaHnyR5sh9FLXcO1T-U-8-Pgkwy6YoylF9_NusAAbqHqme0F7mviyh1mthrn1hqP_PytyzpxSpir6pK96AIWa-CC8t5humg")
                        //.WithCollapseKey("NONE")
                        //.WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"7\"}"));


                        PushClient.QueueNotification(NotificationFactory.AndroidGcm()
                                                     .ForDeviceRegistrationId(element.TokenDispositivo.ToString())
                                                     .WithCollapseKey("NONE")
                                                     .WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"7\"}"));
                        Console.WriteLine("Waiting for Queue to Finish...");

                        PushClient.StopAllServices(true);
                    }
                }
                else
                {
                    Trace.WriteLine("El PROCESO NO ARROJO NINGUN RESULTADO");
                }
            }
            catch (Exception ms)
            {
                THE_PUSTRAN objTran = new THE_PUSTRAN();
                objTran.DescTran          = "OCURRIO ERROR: " + ms.Message;
                objTran.FechaCreaEncuesta = DateTime.Now;
                MngNegocioPushTran.GuardarTranPush(objTran);
                Console.WriteLine("OCURRIO ERROR: " + ms.Message);
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: ngoossens/PushSharp
        static void Main(string[] args)
        {
            //Create our service
            PushService push = new PushService();

            //Wire up the events
            push.Events.OnDeviceSubscriptionExpired += new Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            push.Events.OnDeviceSubscriptionIdChanged += new Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            push.Events.OnChannelException += new Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            push.Events.OnNotificationSendFailure += new Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            push.Events.OnNotificationSent += new Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
            push.Events.OnChannelCreated += new Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
            push.Events.OnChannelDestroyed += new Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

            //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.StartApplePushService(new ApplePushChannelSettings(appleCert, "pushsharp"));

            //Configure and start Android GCM
            //IMPORTANT: The SENDER_ID is your Google API Console App Project ID.
            //  Be sure to get the right Project ID from your Google APIs Console.  It's not the named project ID that appears in the Overview,
            //  but instead the numeric project id in the url: eg: https://code.google.com/apis/console/?pli=1#project:785671162406:overview
            //  where 785671162406 is the project id, which is the SENDER_ID to use!
            push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings("785671162406", "AIzaSyC2PZNXQDVaUpZGmtsF_Vp8tHtIABVjazI", "com.pushsharp.test"));

            //Configure and start Windows Phone Notifications
            push.StartWindowsPhonePushService(new WindowsPhonePushChannelSettings());

            //Configure and start Windows Notifications
            push.StartWindowsPushService(new WindowsPushChannelSettings("677AltusApps.PushSharpTest",
                "ms-app://s-1-15-2-397915024-884168245-3562497613-3307968140-4074292843-797285123-433377759", "ei5Lott1HEbbZBv2wGDTUsrCjU++Pj8Z"));

            //Fluent construction of a Windows Toast Notification
            push.QueueNotification(NotificationFactory.Windows().Toast().AsToastText01("This is a test").ForChannelUri("YOUR_CHANNEL_URI_HERE"));

            //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(NotificationFactory.WindowsPhone().Toast()
                .ForEndpointUri(new Uri("http://sn1.notify.live.net/throttledthirdparty/01.00/AAFCoNoCXidwRpn5NOxvwSxPAgAAAAADAgAAAAQUZm52OkJCMjg1QTg1QkZDMkUxREQ"))
                .ForOSVersion(WindowsPhone.WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
                .WithBatchingInterval(WindowsPhone.BatchingInterval.Immediate)
                .WithNavigatePath("/MainPage.xaml")
                .WithText1("PushSharp")
                .WithText2("This is a Toast"));

            //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(NotificationFactory.Apple()
                .ForDeviceToken("1071737321559691b28fffa1aa4c8259d970fe0fc496794ad0486552fc9ec3db")
                .WithAlert("1 Alert Text!")
                .WithSound("default")
                .WithBadge(7));

            //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(NotificationFactory.AndroidGcm()
                .ForDeviceRegistrationId("APA91bG7J-cZjkURrqi58cEd5ain6hzi4i06T0zg9eM2kQAprV-fslFiq60hnBUVlnJPlPV-4K7X39aHIe55of8fJugEuYMyAZSUbmDyima5ZTC7hn4euQ0Yflj2wMeTxnyMOZPuwTLuYNiJ6EREeI9qJuJZH9Zu9g")
                .WithCollapseKey("NONE")
                .WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"7\"}"));

            push.QueueNotification(NotificationFactory.Windows()
                .Toast()
                .ForChannelUri("https://bn1.notify.windows.com/?token=AgUAAACC2u7flXAmaevcggrLenaSdExjVfIHvr6KSZrg0KeuGrcz877rPJprPL9bEuQH%2bacmmm%2beUyXNXEM8oRNit%2bzPoigksDOq6bIFyV3XGmhUmXadysLokl5rlmTscvHGAbs%3d")
                .WithRequestForStatus(true)
                .AsToastText01("This is a test!"));

            //Configure and start Blackberry Push
            push.StartBlackberryPushService(new BlackberryPushChannelSettings(
              "https://cpXXXX.pushapi.eval.blackberry.com", "xxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxx"));

            //Fluent construction of an Blackberry Notification
            push.QueueNotification(NotificationFactory.Blackberry()
                .ForDeviceRegistrationId("xxxxxxxx")
                .WithData("This is a test!"));

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

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #8
0
        public List <RemoteNotificationResult> Send()
        {
            foreach (RemoteNotification notif in m_notifications)
            {
                PlatformType platformType = PlatformConverter.FromDeviceType(notif.DeviceType);
                switch (platformType)
                {
                case PlatformType.Apple:
                    EnsureiOS();
                    AppleNotification n = NotificationFactory.Apple();
                    n.DeviceToken = notif.DeviceToken;
                    n.Payload     = new AppleNotificationPayload();
                    if (!string.IsNullOrEmpty(notif.Message))
                    {
                        n.Payload.Alert = new AppleNotificationAlert()
                        {
                            Body = notif.Message
                        }
                    }
                    ;
                    if (!string.IsNullOrEmpty(notif.Sound))
                    {
                        n.Payload.Sound = notif.Sound;
                    }
                    if (!string.IsNullOrEmpty(notif.Action) && notif.Action.Trim().Length > 0)
                    {
                        n.Payload.AddCustom("a", notif.Action);
                        if (notif.Parameters != null && notif.Parameters.Names.Count > 0)
                        {
                            n.Payload.AddCustom("p", notif.Parameters.ToJObject());
                        }
                    }
                    if (!string.IsNullOrEmpty(notif.Badge))
                    {
                        int badgeInt;
                        if (int.TryParse(notif.Badge, out badgeInt))
                        {
                            n.Payload.Badge = badgeInt;
                        }
                        else if (notif.Badge == "!")
                        {
                            n.Payload.Badge = -1;
                        }
                    }
                    if (notif.ExecutionTime != 0)
                    {
                        n.Payload.ContentAvailable = 1;
                    }

                    Service.QueueNotification(n);
                    break;

                case PlatformType.AndroidGcm:
                    EnsureAndroid();
                    GcmNotification g = NotificationFactory.Google();
                    g.RegistrationIds.Add(notif.DeviceToken);
                    g.JsonData = string.Format("{{ \"payload\":\"{0}\",\"action\":\"{1}\",\"parameters\": {2} ,\"executiontime\": {3} ,\"priority\": {4} }}"
                                               , notif.Message, notif.Action, notif.Parameters.ToJson(), notif.ExecutionTime.ToString(), notif.Delivery.Priority);
                    g.CollapseKey = "NONE";
                    Service.QueueNotification(g);
                    break;

                case PlatformType.WindowsPhone:
                    EnsureWindows();
                    WindowsNotification w = NotificationFactory.Windows();
                    w.ChannelUri    = notif.DeviceToken;
                    w.Message       = notif.Message;
                    w.Title         = notif.Title;
                    w.ImageUri      = notif.Icon;
                    w.Badge         = notif.Badge;
                    w.Sound         = notif.Sound;
                    w.Action        = notif.Action;
                    w.Parameters    = notif.Parameters;
                    w.ExecutionTime = notif.ExecutionTime;

                    Service.QueueNotification(w);
                    break;

                default:
                    RemoteNotificationResult result = RemoteNotificationResult.ForDevice(notif.DeviceType, notif.DeviceToken);
                    result.ErrorCode        = INVALID_DEVICE_TYPE;
                    result.ErrorDescription = GetErrorDescription(INVALID_DEVICE_TYPE);
                    SetResult(result);
                    break;
                }
            }

            Service.StopAllServices(true);
            return(m_results);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: vpdsouza/PushSharp
        static void Main(string[] args)
        {
            //Create our service
            PushService push = new PushService();

            //Wire up the events
            push.Events.OnDeviceSubscriptionExpired   += new Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            push.Events.OnDeviceSubscriptionIdChanged += new Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            push.Events.OnChannelException            += new Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            push.Events.OnNotificationSendFailure     += new Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            push.Events.OnNotificationSent            += new Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
            push.Events.OnChannelCreated   += new Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
            push.Events.OnChannelDestroyed += new Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

            //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.StartApplePushService(new ApplePushChannelSettings(appleCert, "pushsharp"));

            //Configure and start Android GCM
            //IMPORTANT: The SENDER_ID is your Google API Console App Project ID.
            //  Be sure to get the right Project ID from your Google APIs Console.  It's not the named project ID that appears in the Overview,
            //  but instead the numeric project id in the url: eg: https://code.google.com/apis/console/?pli=1#project:785671162406:overview
            //  where 785671162406 is the project id, which is the SENDER_ID to use!
            push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings("785671162406", "AIzaSyC2PZNXQDVaUpZGmtsF_Vp8tHtIABVjazI", "com.pushsharp.test"));

            //Configure and start Windows Phone Notifications
            push.StartWindowsPhonePushService(new WindowsPhonePushChannelSettings());

            //Configure and start Windows Notifications
            push.StartWindowsPushService(new WindowsPushChannelSettings("677AltusApps.PushSharpTest",
                                                                        "ms-app://s-1-15-2-397915024-884168245-3562497613-3307968140-4074292843-797285123-433377759", "ei5Lott1HEbbZBv2wGDTUsrCjU++Pj8Z"));

            //Fluent construction of a Windows Toast Notification
            push.QueueNotification(NotificationFactory.Windows().Toast().AsToastText01("This is a test").ForChannelUri("YOUR_CHANNEL_URI_HERE"));

            //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(NotificationFactory.WindowsPhone().Toast()
                                   .ForEndpointUri(new Uri("http://sn1.notify.live.net/throttledthirdparty/01.00/AAFCoNoCXidwRpn5NOxvwSxPAgAAAAADAgAAAAQUZm52OkJCMjg1QTg1QkZDMkUxREQ"))
                                   .ForOSVersion(WindowsPhone.WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
                                   .WithBatchingInterval(WindowsPhone.BatchingInterval.Immediate)
                                   .WithNavigatePath("/MainPage.xaml")
                                   .WithText1("PushSharp")
                                   .WithText2("This is a Toast"));

            //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(NotificationFactory.Apple()
                                   .ForDeviceToken("1071737321559691b28fffa1aa4c8259d970fe0fc496794ad0486552fc9ec3db")
                                   .WithAlert("1 Alert Text!")
                                   .WithSound("default")
                                   .WithBadge(7));

            //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(NotificationFactory.AndroidGcm()
                                   .ForDeviceRegistrationId("APA91bG7J-cZjkURrqi58cEd5ain6hzi4i06T0zg9eM2kQAprV-fslFiq60hnBUVlnJPlPV-4K7X39aHIe55of8fJugEuYMyAZSUbmDyima5ZTC7hn4euQ0Yflj2wMeTxnyMOZPuwTLuYNiJ6EREeI9qJuJZH9Zu9g")
                                   .WithCollapseKey("NONE")
                                   .WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"7\"}"));

            push.QueueNotification(NotificationFactory.Windows()
                                   .Toast()
                                   .ForChannelUri("https://bn1.notify.windows.com/?token=AgUAAACC2u7flXAmaevcggrLenaSdExjVfIHvr6KSZrg0KeuGrcz877rPJprPL9bEuQH%2bacmmm%2beUyXNXEM8oRNit%2bzPoigksDOq6bIFyV3XGmhUmXadysLokl5rlmTscvHGAbs%3d")
                                   .WithRequestForStatus(true)
                                   .AsToastText01("This is a test!"));

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

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #10
0
        public void CheckAndSendNotifications()
        {
            MoodServer server = this.db.Get <MoodServer>().Where(s => s.Name.Equals(Configuration.WebConfiguration.ServerName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (server != null && server.CanPushClientNotifcations)
            {
                //todo check if server can send push
                var now           = DateTime.UtcNow;
                var notifications = this.db.Get <PushNotification>().Where(p => p.Sent == false && p.SendDate <= now).OrderBy(p => p.SendDate);


                if (notifications.Any())
                {
                    //Create our service
                    PushService push = new PushService();

                    //Wire up the events
                    push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
                    push.Events.OnNotificationSent        += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);


                    //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(Configuration.WebConfiguration.APNSCertificatePath);


                    var appleCert = new X509Certificate2(File.ReadAllBytes(Configuration.WebConfiguration.APNSCertificatePath), "d1scov3r!", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
                    //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.StartApplePushService(new ApplePushChannelSettings(appleCert, "d1scov3r!"));
                    push.StartApplePushService(new ApplePushChannelSettings(appleCert));
                    foreach (var notification in notifications)
                    {
                        this.logger.Info(this.GetType(), string.Format("Sending APNS notification - {0}", notification.Message));
                        //set sent first so doesn't repeat if goes wrong
                        notification.Sent = true;


                        var recipients = this.db.Get <Responder>().Where(r => r.Event.Id == notification.Event.Id);
                        foreach (var recipient in recipients)
                        {
                            //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(NotificationFactory.Apple()
                                                   .ForDeviceToken(recipient.DeviceId)
                                                   .WithAlert(notification.Message)
                                                   .WithSound(notification.PlaySound ? "default" : "")
                                                   );
                        }
                    }
                    this.db.SaveChanges();
                    //Stop and wait for the queues to drains
                    push.StopAllServices(true);
                }
            }
        }