コード例 #1
0
ファイル: AppPushDemo.cs プロジェクト: yellowjime/Examples
        private void CreateAndroidPushSettings()
        {
            if (needAndroidPush == false)
            {
                return;
            }
            // Start service.
            string senderId = ConfigurationManager.AppSettings["AndroidAppPushSenderID"];    // 82654747314
            string apiKey   = ConfigurationManager.AppSettings["AndroidAppPushApiKey"];      // "AIzaSyCnmCx9MISzmx8G_XcnWI8DwsuIX7wjzac"
            string pkgName  = ConfigurationManager.AppSettings["AndroidAppPushPkgName"];     // "com.google.android.gcm.demo.app"

            androidPushChannelSettings = new PushSharp.Android.GcmPushChannelSettings(senderId, apiKey, pkgName);

            push.RegisterGcmService(androidPushChannelSettings);
        }
コード例 #2
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);
        }
コード例 #3
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.");
        }
コード例 #4
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);
         }
     }
 }
コード例 #5
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)

                                       );
            }
        }
コード例 #6
0
    public NotificationManager(String compName)
    {
        _push = new PushBroker();
        _push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAutUa56XnPXuJaPtQk7dATEpvkzu7p1aE"));

        _compName = compName;
    }
コード例 #7
0
        public void PushAndroid(List <string> registrationIds, PushMessage msg)
        {
            //if (ConfigurationManager.AppSettings["EnableGooglePushNotification"].ToLower() == "no")
            //    return;

            if (!registrationIds.Any())
            {
                return;
            }

            //try
            //{
            var jsonMsg = JsonConvert.SerializeObject(msg);

            //---------------------------
            // 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(ANDROID_API_KEY));
            //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(registrationIds)
                                   //.WithJson(string.Format("{\"alert\":\"{0} \",\"badge\":{1},\"sound\":\"sound.caf\"}", message, badge)));
                                   .WithJson(jsonMsg));
            push.StopAllServices();
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("Push error: " + ex.ToString());
            //}
        }
コード例 #8
0
        /// <summary>
        /// Notifies to android.
        /// </summary>
        /// <param name="devices">The devices.</param>
        /// <param name="announcement">The announcement.</param>
        private void NotifyToAndroid(IList <DeviceRegistryModel> devices, string notificationToken, PageItemModel announcement)
        {
            try
            {
                if (!string.IsNullOrEmpty(this.GCMApiKey))
                {
                    _broker.RegisterGcmService(new GcmPushChannelSettings(this.GCMApiKey));

                    foreach (var device in devices)
                    {
                        _broker.QueueNotification(new GcmNotification()
                                                  .ForDeviceRegistrationId(device.DeviceId)
                                                  .WithJson(Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            alert             = announcement.PageHeaderText,
                            sound             = "default",
                            badge             = GetUnreadNotification(device),
                            LaunchImage       = announcement.PageItemImageUrl,
                            PageItemId        = announcement.PageItemId.ToString(),
                            NotificationToken = notificationToken
                        })));
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ExceptionValueTracker(devices, announcement);
            }
        }
コード例 #9
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();
    }
コード例 #10
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.");
        }
コード例 #11
0
    public NotificationManager(String compName)
    {
        _push = new PushBroker();
        _push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAutUa56XnPXuJaPtQk7dATEpvkzu7p1aE"));

        _compName = compName;
    }
コード例 #12
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();
        }
コード例 #13
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();
            }
        }
コード例 #14
0
        private void RegisterAndroidServices()
        {
            string googleConsoleAPIAccessKey = ConfigurationManager.AppSettings["GoogleConsoleAPIAccessKey"];

            //string googleConsoleAPIAccessKey = ConfigurationManager.AppSettings["GoogleConsoleAPIAccessKeyUser"];

            m_broker.RegisterGcmService(new GcmPushChannelSettings(googleConsoleAPIAccessKey));
        }
コード例 #15
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();
        }
コード例 #16
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");
		}
コード例 #17
0
 void ConfigureAndriod(NotiConfig config)
 {
     this.HasAndriod = config.HasAndroid;
     if (this.HasAndriod)
     {
         var setting = new GcmPushChannelSettings(config.GcmSenderId, config.GcmAuthToken, config.GcmPackageName);
         pushBroker.RegisterGcmService(setting);
     }
 }
コード例 #18
0
            public override void Configure(Funq.Container container)
            {
                _pushBroker.RegisterGcmService(new GcmPushChannelSettings(AppSettings.GetString("AndroidServerKey")));

                container.Register(c => _pushBroker).ReusedWithin(ReuseScope.Container);
                container.Register(new ServerSettings {
                    ApiKey = AppSettings.GetString("ApiKey")
                });
            }
