コード例 #1
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);
        }
コード例 #2
0
        private static void PushAndroid(string mensaje, string deviceId)
        {
            //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;

            //@"{""alert"":""Hello World!"",""badge"":7,""sound"":""sound.caf""}")
            //string cmd = string.Format("{\"alert\":\"{0}\",\"badge\":7,\"sound\":\"sound.caf\"}", mensaje);
            string cmd = string.Format("{\"alert\":\"{0}\",\"badge\":7}", mensaje);

            push.RegisterGcmService(new GcmPushChannelSettings(appkey));
            push.QueueNotification(
                new GcmNotification()
                .ForDeviceRegistrationId(deviceId)
                .WithJson(cmd));

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
コード例 #3
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();
        }
コード例 #4
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();
        }
コード例 #5
0
ファイル: AppleTests.cs プロジェクト: Calsy/PushSharp
        public void Setup()
        {
            Log.Level = LogLevel.Info;

            appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../Resources/PushSharp.Apns.Sandbox.p12"));
            broker = new PushBroker();
        }
コード例 #6
0
ファイル: UsersWS.cs プロジェクト: meir2017/CarePet
    [WebMethod]// נסיוני
    public void RunPushNotification(int num)
    {
        string myReg;

        if (num > 5)
        {
            myReg = "dyow6Hnx4rw:APA91bGmmQvZRd2Eu3l2kaBMixIDdtau8qWfKi-JQUixrUhMvmQ51lDnRkq31E-ZzD94BSNPmkhSaU0WlrFGQL-p5_olurBlB93e0PKTTyTLJz2fBZ12kHS3tiONPwruH9dL7Sy0SJs7";
        }
        else
        {
            myReg = "f537ZMaiTAo:APA91bHnzPdDkUu665pOyoKNbo26anQftYIPSrJ6o0JejgsMgWf2D3k1KzVbgDEtGJOCqBVHRUAU8hGJhb8Dy4_ZMT9dCxcX3JLiVPwBFkQE9ZN4GvSL0iG0EUvxHp8lvxKZIspTywnH";
        }

        //   string myReg1= "f_y2JgBx59E:APA91bG_ziqfyssypiiA7HEnZVQonnGaKRvyw7SQrgj-fCUauPFDZfxfBhyNss7SWu4ascVRc8JEb2xtzLMLxtrNDEsfkeGlGhSB9iPQoUWZEL2Nh9aQIa4KR0g_dLAWtteVGPeFeDH7";
        var push = new PushBroker();


        push.OnNotificationSent += NotificationSent;
        //key
        push.RegisterGcmService(new GcmPushChannelSettings("AAAAD_Zs3Og:APA91bF10XYTd21DUbbipM0UObV-RhJxHJtSe1egPSCs0wcT_AoxSJD8vRd4PuATqh48W8f9_goVh6KFBBavG2KUPxcfOf1aEUTZQq5mzeLSvAP77RuJWK4zL_usQud9Mr1Jo0MYdI0l"));



        string message = "meir--:)   . " + num;

        //reng uesr
        push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(myReg)
                               .WithJson("{\"message\": \" " + message + " \", \"title\": \" my title\", \"msgcnt\": \"1\", \"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"Pistol.mp3\"}"));


        push.StopAllServices();
    }
コード例 #7
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();
        }
コード例 #8
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();
        }
コード例 #9
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);
            }
        }
コード例 #10
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);
         }
     }
 }
コード例 #11
0
ファイル: PushService.cs プロジェクト: fishonline/API-1
        /// <summary>
        /// Initializes a new instance of the <see cref="PushService" /> class.
        /// </summary>
        /// <param name="googleGcmApiKey"> The google api key</param>
        /// <param name="appleCertPwd"> The Api certificate password</param>
        /// <param name="outputPath">The output path</param>
        /// <param name="loggerService"> The logger service</param>
        /// <param name="mapperFactory">the mapper factory</param>
        /// <param name="notificationLogRepository">The notification log repository</param>
        public PushService(string googleGcmApiKey, string appleCertPwd, string outputPath, ILoggerService loggerService, IMapperFactory mapperFactory, IRepository<NotificationLog> notificationLogRepository)
        {
            this.loggerService = loggerService;
            this.mapperFactory = mapperFactory;
            this.notificationLogRepository = notificationLogRepository;

            this.pushBroker = new PushBroker();
            try
            {
                this.pushBroker.RegisterGcmService(new GcmPushChannelSettings(googleGcmApiKey));
            }
            catch (Exception ex)
            {
                this.loggerService.LogException("Register Android notification service" + ex.Message);
            }

            var appleCert = File.ReadAllBytes(outputPath);

            try
            {
                this.pushBroker.RegisterAppleService(new ApplePushChannelSettings(appleCert, appleCertPwd));
            }
            catch (Exception ex)
            {
                this.loggerService.LogException("Register iOS notification service" + ex.Message);
            }
        }
コード例 #12
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);
        }
コード例 #13
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;
        }
コード例 #14
0
ファイル: Push.cs プロジェクト: cheahjs/wf-weblog-deathsnacks
        /// <summary>
        /// Pushes a GCM data payload to a list of <paramref name="ids"/>.
        /// </summary>
        /// <param name="ids">List of GCM ids</param>
        /// <param name="topic">Unused topic parameter</param>
        /// <param name="ttl">Time to live</param>
        /// <param name="data">Data payload to send</param>
        /// <param name="collapse">Collapse key to use</param>
        public static void PushDataNotification(List <String> ids, string topic, int ttl, Dictionary <string, string> data,
                                                string collapse = "alerts")
        {
            Log.InfoFormat("Starting push. No. of ids: {0}.", ids.Count);
            var push = new PushBroker();

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

            push.RegisterGcmService(new GcmPushChannelSettings(Program.Config.GcmSenderId, Program.Config.GcmKey,
                                                               Program.Config.GcmPackage));
            //push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("/topics/" + topic).WithCollapseKey(collapse).WithData(data));
            for (var i = 0; i < Math.Ceiling((double)ids.Count / 999); i++)
            {
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(ids.Page(999, i))
                                       .WithCollapseKey(collapse)
                                       /*.WithTimeToLive(ttl)*/
                                       .WithData(data));
            }
            push.StopAllServices();
            Log.InfoFormat("Queues have drained.");
        }
コード例 #15
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"));
        }
コード例 #16
0
        static void Main(string[] args)
        {
            var listeningOn = args.Length == 0 ? "http://*:1338/" : args[0];

            var pushBroker = new PushBroker();

            pushBroker.OnNotificationSent += (sender, notification) =>
            {
                Console.Write("OK");
            };
            pushBroker.OnNotificationFailed += (sender, notification, error) =>
            {
                Console.Write(error.Message);
            };
            pushBroker.OnChannelException += (sender, channel, error) =>
            {
                Console.Write(error.Message);
            };

            var appHost = new Program.AppHost(pushBroker)
                          .Init()
                          .Start(listeningOn);

            Console.WriteLine("AppHost Created at {0}, listening on {1}",
                              DateTime.Now, listeningOn);

            Console.ReadKey();
        }
コード例 #17
0
        private void notifyAllSubscribers(Town town, string senderName)
        {
            //TODO remove the current user
            var registrationIds = this.unitOfWork.Subscriptions
                                  .Filter(s => s.TownID == town.TownID, new string[] { "User" })
                                  .Select(s => s.User.GCMClientToken);

            if (registrationIds.Count() > 0)
            {
                //Create our push services broker
                var push = new PushBroker();

                push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyDZwSkJL1KowOSLWD9dgbJaY1qsqMTLsc8"));

                var obj = new
                {
                    msg        = senderName + " uploaded a new photo.",
                    townId     = town.TownID,
                    townName   = town.Name,
                    senderName = senderName
                };

                var serializer = new JavaScriptSerializer();
                var json       = serializer.Serialize(obj);

                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(registrationIds)
                                       .WithJson(json));

                //Stop and wait for the queues to drains
                push.StopAllServices();
            }
        }
コード例 #18
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!";
 }
コード例 #19
0
        public bool Send(WindowsPhoneApiNotificationPayLoad payLoad)
        {
            HookEvents(PushBroker);

            try
            {
                PushBroker.RegisterService <WindowsPhoneNotification>(new WindowsPhonePushService());

                var notification = new WindowsPhoneToastNotification()
                                   .ForEndpointUri(new Uri(payLoad.Token))
                                   .ForOSVersion(WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
                                   .WithBatchingInterval(BatchingInterval.Immediate)
                                   .WithNavigatePath(payLoad.NavigationPath)
                                   .WithText1(payLoad.Message)
                                   .WithText2(payLoad.TextMessage2);

                PushBroker.QueueNotification(notification);
            }
            finally
            {
                StopBroker();
            }

            return(true);
        }
コード例 #20
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();
        }