コード例 #19
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;
        }
コード例 #20
0
        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");
        }
コード例 #21
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();
        }
コード例 #22
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();
        }
コード例 #23
0
        public static void SendNotification(List <PushNotificationDetail> pushSettings)
        {
            if (pushSettings == null)
            {
                return;
            }
            //Create our push services broker
            var push = new PushBroker();

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

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

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

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

            if (androidSettings.Count > 0 && androidSettings != null)
            {
                var androidSetting = androidSettings.FirstOrDefault();
                push.RegisterGcmService(new GcmPushChannelSettings(androidSetting.GoogleAPIKey));
                //Fluent construction of an Android GCM Notification
                //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(androidSetting.DeviceToken)
                                       .WithJson("{\"alert\":\"New campaign available\",\"badge\":" + androidSetting.Badge + ",\"sound\":\"" + androidSetting.Sound + "\"}"));
            }

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
コード例 #24
0
    public void SendPushMessage(string user_id, string msg, string head)
    {
        //Create our push services broker
        var push = new PushBroker();

        MyPush p = MyPush.GetPushInfo(user_id);

        push.RegisterGcmService(new GcmPushChannelSettings(WebConfigurationManager.AppSettings["apiKey"]));

        push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(p.Push_str)
                               .WithJson("{\"message\": \" " + msg + " \", \"title\": \" " + head + " \"}"));

        //Stop and wait for the queues to drains
        push.StopAllServices();
    }
コード例 #25
0
ファイル: UsersWS.cs プロジェクト: meir2017/CarePet
    public void SendNotificationToUser(string m, string t, string user_Reng)
    {
        string message = m;
        string title   = t;
        var    push    = new PushBroker();

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

        push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(user_Reng)
                               .WithJson("{\"message\": \" " + message + " \", \"content-available\": \"1\", \"force-start\": \"1\", \"title\": \"  " + title + "\", \"msgcnt\": \"1\", \"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

        push.StopAllServices();
    }
コード例 #26
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();
        }
コード例 #27
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();
        }
コード例 #28
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();
        }
コード例 #29
0
        public Stream SendMessage(Stream messageBody)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(messageBody);

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

                string result = "";

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

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

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

                    result += "IOS: ok; ";
                }

                return(Common.Utils.MakeTextAnswer(result));
            }
            catch (Exception e)
            {
                return(Common.Utils.MakeExceptionAnswer(e));
            }
        }
コード例 #30
0
        private static void RegisterGcmService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Gcm.ElementInformation.IsPresent)
            {
                return;
            }

            try
            {
                Log.Debug("registering gcm service");
                pushBroker.RegisterGcmService(new GcmPushChannelSettings(config.Gcm.AuthorizationKey));
            }
            catch (Exception error)
            {
                Log.Error("couldn't register gcm service", error);
            }
        }
コード例 #31
0
        public static ResultPush Android(AndroidMessage androidMessage)
        {
            ResultPush resultPush = new ResultPush();

            if (androidMessage != null)
            {
                PushBroker push = Pusher(resultPush);

                push.RegisterGcmService(new GcmPushChannelSettings(GetConfig.Key.Android));
                var jsonObject = JsonConvert.SerializeObject(androidMessage, SerializerSettings());

                push.QueueNotification(new GcmNotification()
                                       .ForDeviceRegistrationId(androidMessage.DeviceTokens)
                                       .WithJson(jsonObject));
            }

            return(resultPush);
        }
コード例 #32
0
        //private devicePlatform type;

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

                _push.OnNotificationSent          += NotificationSent;
                _push.OnChannelException          += ChannelException;
                _push.OnServiceException          += ServiceException;
                _push.OnNotificationFailed        += NotificationFailed;
                _push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
                _push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
                _push.OnChannelCreated            += ChannelCreated;
                _push.OnChannelDestroyed          += ChannelDestroyed;
                var appleCertificate = File.ReadAllBytes("E:\\APNSDistCertificate.p12");
                _push.RegisterAppleService(new ApplePushChannelSettings(true, appleCertificate, "PowerfulP1234"));
                _push.RegisterGcmService(new GcmPushChannelSettings("YOUR Google API's Console API Access  API KEY for Server Apps HERE"));
            }
        }