コード例 #21
0
        /// <summary>
        /// Initilizes the push broker instance and creates a new DbContext, checks for both if there is no instance, if so creates a new one.
        /// </summary>
        private void InitBroker()
        {
            _broker = _broker ?? new PushBroker();
            _databaseContext = _databaseContext ?? new PushSharpDatabaseContext();

            // subscribe to the push brokers API events
            _broker.OnNotificationSent += broker_OnNotificationSent;
            _broker.OnNotificationFailed += broker_OnNotificationFailed;
            _broker.OnServiceException += broker_OnServiceException;
            _broker.OnNotificationRequeue += broker_OnNotificationRequeue;
            _broker.OnDeviceSubscriptionExpired += broker_OnDeviceSubscriptionExpired;
            _broker.OnDeviceSubscriptionChanged += broker_OnDeviceSubscriptionChanged;
            _broker.OnChannelCreated += broker_OnChannelCreated;
            _broker.OnChannelDestroyed += broker_OnChannelDestroyed;
            _broker.OnChannelException += broker_OnChannelException;

            _broker.RegisterGcmService(new GcmPushChannelSettings(_googlePushNotificationAuthToken));

            // NOTE: in this case we are skipping apple stuff, 
            // if you wish to use apple iOS notifications uncomment below and use the proper cert i.e. dev/prod
            // _broker.RegisterAppleService(new ApplePushChannelSettings(false, _applePushNotificationCertificate, "Password"));

            _broker.RegisterWindowsService(_windowsPushNotificationChannelSettings);

            On(DisplayMessage, "Push Broker successfully initialized.");
        }
コード例 #22
0
    /// <summary>
    /// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.Panel"/> class.
    /// </summary>
    public SendPushNotificationControl()
    {
        string root     = HttpContext.Current.Server.MapPath("~/certificate");
        string certName = "metafitness.p12";

        byte[] cert = File.ReadAllBytes(Path.Combine(root, certName));

        pushService = new PushBroker();
        //ApplePushChannelSettings settings = new ApplePushChannelSettings(false, cert, "ilovebbq");
        //pushService.StartApplePushService(settings);

        //Label = new Label { ID = "lblPushMessage", ClientIDMode = ClientIDMode.Static, Text = "Test" };
        Button = new Button {
            ID = "btnPushSend", ClientIDMode = ClientIDMode.Static, Text = "Send"
        };
        Button.Click += new EventHandler(ButtonOnClick);

        GridView = new GridView {
            ID = "grdvPushResult", ClientIDMode = ClientIDMode.Static, AutoGenerateColumns = false, Width = 300, GridLines = GridLines.Both, ShowHeaderWhenEmpty = true
        };
        GridView.Columns.Add(new BoundField
        {
            HeaderText = "Message",
            DataField  = "Message",
            HtmlEncode = true
        });
        GridView.Columns.Add(new BoundField
        {
            HeaderText       = "SendDate",
            DataField        = "SendDate",
            HtmlEncode       = false,
            DataFormatString = "{0:MM-dd-yyyy}"
        });
    }
コード例 #23
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();
 }
コード例 #24
0
    public NotificationManager(String compName)
    {
        _push = new PushBroker();
        _push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAutUa56XnPXuJaPtQk7dATEpvkzu7p1aE"));

        _compName = compName;
    }
コード例 #25
0
        /// <summary>
        /// Initilizes the push broker instance and creates a new DbContext, checks for both if there is no instance, if so creates a new one.
        /// </summary>
        private void InitBroker()
        {
            _broker          = _broker ?? new PushBroker();
            _databaseContext = _databaseContext ?? new PushSharpDatabaseContext();

            // subscribe to the push brokers API events
            _broker.OnNotificationSent          += broker_OnNotificationSent;
            _broker.OnNotificationFailed        += broker_OnNotificationFailed;
            _broker.OnServiceException          += broker_OnServiceException;
            _broker.OnNotificationRequeue       += broker_OnNotificationRequeue;
            _broker.OnDeviceSubscriptionExpired += broker_OnDeviceSubscriptionExpired;
            _broker.OnDeviceSubscriptionChanged += broker_OnDeviceSubscriptionChanged;
            _broker.OnChannelCreated            += broker_OnChannelCreated;
            _broker.OnChannelDestroyed          += broker_OnChannelDestroyed;
            _broker.OnChannelException          += broker_OnChannelException;

            _broker.RegisterGcmService(new GcmPushChannelSettings(_googlePushNotificationAuthToken));

            // NOTE: in this case we are skipping apple stuff,
            // if you wish to use apple iOS notifications uncomment below and use the proper cert i.e. dev/prod
            // _broker.RegisterAppleService(new ApplePushChannelSettings(false, _applePushNotificationCertificate, "Password"));

            _broker.RegisterWindowsService(_windowsPushNotificationChannelSettings);

            On(DisplayMessage, "Push Broker successfully initialized.");
        }
コード例 #26
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)

                                       );
            }
        }
コード例 #27
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);
        }
コード例 #28
0
    public NotificationManager(String compName)
    {
        _push = new PushBroker();
        _push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAutUa56XnPXuJaPtQk7dATEpvkzu7p1aE"));

        _compName = compName;
    }
コード例 #29
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();
        }
コード例 #30
0
ファイル: AppPushDemo.cs プロジェクト: yellowjime/Examples
        public AppPushDemo()
        {
            logger = LogManager.GetCurrentClassLogger();

            push = new PushBroker();

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

            //needSms = Convert.ToBoolean(ConfigurationManager.AppSettings["SMSEnabled"]);
            needApplePush      = true;
            needAndroidPush    = true;
            needBlackBerryPush = true;

            string pushEnabled = ConfigurationManager.AppSettings["ApplePushEnabled"];

            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needApplePush);
            }

            pushEnabled = ConfigurationManager.AppSettings["AndroidPushEnabled"];
            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needAndroidPush);
            }

            pushEnabled = ConfigurationManager.AppSettings["BlackBerryPushEnabled"];
            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needBlackBerryPush);
            }

            appleTargetDeviceToken = ConfigurationManager.AppSettings["AppleTargetDeviceToken"];
            if (String.IsNullOrEmpty(appleTargetDeviceToken))
            {
                needApplePush = false;
                Console.WriteLine("Apple Push is disabled because AppleTargetDeviceToken is not set in app config!");
            }

            androidTargetDeviceToken = ConfigurationManager.AppSettings["AndroidTargetDeviceToken"];
            if (String.IsNullOrEmpty(androidTargetDeviceToken))
            {
                needAndroidPush = false;
                Console.WriteLine("Android Push is disabled because AndroidTargetDeviceToken is not set in app config!");
            }


            CreateApplePushSettings();
            CreateAndroidPushSettings();
            CreateBlackBerryPushSettings();
        }
コード例 #31
0
ファイル: AppPushDemo.cs プロジェクト: kimx/Examples
        public AppPushDemo()
        {
            logger = LogManager.GetCurrentClassLogger();

            push = new PushBroker();

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

            //needSms = Convert.ToBoolean(ConfigurationManager.AppSettings["SMSEnabled"]);
            needApplePush = true;
            needAndroidPush = true;
            needBlackBerryPush = true;

            string pushEnabled = ConfigurationManager.AppSettings["ApplePushEnabled"];
            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needApplePush);
            }

            pushEnabled = ConfigurationManager.AppSettings["AndroidPushEnabled"];
            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needAndroidPush);
            }

            pushEnabled = ConfigurationManager.AppSettings["BlackBerryPushEnabled"];
            if (pushEnabled != null)
            {
                Boolean.TryParse(pushEnabled, out needBlackBerryPush);
            }

            appleTargetDeviceToken = ConfigurationManager.AppSettings["AppleTargetDeviceToken"];
            if (String.IsNullOrEmpty(appleTargetDeviceToken))
            {
                needApplePush = false;
                Console.WriteLine("Apple Push is disabled because AppleTargetDeviceToken is not set in app config!");
            }

            androidTargetDeviceToken = ConfigurationManager.AppSettings["AndroidTargetDeviceToken"];
            if (String.IsNullOrEmpty(androidTargetDeviceToken))
            {
                needAndroidPush = false;
                Console.WriteLine("Android Push is disabled because AndroidTargetDeviceToken is not set in app config!");
            }
              

            CreateApplePushSettings();
            CreateAndroidPushSettings();
            CreateBlackBerryPushSettings();
        }
コード例 #32
0
        /// <summary>
        /// Initializes Google Cloud Messaging (GCM) Service
        /// </summary>
        public static void InitGoogleCloudMessagingService()
        {
            push = new PushBroker();
            string googleApiKey = FWUtils.ConfigUtils.GetAppSettings().Project.GoogleApiServerKey;

            //Registering the GCM Service and sending an Android Notification
            push.RegisterGcmService(new GcmPushChannelSettings(googleApiKey));
            push.OnServiceException          += push_OnServiceException;
            push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
        }
コード例 #33
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();
        }
コード例 #34
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();
        }
コード例 #35
0
 private void initialize()
 {
     if (this.pushBrokerProduction == null)
     {
         this.pushBrokerProduction = this.createPushBrokerObject(true);
     }
     if (this.pushBrokerSandbox == null)
     {
         this.pushBrokerSandbox = this.createPushBrokerObject(false);
     }
 }
コード例 #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PushNotificationEngine"/> class.
        /// </summary>
        /// <param name="deviceRegistryDataRepository">The device registry data repository.</param>
        /// <param name="notificationLogDataRepository">The notification log data repository.</param>
        public PushNotificationEngine(IDeviceRegistryDataRepository deviceRegistryDataRepository,
            INotificationLogDataRepository notificationLogDataRepository)
        {
            this._deviceRegistryDataRepository = deviceRegistryDataRepository;
            this._notificationLogDataRepository = notificationLogDataRepository;

            this._broker = new PushBroker();
            this._random = new Random();

            RegisterEvents();
        }