コード例 #33
0
ファイル: JKLineDb.cs プロジェクト: housemeow/JKLine-Server
        internal string SendMessage(int smid, int rmid, string message)
        {
            if (IsMemberNotExisting(smid) || IsMemberNotExisting(rmid))
            {
                return(MESSAGE_MEMBER_IS_NOT_EXISTING);
            }
            MessageQueue messageQueue = new MessageQueue();

            messageQueue.message         = message;
            messageQueue.MessageReceiver = GetMember(rmid);
            messageQueue.MessageSender   = GetMember(smid);
            messageQueue.rmid            = rmid;
            messageQueue.smid            = smid;
            messageQueue.timeStamp       = DateTime.Now;
            GetMessageQueues().Add(messageQueue);
            try
            {
                GetJKLineEntites().SaveChanges();
                DisposeJKLineEntities();
                string     receiverPushToken = messageQueue.MessageReceiver.pushToken;
                PushBroker push = new PushBroker();
                push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyA7dl25oulxDoTpExp9RdAlsCUR-tv61_U"));
                Dictionary <string, string> pushedMessage = new Dictionary <string, string>();
                int    unreceiveMessageCount = GetUnreceiveMessageCount(smid, rmid);
                string jsonString            = String.Format("{{\"message\":\"{0}\",\"senderName\":\"{1}\",\"timeStamp\":\"{2}\",\"count\":{3}}}", message, messageQueue.MessageSender.name, messageQueue.timeStamp.ToShortTimeString(), unreceiveMessageCount);
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiverPushToken)
                                       .WithJson(jsonString));
                return(jsonString);
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            GetJKLineEntites().SaveChanges();
            return(DateTime.Now.ToString());
        }
コード例 #34
0
ファイル: Common.cs プロジェクト: travismc6/TripServiceApp
        public async static Task <bool> SendGms(string notifyId, string tripUserId, string tripId, string titleText, string contentText, string type, string tripCode = null,
                                                string userCode = null, string tripUserName = null, string tripDisplayName = null, string extras = null)
        {
            bool success = true;

            try
            {
                var json = @"
                    {{
                        ""titleMsg"" : ""{0}"",
                        ""contentMsg"" : ""{1}"",
                        ""tripId"" : ""{2}"",
                        ""tripUserId"" : ""{3}"",
                        ""type"" : ""{4}"",
                        ""tripCode"" : ""{5}"",
                        ""tripUserCode"" : ""{6}"",
                        ""tripUserName"" : ""{7}"",
                        ""tripDisplayName"" : ""{8}""
                    }}
                ";
                json = String.Format(json, titleText, contentText, tripId, tripUserId, type, tripCode, userCode, tripUserName, tripDisplayName);

                new Task(() =>
                {
                    PushBroker pushBroker = new PushBroker();
                    pushBroker.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAwINnHoq85XTCZBraKW4yxKC_bk4NYqw8"));
                    pushBroker.QueueNotification(new GcmNotification().ForDeviceRegistrationId(notifyId)
                                                 .WithJson(json));

                    pushBroker.StopAllServices();
                }

                         ).Start();
            }

            catch (Exception ex)
            {
                success = false;
            }

            return(success);
        }
コード例 #35
0
ファイル: Common.cs プロジェクト: travismc6/TripServiceApp
        public async static Task<bool> SendGms(string notifyId, string tripUserId, string tripId, string titleText, string contentText, string type, string tripCode = null, 
            string userCode = null, string tripUserName = null, string tripDisplayName = null, string extras = null)
        {
            bool success = true;
            try
            {
                var json = @"
                    {{
                        ""titleMsg"" : ""{0}"",
                        ""contentMsg"" : ""{1}"",
                        ""tripId"" : ""{2}"",
                        ""tripUserId"" : ""{3}"",
                        ""type"" : ""{4}"",
                        ""tripCode"" : ""{5}"",
                        ""tripUserCode"" : ""{6}"",
                        ""tripUserName"" : ""{7}"",
                        ""tripDisplayName"" : ""{8}""
                    }}
                ";
                json = String.Format(json, titleText, contentText, tripId, tripUserId, type, tripCode, userCode, tripUserName, tripDisplayName);

                 new Task( () =>
                    {
                        PushBroker pushBroker = new PushBroker();
                        pushBroker.RegisterGcmService(new GcmPushChannelSettings("AIzaSyAwINnHoq85XTCZBraKW4yxKC_bk4NYqw8"));
                        pushBroker.QueueNotification(new GcmNotification().ForDeviceRegistrationId(notifyId)
                            .WithJson(json));
                    
                        pushBroker.StopAllServices();
                    }
                    
                    ).Start();
            } 

            catch(Exception ex)
            {
                success = false;
            }

            return success;
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: l0vekobe0824/MDCC
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "<specify your .p12 file here>"));

            string iphoneToken = "<PUT YOUR DEVICE TOKEN HERE>";

            var settings = new ApplePushChannelSettings(cert, "pushdemo");

            push.RegisterAppleService(settings);

            var Notification = new AppleNotification()
                               .ForDeviceToken(iphoneToken)
                               .WithAlert("欢迎来到中国移动者开发大会!")
                               .WithSound("sound.caf")
                               .WithBadge(4);

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



            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();

            //GCM



            var RegID_emulator = "<PUT YUOR REGISTER ID HERE>";

            push.RegisterGcmService(new GcmPushChannelSettings("<PUT YOUR GOOGLE API SERVER KEY HERE>"));

            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID_emulator)
                                   .WithJson("{\"alert\":\"欢迎来到中国移动者开发大会!\",\"badge\":7,\"sound\":\"sound.caf\"}"));


            push.StopAllServices();
        }