コード例 #37
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PushNotificationEngine"/> class.
        /// </summary>
        /// <param name="deviceRegistryDataRepository">The device registry data repository.</param>
        /// <param name="notificationLogDataRepository">The notification log data repository.</param>
        public PushNotificationEngine(IDeviceRegistryDataRepository deviceRegistryDataRepository,
                                      INotificationLogDataRepository notificationLogDataRepository)
        {
            this._deviceRegistryDataRepository  = deviceRegistryDataRepository;
            this._notificationLogDataRepository = notificationLogDataRepository;

            this._broker = new PushBroker();
            this._random = new Random();

            RegisterEvents();
        }
コード例 #38
0
 private void SetEvents(PushBroker broker)
 {
     broker.OnNotificationSent          += NotificationSent;
     broker.OnNotificationFailed        += NotificationFailed;
     broker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
     broker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
     broker.OnChannelException          += ChannelException;
     broker.OnServiceException          += ServiceException;
     broker.OnChannelCreated            += ChannelCreated;
     broker.OnChannelDestroyed          += ChannelDestroyed;
 }
コード例 #39
0
ファイル: Pusher.cs プロジェクト: Ontropix/whowhat
        public Pusher()
        {
            broker = new PushBroker();

            broker.OnChannelException += BrokerOnOnChannelException;
            broker.OnNotificationFailed += BrokerOnOnNotificationFailed;
            broker.OnChannelCreated += BrokerOnOnChannelCreated;
            broker.OnNotificationSent += BrokerOnOnNotificationSent;

            broker.RegisterWindowsPhoneService();
        }
コード例 #40
0
        public NotiPusher(NotiConfig config, string basePath)
        {
            pushBroker = new PushBroker();
            pushBroker.OnChannelException          += OnChannelException;
            pushBroker.OnDeviceSubscriptionChanged += OnDeviceSubscriptionChanged;
            pushBroker.OnDeviceSubscriptionExpired += OnDeviceSubscriptionExpired;
            pushBroker.OnNotificationFailed        += OnNotificationFailed;
            pushBroker.OnServiceException          += OnServiceException;

            ConfigureIos(config, basePath);
            ConfigureAndriod(config);
        }
コード例 #41
0
 public static void Restart()
 {
     lock (_lock)
     {
         if (_broker != null)
         {
             _broker.StopAllServices(true);
             PushBo.Instance.ActiveChannels = null;
             _broker = CreateBroker();
         }
     }
 }
コード例 #42
0
ファイル: Push.cs プロジェクト: cheahjs/wf-weblog-deathsnacks
 /// <summary>
 /// Push data payload to a <paramref name="topic"/>.
 /// </summary>
 /// <param name="push"></param>
 /// <param name="topic">Topic to send to</param>
 /// <param name="data">Data payload to send</param>
 /// <param name="collapse">Collapse key to use</param>
 private static void PushTopics(PushBroker push, string topic, Dictionary <string, string> data, string collapse)
 {
     foreach (var pair in data)
     {
         push.QueueNotification(
             new GcmNotification().ForDeviceRegistrationId("/topics/" + topic)
             .WithCollapseKey(collapse)
             .WithData(new Dictionary <string, string> {
             { pair.Key, pair.Value }
         }));
     }
 }
コード例 #43
0
 public static void Restart()
 {
     lock (_lock)
     {
         if (_broker != null)
         {
             _broker.StopAllServices(true);
             PushBo.Instance.ActiveChannels = null;
             _broker = CreateBroker();
         }
     }
 }
コード例 #44
0
        public ExitRoomServer()
        {
            InitializeComponent();
            countdownTimer = new System.Windows.Forms.Timer();
            countdownTimer.Tick += new EventHandler(timer_Tick);
            countdownTimer.Interval = 1000;

            registrationIDList = new List<string>();

            timerPaused = true;

            // PushSharp code implementation
            //Create our push services broker
            pushBroker = new PushBroker();

            //Wire up the events for all the services that the broker registers
            pushBroker.OnNotificationSent += NotificationSent;
            pushBroker.OnChannelException += ChannelException;
            pushBroker.OnServiceException += ServiceException;
            pushBroker.OnNotificationFailed += NotificationFailed;
            pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            pushBroker.OnChannelCreated += ChannelCreated;
            pushBroker.OnChannelDestroyed += ChannelDestroyed;

            // Register server to GCM service
            pushBroker.RegisterGcmService(new GcmPushChannelSettings("AIzaSyBmNMdpaTiZsIT2Ty3xUxUbK025MeK6Apk"));

            // Start listening for client registrations
            CheckForIllegalCrossThreadCalls = false;
            String hostname = "";
            System.Net.IPHostEntry ip = new IPHostEntry();
            hostname = System.Net.Dns.GetHostName();
            ip = System.Net.Dns.GetHostEntry(hostname);

            foreach (System.Net.IPAddress listip in ip.AddressList)
            {
                IPAddress ipAd = IPAddress.Parse(listip.ToString());
                int port = 4444;
                tcpListener = new TcpListener(ipAd, port);
                if (listip.AddressFamily == AddressFamily.InterNetwork)
                {
                    writeConsole("Server ip: " + listip);

                }
                writeConsole("Server listening to port: " + port);
                tcpListener.Start();
            }

            // Start listening for incoming data
            new Thread(connect).Start();
        }
コード例 #45
0
 private void destroy()
 {
     if (pushBrokerSandbox != null)
     {
         pushBrokerSandbox.StopAllServices(true);
     }
     if (pushBrokerProduction != null)
     {
         pushBrokerProduction.StopAllServices(true);
     }
     pushBrokerSandbox    = null;
     pushBrokerProduction = null;
 }
コード例 #46
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
        }
コード例 #47
0
        public void Test_StopAll()
        {
            var b = new PushBroker();

            b.RegisterWindowsPhoneService("APP1");
            b.RegisterWindowsPhoneService("APP2");

            Assert.AreEqual(b.GetAllRegistrations().Count(), 12, "Expected Registrations");

            b.StopAllServices();

            Assert.AreEqual(b.GetAllRegistrations().Count(), 0, "Expected 0 Registrations");
        }
コード例 #48
0
 private void btnStart_Click(object sender, EventArgs e)
 {
     push = new PushBroker();
     push.OnNotificationSent += push_OnNotificationSent;
     push.OnChannelException += push_OnChannelException;
     push.OnServiceException += push_OnServiceException;
     push.OnNotificationFailed += push_OnNotificationFailed;
     push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
     push.OnDeviceSubscriptionChanged += push_OnDeviceSubscriptionChanged;
     push.OnChannelCreated += push_OnChannelCreated;
     push.OnChannelDestroyed += push_OnChannelDestroyed;
     startActions();
 }
コード例 #49
0
        private static PushBroker CreateInstance()
        {
            Log.Info("initializing PushBroker instance");

            var config = PushServiceConfiguration.GetSection();

            var pushBroker = new PushBroker();

            SubscribeOnEvents(pushBroker, config);
            RegisterApnsService(pushBroker, config);
            RegisterGcmService(pushBroker, config);

            return pushBroker;
        }
コード例 #50
0
        private static void SubscribeOnEvents(PushBroker pushBroker, PushServiceConfiguration config)
        {
            pushBroker.OnChannelCreated += (sender, channel) => Log.DebugFormat("channel ({0}) created", channel);
            pushBroker.OnChannelDestroyed += sender => Log.Debug("channel destroyed");
            pushBroker.OnChannelException += (sender, channel, exception) => Log.ErrorFormat("channel ({0}) exception: {1}", channel, exception);
            pushBroker.OnServiceException += (sender, error) => Log.Error("service exception", error);
            pushBroker.OnNotificationRequeue += (sender, args) => Log.DebugFormat("notification ({0}) requeue: cancel = {1}", args.Notification, args.Cancel);
            pushBroker.OnNotificationSent += (sender, notification) => Log.DebugFormat("notification ({0}) sent", notification);

            pushBroker.OnNotificationFailed += (sender, notification, error) =>
                {
                    Log.ErrorFormat("notification ({0}) failed: {1}", notification, error);
                    if (error is MaxSendAttemptsReachedException)
                    {
                        if (Monitor.TryEnter(Lock))
                        {
                            try
                            {
                                if (_lastRestartTime + config.RestartInterval < DateTime.UtcNow)
                                {
                                    _instance.StopAllServices(false);
                                    _instance = null;
                                    _lastRestartTime = DateTime.UtcNow;
                                }
                            }
                            catch (Exception restartError)
                            {
                                Log.Error("can't restart service", restartError);
                            }
                            finally
                            {
                                Monitor.Exit(Lock);
                            }
                        }
                    }
                };

            pushBroker.OnDeviceSubscriptionChanged += (sender, id, subscriptionId, notification) =>
                {
                    Log.DebugFormat("device ({0}) subscription changed to {1}. notification is ({2})", id, subscriptionId, notification);
                    new DeviceDao().UpdateToken(id, subscriptionId);
                };

            pushBroker.OnDeviceSubscriptionExpired += (sender, id, utc, notification) =>
                {
                    Log.DebugFormat("device ({0}) subscription expired. notification is ({1}) and utc is ({2})", id, notification, utc);
                    new DeviceDao().Delete(id);
                };
        }