コード例 #37
0
        private void sendNotification(bool isApple, bool isAndroid, string deviceToken, string notificationText)
        {
            if (string.IsNullOrEmpty(deviceToken))
            {
                MessageBox.Show(this, "Enter device token");
                return;
            }

            var pushBroker = new PushBroker();

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

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

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

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

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

            pushBroker.StopAllServices();
        }
コード例 #38
0
        public void testPush()
        {
            var push = new PushBroker();

            /*
             * //Registering the Apple Service and sending an iOS Notification
             * var appleCert = File.ReadAllBytes("ApnsSandboxCert.p12"));
             * push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "pwd"));
             *  push.QueueNotification(new AppleNotification()
             *             .ForDeviceToken("DEVICE TOKEN HERE")
             *             .WithAlert("Hello World!")
             *             .WithBadge(7)
             *             .WithSound("sound.caf"));*/

            //Registering the GCM Service and sending an Android Notification
            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyD3J2zRHVMR1BPPnbCVaB1D_qWBYGC4-uU"));
            //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")
                                   .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
        }
コード例 #39
0
        public static void Notify(DeviceToken deviceToken, string message)
        {
            //Create our push services broker
            var push = new PushBroker();

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

            push.StopAllServices();
        }
コード例 #40
0
        public void testPush()
        {
            using(var push = new PushBroker())
            {

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

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

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

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

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

            //Queue the Android notification. Unfortunately, we have to build this packet manually.
            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE_REGISTRATION_ID")
                      .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
            //*********************************
            }
        }