コード例 #51
0
 public static PushBroker GetBroker()
 {
     PushBroker pushBroker;
     if (HttpContext.Current.Application["PushBroker"] == null)
     {
         pushBroker = new PushBroker();
         pushBroker.RegisterWindowsPhoneService();
         HttpContext.Current.Application["PushBroker"] = pushBroker;
     }
     else
     {
         pushBroker = HttpContext.Current.Application["PushBroker"] as PushBroker;
     }
     return pushBroker;
 }
コード例 #52
0
ファイル: Program.cs プロジェクト: tianhang/PushSharp_custom
        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!

            //---------------------------
            // 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\"}"));

            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();
        }
コード例 #53
0
        public AndroidPushNotificationService(IPushRepository repository)
        {
            this._repository = repository;
            this._pushBroker = new PushBroker();

            ////Wire up the events for all the services that the broker registers
            //this._pushBroker.OnNotificationSent += this.NotificationSent;
            //this._pushBroker.OnChannelException += this.ChannelException;
            //this._pushBroker.OnServiceException += this.ServiceException;
            //this._pushBroker.OnDeviceSubscriptionExpired += this.DeviceSubscriptionExpired;
            //this._pushBroker.OnDeviceSubscriptionChanged += this.DeviceSubscriptionChanged;
            //this._pushBroker.OnChannelCreated += this.ChannelCreated;
            //this._pushBroker.OnChannelDestroyed += this.ChannelDestroyed;

            this.isStarted = false;
        }
コード例 #54
0
        protected virtual void QueueNotification(PushBroker push,IJobExecutionContext context)
        {
            ILog log = LogManager.GetLogger(typeof(ApnsNotificationJob));
            int cursor = 0;
           int size = JobConfig.DEFAULT_PAGE_SIZE;
            int successCount = 0;
            DateTime startDate = DateTime.Today;
            DateTime endDate = startDate.AddDays(1);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var prods = (from p in db.Promotions
                            where (p.StartDate >= startDate && p.StartDate < endDate)
                            && p.Status == 1
                             select p).OrderByDescending(p=>p.IsTop).ThenByDescending(p=>p.CreatedDate).FirstOrDefault();
                if (prods != null)
                {
                    var devices = (from d in db.DeviceLogs
                                   where d.Status == 1

                                   select new {DeviceToken = d.DeviceToken }).Distinct();

                    int totalCount = devices.Count();
                    while (cursor < totalCount)
                    {
                        var pageDevices = devices.OrderBy(o=>o.DeviceToken).Skip(cursor).Take(size);
                        foreach (var device in pageDevices)
                        {
                            push.QueueNotification(new AppleNotification()
                                               .ForDeviceToken(device.DeviceToken)
                                               .WithAlert(prods.Name)
                                               .WithBadge(1)
                                               .WithCustomItem("from",JsonConvert.SerializeObject(new {targettype=(int)PushSourceType.Promotion,targetvalue=prods.Id.ToString()}))
                                               .WithSound("sound.caf"));
                            successCount++;
                        }

                        cursor += size;
                    }
                }

            }
            sw.Stop();
            log.Info(string.Format("{0} notifications in {1} => {2} notis/s", successCount, sw.Elapsed, successCount / sw.Elapsed.TotalSeconds));

        }
コード例 #55
0
        public void PushToAndroid(string myAuthToken, string type)
        {
            //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;

           // string myAuthToken =
           // "f1NihVZfat0:APA91bE7vk55QCEbQzjYfI0jUv1bdCTP9ciK27AXXutSsXfJcOmAZCt8vRxFrMHHslo6DbVZyNKRMdxfYN6np1NJ9DR6Tz20SV9hInGlia7ftgq0o-mimw_UI7cUfE9wi4FzQJgND7y5";

            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyDIbpRonx7yh3NKBAr4rAzmfmIFeEWRTfE"));
            KompetansetorgetServerContext db = new KompetansetorgetServerContext();

            Random rnd = new Random();
            string uuid;
            string message;
            if (type == "project")
            {
                List<Project> projects = db.projects.ToList();
                int index = rnd.Next(0, projects.Count); // creates a number between 0 and Count
                uuid = projects[index].uuid;
                message = "Nytt oppgaveforslag registert!";
            }

            else
            {
                List<Job> jobs = db.jobs.ToList();
                int index = rnd.Next(0, jobs.Count); // creates a number between 0 and Count
                uuid = jobs[index].uuid;
                message = "Ny jobbstilling registert!";
            }

            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(myAuthToken)
                                    .WithJson("{\"message\":\"" + message + "\",\"badge\":\"7\",\"sound\":\"sound.caf\",\"type\":\"" + type + "\", \"uuid\":\"" + uuid + "\"}"));


            //Stop and wait for the queues to drains before it dispose 
            push.StopAllServices();
        }
コード例 #56
0
ファイル: CoreTests.cs プロジェクト: 89sos98/PushSharp
		public void Test_ApplicationId_And_NotificationType_Registrations()
		{
			var b = new PushBroker ();

			var gcm = new PushSharp.Android.GcmPushService (new PushSharp.Android.GcmPushChannelSettings (""));

			b.RegisterService<PushSharp.Android.GcmNotification> (gcm, "APP1");
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.GcmNotification> ("APP1").Count (), 1, "Expected 1 GcmNotification APP1 Registration");

			b.RegisterService<PushSharp.Android.GcmNotification> (gcm, "APP2");
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.GcmNotification> ("APP2").Count (), 1, "Expected 1 GcmNotification APP2 Registration");

			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.GcmNotification> ().Count (), 2, "Expected 2 GcmNotification Registrations");


			b.RegisterService<PushSharp.Android.C2dmNotification> (gcm, "APP1");
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.C2dmNotification> ("APP1").Count (), 1, "Expected 1 C2dmNotification APP1 Registration");

			b.RegisterService<PushSharp.Android.C2dmNotification> (gcm, "APP2");
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.C2dmNotification> ("APP2").Count (), 1, "Expected 1 C2dmNotification APP2 Registration");

			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.C2dmNotification> ().Count (), 2, "Expected 2 C2dmNotification Registrations");


			Assert.AreEqual (b.GetRegistrations ("APP1").Count (), 2, "Expected 2 APP1 Registrations");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 2, "Expected 2 APP2 Registrations");

			//Now remove GCM by type
			b.StopAllServices<PushSharp.Android.GcmNotification> ();
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.GcmNotification> ().Count (), 0, "Expected 0 GcmNotfication Registrations");
			Assert.AreEqual (b.GetRegistrations<PushSharp.Android.C2dmNotification> ().Count (), 2, "Expected 2 C2dmNotification Registrations");
			Assert.AreEqual (b.GetRegistrations ("APP1").Count (), 1, "Expected 1 APP1 Registration");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 1, "Expected 1 APP2 Registration");

			//Now remove APP1
			b.StopAllServices ("APP1");
			Assert.AreEqual (b.GetRegistrations ("APP1").Count (), 0, "Expected 0 APP1 Registration");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 1, "Expected 1 APP2 Registration");

			//Now remove APP2 
			b.StopAllServices ("APP2");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 0, "Expected 0 APP2 Registration");

			Assert.AreEqual (b.GetAllRegistrations ().Count (), 0, "Expected 0 Registrations");
		}
コード例 #57
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();
        }
コード例 #58
0
ファイル: CoreTests.cs プロジェクト: 89sos98/PushSharp
		public void Test_ApplicationId_Registrations()
		{
			var b = new PushBroker ();
			b.RegisterGcmService (new PushSharp.Android.GcmPushChannelSettings (""), "APP1");
			b.RegisterGcmService (new PushSharp.Android.GcmPushChannelSettings (""), "APP2");


			Assert.AreEqual (b.GetRegistrations ("APP1").Count (), 1, "Expected 1 APP1 Registration");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 1, "Expected 1 APP2 Registration");

			b.StopAllServices ("APP1");
			Assert.AreEqual (b.GetRegistrations ("APP1").Count (), 0, "Expected 0 APP1 Registrations");
			Assert.AreEqual (b.GetAllRegistrations ().Count (), 1, "Expected 1 Registration");

			b.StopAllServices ("APP2");
			Assert.AreEqual (b.GetRegistrations ("APP2").Count (), 0, "Expected 0 APP2 Registrations");
			Assert.AreEqual (b.GetAllRegistrations ().Count (), 0, "Expected 0 Registrations");
		}
コード例 #59
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;
            }
        }
コード例 #60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceNotificationBase"/> class.
        /// </summary>
        /// <param name="deviceRegistryDataRepository">The device registry data repository.</param>
        /// <param name="notificationLogDataRepository">The notification log data repository.</param>
        public DeviceNotification(IDeviceRegistryDataRepository deviceRegistryDataRepository,
            INotificationLogDataRepository notificationLogDataRepository)
        {
            try
            {
                this._deviceRegistryDataRepository = deviceRegistryDataRepository;
                this._notificationLogDataRepository = notificationLogDataRepository;

                this._broker = new PushBroker();
                RegisterEvents();

                _allDevices = this._deviceRegistryDataRepository
                    .GetList(x => x.StatusId.Equals((int)StatusEnum.Active)).ToList();
            }
            catch (Exception ex)
            {
                ex.ExceptionValueTracker();
            }
        }