コード例 #41
0
        public async Task<int> AndroidSend(object data) // AppName & DeviceId % Message
        {
            return await Task.Run(() =>
            {
                try
                {
                    //dynamic inData = data.ToDynamicObject();
                    //string AppName = inData.AppName;
                    //string DeviceId = inData.DeviceId;
                    string Message = "inData.Message";


                    //string apiKey = GetApiKey(AppName);
                    PushBroker push = new PushBroker();
                    #region events
                    push.OnNotificationSent += NotificationSent;
                    push.OnChannelException += ChannelException;
                    push.OnServiceException += ServiceException;
                    push.OnNotificationFailed += NotificationFailed;
                    push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
                    push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
                    push.OnChannelCreated += ChannelCreated;
                    push.OnChannelDestroyed += ChannelDestroyed;
                    #endregion
                    push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyCBaTkTbugJ3kOlP0ZB6d-8wGZgq0uVRbk"));
                    push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("dWhQGPfAMhQ:APA91bGC6NvVjPNBcRbBdKEbOPA6t2nEHTzR3DgIiCjKLDmYfS0ovQCLwGSJxoLIjhVA6FGYKqNEoLx1y8Yw3mKcP5l31bFJ-X1NRNMZqEJLULVEU7OHsFw_jDIAE2bZwY-0PnVMLSJ-")
                        .WithJson(@"{""message"":""" + Message + @"""}"));
                    push.StopAllServices();
                    return 1;
                }
                catch (Exception ex)
                {
                    return ex.HResult;
                }
            });
        }
コード例 #42
0
ファイル: Program.cs プロジェクト: Terry-Lin/MDCC
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                        "<specify your .p12 file here>"));

            string iphoneToken = "<PUT YOUR DEVICE TOKEN HERE>";

            var settings = new ApplePushChannelSettings(cert, "pushdemo");

            push.RegisterAppleService(settings);

            var Notification = new AppleNotification()
                .ForDeviceToken(iphoneToken)
                    .WithAlert("欢迎来到中国移动者开发大会!")
                    .WithSound("sound.caf")
                    .WithBadge(4);

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();

            //GCM

            var RegID_emulator = "<PUT YUOR REGISTER ID HERE>";

            push.RegisterGcmService(new GcmPushChannelSettings("<PUT YOUR GOOGLE API SERVER KEY HERE>"));

            push.QueueNotification (new GcmNotification ().ForDeviceRegistrationId (RegID_emulator)
                                   .WithJson("{\"alert\":\"欢迎来到中国移动者开发大会!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

            push.StopAllServices();
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: mamta-bisht/VS2013Roadshow
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                        "PushDemo.p12"));
            string ipadtoken = "6f22cc6eaff02281125092987dd6b9dc1242722bb455253ff308f71dab296169";
            string iphoneToken = "5477ac3de431bcf89982c569cb33846285565b7f62b235ad10d8737754b8b81a";

            var settings = new ApplePushChannelSettings(cert, "pushdemo");

            push.RegisterAppleService(settings);

            var Notification = new AppleNotification()
                .ForDeviceToken(iphoneToken)
                    .WithAlert("欢迎来到Visual Studio 2013新功能会议!")
                    .WithSound("sound.caf")
                    .WithBadge(4);

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

            Console.WriteLine("Queue Finished.....");

            //GCM

            var RegID_phone = "APA91bEHi1O4JzS3tmtAY5zycJCTcUZyxvDgwKRjHdvvp02DfEGsC433d5xN0Naf8BF1-l1Q9kQra_GpslhXuB-D_lyiJdLWlCKehwgAsNdVhUcLIeHp7-aElC_kol62yBZ1ZJtInwq7";
            var RegID_emulator = "APA91bFj1aE5r6TjypnfvAKzTBK19eYGLfuBpKldIhMCwn5YiubfmUFLJg54Pw2tFvvZnC0w4QIR35Wlrf6phzuKS1L8r0YfVHbYfo8tNlQNmQ9WjMHUgam5rC2HrApQDQrLJyhXAcwj";

            push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyARS7ie-GIeCSGAx_bxq9yQk6l9xgl_2IM"));

            push.QueueNotification (new GcmNotification ().ForDeviceRegistrationId (RegID_emulator)
                                    .WithJson("{\"alert\":\"欢迎来到Visual Studio 2013新功能会议!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

            push.StopAllServices();
        }
コード例 #44
0
ファイル: Program.cs プロジェクト: FragCoder/PushSharp
        static void Main(string[] args)
        {
            //Create our push services broker
            var push = new PushBroker();

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

            //------------------------------------------------
            //IMPORTANT NOTE about Push Service Registrations
            //------------------------------------------------
            //Some of the methods in this sample such as 'RegisterAppleServices' depend on you referencing the correct
            //assemblies, and having the correct 'using PushSharp;' in your file since they are extension methods!!!

            // If you don't want to use the extension method helpers you can register a service like this:
            //push.RegisterService<WindowsPhoneToastNotification>(new WindowsPhonePushService());

            //If you register your services like this, you must register the service for each type of notification
            //you want it to handle.  In the case of WindowsPhone, there are several notification types!

            //-------------------------
            // APPLE NOTIFICATIONS
            //-------------------------
            //Configure and start Apple APNS
            // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to generate one for connecting to Sandbox,
            //   and one for connecting to Production.  You must use the right one, to match the provisioning profile you build your
            //   app with!
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/PushSharp.Apns.Sandbox.p12"));
            //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server
            //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
            //  If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
            //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')
            push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "CERTIFICATE PASSWORD HERE")); //Extension method
            //Fluent construction of an iOS notification
            //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            //  for registered for remote notifications is called, and the device token is passed back to you
            push.QueueNotification(new AppleNotification()
                                       .ForDeviceToken("DEVICE TOKEN HERE")
                                       .WithAlert("Hello World!")
                                       .WithBadge(7)
                                       .WithSound("sound.caf"));

            //---------------------------
            // ANDROID GCM NOTIFICATIONS
            //---------------------------
            //Configure and start Android GCM
            //IMPORTANT: The API KEY comes from your Google APIs Console App, under the API Access section,
            //  by choosing 'Create new Server key...'
            //  You must ensure the 'Google Cloud Messaging for Android' service is enabled in your APIs Console
            push.RegisterGcmService(new GcmPushChannelSettings("YOUR Google API's Console API Access  API KEY for Server Apps HERE"));
            //Fluent construction of an Android GCM Notification
            //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE REGISTRATION ID HERE")
                                  .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

            //-----------------------------
            // WINDOWS PHONE NOTIFICATIONS
            //-----------------------------
            //Configure and start Windows Phone Notifications
            push.RegisterWindowsPhoneService();
            //Fluent construction of a Windows Phone Toast notification
            //IMPORTANT: For Windows Phone you MUST use your own Endpoint Uri here that gets generated within your Windows Phone app itself!
            push.QueueNotification(new WindowsPhoneToastNotification()
                .ForEndpointUri(new Uri("DEVICE REGISTRATION CHANNEL URI HERE"))
                .ForOSVersion(WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
                .WithBatchingInterval(BatchingInterval.Immediate)
                .WithNavigatePath("/MainPage.xaml")
                .WithText1("PushSharp")
                .WithText2("This is a Toast"));

            //-------------------------
            // WINDOWS NOTIFICATIONS
            //-------------------------
            //Configure and start Windows Notifications
            push.RegisterWindowsService(new WindowsPushChannelSettings("WINDOWS APP PACKAGE NAME HERE",
                "WINDOWS APP PACKAGE SECURITY IDENTIFIER HERE", "CLIENT SECRET HERE"));
            //Fluent construction of a Windows Toast Notification
            push.QueueNotification(new WindowsToastNotification()
                .AsToastText01("This is a test")
                .ForChannelUri("DEVICE CHANNEL URI HERE"));

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

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #45
0
        private static void RegisterGcmService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Gcm.ElementInformation.IsPresent)
                return;

            try
            {
                Log.Debug("registering gcm service");
                pushBroker.RegisterGcmService(new GcmPushChannelSettings(config.Gcm.AuthorizationKey));
            }
            catch (Exception error)
            {
                Log.Error("couldn't register gcm service", error);
            }
        }
コード例 #46
0
ファイル: Program.cs プロジェクト: RCortes/BBVA
        static void Main(string[] args)
        {
            Process[] localAll = Process.GetProcesses();
            int p = 1;
            foreach (Process pr in localAll)
            {
                if (pr.ProcessName == "sendNotificationAndroid")
                {
                    if (p > 1)
                    {
                        Console.Write("\n\n\n \"sendNotificationAndroid.exe\" ya esta en ejecución... será cerrada");
                        System.Threading.Thread.Sleep(3000);
                        Environment.Exit(0);
                    }
                    p++;
                }
            }

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

            var push = new PushBroker();

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

            SqlConnection conn = new SqlConnection(connectionString: conex);

            try
            {
                conn.Open();

                while (true)
                {
                    string type = "";

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

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

                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

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

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

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

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

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

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

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

                    if (type != "")
                    {

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

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

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

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

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

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

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

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

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

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

            //                                }
            //                            }
            //                        }

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

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

            //                        }
            //                    }

                        string sql = @"SELECT * FROM dbo.Notification WHERE idPlataform = 1 AND idNotificationType = @type ORDER BY creation";
                        command = new SqlCommand(sql, conn);

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

                        push.StopAllServices(true);

                        push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["configGCM"]));

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

                              //  if (DateTime.Compare(DateTime.Parse(expiration), DateTime.Parse(ahora)) <= 0)
                              //  {
                                    push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(_dr[1].ToString())
                                        .WithJson("{\"alert\":\"" + _dr[11].ToString() + "\",\"badge\":\"1\",\"sound\":\"default.caf\"}"));
                                //}

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

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

                                }
                                catch (Exception ex2)
                                {
                                    //Emails.Email.Enviarcorreo("Error envio de push Android BBVA", "*****@*****.**", ex.Message.ToString(), "Error");
                                    Console.Write(ex2.Message);
                                    System.Threading.Thread.Sleep(3000);

                                }

                            }
                            actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());
                            if (DateTime.Compare(actual, duration) > 0)
                            {
                                break;

                            }
                        }
                        push.StopAllServices(true);
                    }
                }

                    conn.Close();

            }
            catch (Exception ex)
            {
                conn.Close();
                Console.Write(ex.Message);
                string body = "\n Error: " + ex.Message +" \n hora: " + DateTime.Now.ToString();
                Emails.Email.Enviarcorreo("Error envio de push Android BBVA", "*****@*****.**", body, "Error");
                System.Threading.Thread.Sleep(7000);
                push.StopAllServices(true);
                Environment.Exit(0);
            }
        }
コード例 #47
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.");
        }
コード例 #48
0
ファイル: JKLineDb.cs プロジェクト: housemeow/JKLine-Server
        internal string SendMessage(int smid, int rmid, string message)
        {
            if (IsMemberNotExisting(smid) || IsMemberNotExisting(rmid))
            {
                return MESSAGE_MEMBER_IS_NOT_EXISTING;
            }
            MessageQueue messageQueue = new MessageQueue();
            messageQueue.message = message;
            messageQueue.MessageReceiver = GetMember(rmid);
            messageQueue.MessageSender = GetMember(smid);
            messageQueue.rmid = rmid;
            messageQueue.smid = smid;
            messageQueue.timeStamp = DateTime.Now;
            GetMessageQueues().Add(messageQueue);
            try
            {
                GetJKLineEntites().SaveChanges();
                DisposeJKLineEntities();
                string receiverPushToken = messageQueue.MessageReceiver.pushToken;
                PushBroker push = new PushBroker();
                push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyA7dl25oulxDoTpExp9RdAlsCUR-tv61_U"));
                Dictionary<string, string> pushedMessage = new Dictionary<string, string>();
                int unreceiveMessageCount = GetUnreceiveMessageCount(smid, rmid);
                string jsonString = String.Format("{{\"message\":\"{0}\",\"senderName\":\"{1}\",\"timeStamp\":\"{2}\",\"count\":{3}}}", message, messageQueue.MessageSender.name, messageQueue.timeStamp.ToShortTimeString(), unreceiveMessageCount);
                push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiverPushToken)
                                      .WithJson(jsonString));
                return jsonString;

            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
            GetJKLineEntites().SaveChanges();
            return DateTime.Now.ToString();
        }
コード例 #49
0
ファイル: WebApiController.cs プロジェクト: marduk112/clubmap
 public async Task<IHttpActionResult> SendMessage(Message message)
 {
     try
     {
         message.SenderId = User.Identity.GetUserId();
         var result = await new WebApiLogic().SaveMessage(message);
         if (!result) return BadRequest();
         string registrationId;
         using (var db = new ApplicationDbContext())
         {
             var user = db.Users.Find(message.ReceiverId);
             registrationId = user.DeviceId;
         }
         var push = new PushBroker();
         //---------------------------
         // 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("AIzaSyDOOAhH2o5IP00lL9aJt5NbYfRNfGWDJ94"));
         //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(registrationId)
             .WithJson(JsonConvert.SerializeObject(message)));
         //Stop and wait for the queues to drains
         push.StopAllServices();
         return Ok();
     }
     catch
     {
         return InternalServerError();
     }
 }
コード例 #50
0
ファイル: Cronus.cs プロジェクト: Elders/Pushnotifications
        private static PushBroker ConfigurePushBroker(Pandora pandora)
        {
            var broker = new PushBroker();
            broker.OnNotificationSent += PushNotificationLogger.NotificationSent;
            broker.OnChannelException += PushNotificationLogger.ChannelException;
            broker.OnServiceException += PushNotificationLogger.ServiceException;
            broker.OnNotificationFailed += PushNotificationLogger.NotificationFailed;
            broker.OnDeviceSubscriptionExpired += PushNotificationLogger.DeviceSubscriptionExpired;
            broker.OnDeviceSubscriptionChanged += PushNotificationLogger.DeviceSubscriptionChanged;
            broker.OnChannelCreated += PushNotificationLogger.ChannelCreated;
            broker.OnChannelDestroyed += PushNotificationLogger.ChannelDestroyed;

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

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

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

            string iosCertPath = Environment.ExpandEnvironmentVariables(iosCert);

            var appleCert = File.ReadAllBytes(iosCertPath);

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

            return broker;
        }
コード例 #51
0
ファイル: Program.cs プロジェクト: lbosman/PushSharp
        private static void SendNotification(string deviceToken, string title, string body, int badgeCount, string sound)
        {
            //Create our push services broker
            var push = new PushBroker();

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

            //------------------------------------------------
            //IMPORTANT NOTE about Push Service Registrations
            //------------------------------------------------
            //Some of the methods in this sample such as 'RegisterAppleServices' depend on you referencing the correct
            //assemblies, and having the correct 'using PushSharp;' in your file since they are extension methods!!!

            // If you don't want to use the extension method helpers you can register a service like this:
            //push.RegisterService<WindowsPhoneToastNotification>(new WindowsPhonePushService());

            //If you register your services like this, you must register the service for each type of notification
            //you want it to handle.  In the case of WindowsPhone, there are several notification types!

            //-------------------------
            // APPLE NOTIFICATIONS
            //-------------------------
            //Configure and start Apple APNS
            // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to generate one for connecting to Sandbox,
            //   and one for connecting to Production.  You must use the right one, to match the provisioning profile you build your
            //   app with!
            var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../Resources/OLBPhoneSandboxCertificate.p12"));
            //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server
            //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
            //  If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
            //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')

            ApplePushChannelSettings appleSettings = new ApplePushChannelSettings(false, appleCert, "0lbSandb0x");
            push.RegisterAppleService(appleSettings); //Extension method

            AppleNotification notification = new AppleNotification();

            notification.ForDeviceToken(deviceToken);

            AppleNotificationAlert alert = new AppleNotificationAlert ();

            if (!string.IsNullOrWhiteSpace (title))
                alert.Title = title;

                        if (!string.IsNullOrWhiteSpace (body))
                            alert.Body = body;

                        notification.WithAlert (alert);

                        if (badgeCount >= 0)
                            notification.WithBadge (badgeCount);

                        if (!string.IsNullOrWhiteSpace (sound))
                        {
                            notification.WithSound (sound);
                        }

            push.QueueNotification(notification);

            //---------------------------
            // ANDROID GCM NOTIFICATIONS
            //---------------------------
            //Configure and start Android GCM
            //IMPORTANT: The API KEY comes from your Google APIs Console App, under the API Access section,
            //  by choosing 'Create new Server key...'
            //  You must ensure the 'Google Cloud Messaging for Android' service is enabled in your APIs Console

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

            //Fluent construction of an Android GCM Notification
            //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
            push.QueueNotification(
                new GcmNotification().ForDeviceRegistrationId("APA91bHr5W1cNl5mcZ_iWqGKVnvcXeZwYdVGCCFjt0M8egamRAIq5lCASbUQe-3E9M74CiD8Moildh4SC8Qj6qUUpCnNOQ5v17A9go1enqDipOGSaeiDU_I3fGroneA7tL3FAMlN60nW")
                            .WithJson("{\"alert\":\"Hello Leslie!\",\"badge\":7,\"sound\":\"sound.caf\"}"))
            ;

            //-----------------------------
            //			// WINDOWS PHONE NOTIFICATIONS
            //			//-----------------------------
            //			//Configure and start Windows Phone Notifications
            //			push.RegisterWindowsPhoneService();
            //			//Fluent construction of a Windows Phone Toast notification
            //			//IMPORTANT: For Windows Phone you MUST use your own Endpoint Uri here that gets generated within your Windows Phone app itself!
            //			push.QueueNotification(new WindowsPhoneToastNotification()
            //				.ForEndpointUri(new Uri("DEVICE REGISTRATION CHANNEL URI HERE"))
            //				.ForOSVersion(WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
            //				.WithBatchingInterval(BatchingInterval.Immediate)
            //				.WithNavigatePath("/MainPage.xaml")
            //				.WithText1("PushSharp")
            //				.WithText2("This is a Toast"));
            //
            //
            //			//-------------------------
            //			// WINDOWS NOTIFICATIONS
            //			//-------------------------
            //			//Configure and start Windows Notifications
            //			push.RegisterWindowsService(new WindowsPushChannelSettings("WINDOWS APP PACKAGE NAME HERE",
            //				"WINDOWS APP PACKAGE SECURITY IDENTIFIER HERE", "CLIENT SECRET HERE"));
            //			//Fluent construction of a Windows Toast Notification
            //			push.QueueNotification(new WindowsToastNotification()
            //				.AsToastText01("This is a test")
            //				.ForChannelUri("DEVICE CHANNEL URI HERE"));

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

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
コード例 #52
0
        public Stream SendMessage(Stream messageBody)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(messageBody);

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

                string result = "";

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

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

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

                    result += "IOS: ok; ";
                }

                return Common.Utils.MakeTextAnswer(result);

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

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

            var push = new PushBroker();

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

            try
            {
                SqlConnection conn = new SqlConnection(connectionString: conex);
                conn.Open();

                while (true)
                {
                    string type = "";

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

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

                    //conn = new SqlConnection(connectionString: conex);
                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

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

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

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

                    if (type != "")
                    {

                        string sql = @"SELECT * FROM dbo.Notification WHERE idPlataform = 1 AND idNotificationType = @type";
                        command = new SqlCommand(sql, conn);

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

                        push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["configGCM"]));

                        int i = 0;
                        List<string> IDs = new List<string>();
                        foreach (DataRow _dr in dtDatos.Tables[0].Rows)
                        {

                            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(_dr[1].ToString())
                                .WithJson("{\"alert\":\"" + _dr[9].ToString() + " " + _dr[10].ToString() + " " + _dr[11].ToString() + "\",\"badge\":\"1\",\"sound\":\"default.caf\"}"));

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

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

                                }
                                catch (Exception ex2)
                                {
                                    Emails.Email.Enviarcorreo("Error envio de push Android BBVA", "*****@*****.**", ex.Message.ToString(), "Error");
                                    Console.Write(ex2.Message);
                                }

                            }
                           // push.StopAllServices();
                            //i++;
                            //if (i % 500 == 0)
                            //{
                               push.StopAllServices();
                            //}
                            actual = DateTime.Parse("01-01-0001 " + DateTime.Now.ToShortTimeString());
                            if (DateTime.Compare(actual, duration) > 0)
                            {
                                break;
                            }
                        }
                        push.StopAllServices();
                        System.Threading.Thread.Sleep(5000);
                    }
                }
                    conn.Close();

            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                Emails.Email.Enviarcorreo("Error envio de push Android BBVA", "*****@*****.**", ex.Message.ToString(), "Error");
                push.StopAllServices();
            }
        }