Esempio n. 1
0
        public void PushWarnToApple(string user, string sendMessage)
        {
            var push = new PushBroker();

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

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

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

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

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

            push.StopAllServices();
        }
        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();
        }
 //This method is designed to check push notification, however without real device it's not possible
 public string HelloWorld(string device)
 {
     //create the puchbroker object
     var push = new PushBroker();
     //Wire up the events for all the services that the broker registers
     push.OnNotificationSent += NotificationSent;
     push.OnChannelException += ChannelException;
     push.OnServiceException += ServiceException;
     push.OnNotificationFailed += NotificationFailed;
     push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
     push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
     push.OnChannelCreated += ChannelCreated;
     push.OnChannelDestroyed += ChannelDestroyed;         
            
     try
     {
         var appleCert = File.ReadAllBytes(Server.MapPath("certificate directory"));
                
         push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "certificate password"));
                
         push.QueueNotification(new AppleNotification()
                                             .ForDeviceToken(device)//the recipient device id
                                             .WithAlert("Hello")//the message
                                             .WithBadge(1)
                                             .WithSound("sound.caf")
                                             );
     }
     catch (Exception ex)
     {
          throw ex;
     }
      
     push.StopAllServices(waitForQueuesToFinish: true);
     return "Hello, World!";
 }
Esempio n. 4
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);
        }
Esempio n. 5
0
    [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();
    }
Esempio n. 6
0
        public void SendPushMessage(string msg, string customItemKey = null, params object[] customItemValues)
        {
            if (needApplePush)
            {
                string deviceToken = appleTargetDeviceToken;
                SendApplePushMessage(deviceToken, msg, customItemKey, customItemValues);
            }

            if (needAndroidPush)
            {
                var aMsg = new
                {
                    //    AlertID = alert.AlertID,
                    Message = msg
                };
                string androidRegId = "APA91bEcGtjKIg26hv9_HfNLS0qLaIJN69e-JdJVlthB2bR5bMpwpXN88SiSpIC-VSWUydvdbgfeseb7_rzNb0N27p1rp709_rv6VeT43okapIlPhXiGgXava3Z2AGV-Uum-6U3nvdeUt_khoLswpUV-ECsu3tCuuL2lfqzOvAipQX5irfNXzUg";
                SendAndroidPushMessage(androidRegId, JsonConvert.SerializeObject(aMsg));
            }

            if (needBlackBerryPush)
            {
                SendBlackBerryPushMessage();
            }

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

            //Stop and wait for the queues to drains
            push.StopAllServices(true);
        }
Esempio n. 7
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();
            }
        }
Esempio n. 8
0
        /// <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.");
        }
Esempio n. 9
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();
        }
Esempio n. 10
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");
		}
Esempio n. 11
0
		public void Test_NotificationType_Registrations()
		{
			var b = new PushBroker ();

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

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

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

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

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

			Assert.AreEqual (b.GetAllRegistrations ().Count (), 0, "Expected 0 Registrations");
		}
Esempio n. 12
0
 private void destroy()
 {
     if (pushBrokerSandbox != null)
     {
         pushBrokerSandbox.StopAllServices(true);
     }
     if (pushBrokerProduction != null)
     {
         pushBrokerProduction.StopAllServices(true);
     }
     pushBrokerSandbox    = null;
     pushBrokerProduction = null;
 }
Esempio n. 13
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();
        }
        private static void SubscribeOnEvents(PushBroker pushBroker, PushServiceConfiguration config)
        {
            pushBroker.OnChannelCreated      += (sender, channel) => Log.DebugFormat("channel ({0}) created", channel);
            pushBroker.OnChannelDestroyed    += sender => Log.Debug("channel destroyed");
            pushBroker.OnChannelException    += (sender, channel, exception) => Log.ErrorFormat("channel ({0}) exception: {1}", channel, exception);
            pushBroker.OnServiceException    += (sender, error) => Log.Error("service exception", error);
            pushBroker.OnNotificationRequeue += (sender, args) => Log.DebugFormat("notification ({0}) requeue: cancel = {1}", args.Notification, args.Cancel);
            pushBroker.OnNotificationSent    += (sender, notification) => Log.DebugFormat("notification ({0}) sent", notification);

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

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

            pushBroker.OnDeviceSubscriptionExpired += (sender, id, utc, notification) =>
            {
                Log.DebugFormat("device ({0}) subscription expired. notification is ({1}) and utc is ({2})", id, notification, utc);
                new DeviceDao().Delete(id);
            };
        }
Esempio n. 15
0
    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();
    }
Esempio n. 16
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();
        }
Esempio n. 17
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();
        }
Esempio n. 18
0
        public static void Main(string[] args)
        {
            var pushBroker = new PushBroker();

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

             var appleSettings = new ApplePushChannelSettings(cert, "idbmobile");

             var n = new AppleNotification().ForDeviceToken("7ced312b754878f6971c1169f02fcec3e33bc6b92ccade4921b54961fa03f93b")
            .WithAlert("IDB Push Test").WithBadge(3);

             pushBroker.RegisterAppleService(appleSettings);

             pushBroker.QueueNotification(n);

             pushBroker.StopAllServices();
        }
Esempio n. 19
0
        public void SendPushNotifications(IEnumerable <string> userDeviceTokens, string alert, int badge, string customItem)
        {
            var push = new PushBroker();

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

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

            push.StopAllServices();
        }
        /// <summary>
        /// Kills the push broker instance by frist stoping it's services and unhooking the event handlers, then disposes the sent DbContext.
        /// </summary>
        /// <param name="dbContext">The current EF database context instance to be disposed.</param>
        private void KillBroker(PushSharpDatabaseContext dbContext)
        {
            _broker.StopAllServices();

            // unsubscribe from the 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;

            DisposeContext(dbContext, true);

            On(DisplayMessage, "Push Broker successfully stopped.");
        }
Esempio n. 21
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();
        }
Esempio n. 22
0
        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;
        }
Esempio n. 23
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "<specify your .p12 file here>"));

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

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

            push.RegisterAppleService(settings);

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

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



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

            //GCM



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

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

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


            push.StopAllServices();
        }
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap data = context.JobDetail.JobDataMap;
            var certFile = data.GetString("p12");
            var certPwd = data.GetString("password");
            //Create our push services broker
            var push = new PushBroker();

            //Wire up the events for all the services that the broker registers
            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;

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

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

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

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

            //等待所有的推送任务完成并停止推送服务
            push.StopAllServices();
        }
        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();
        }
Esempio n. 27
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      "PushDemo.p12"));
            string ipadtoken   = "6f22cc6eaff02281125092987dd6b9dc1242722bb455253ff308f71dab296169";
            string iphoneToken = "5477ac3de431bcf89982c569cb33846285565b7f62b235ad10d8737754b8b81a";

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

            push.RegisterAppleService(settings);

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

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



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

            //GCM


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

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

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


            push.StopAllServices();
        }
Esempio n. 28
0
        public void RunPushNotification2()
        {
            string message = "globl";
            //message = getTEST();
            List <Event> m2 = GetUserEventsUsingClass();

            message = m2[1].description.ToString() + "  , " + m2[0].description.ToString();
            //message = m2[1];

            var push = new PushBroker();

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

            //string message = "globl";
            //reng uesr                                                          fhI1KhYUmu0:APA91bGwKfj18xMUBWF22WvlRetFic8JKizjI-9E7nq6w6G8Z4WAOTN3-3FLDD4Fu5myBumx50I2yAMnym_WOeoP1pXJM8M0yLDq8poqxgo4eSDOQU_FWa0KFZdWFVo0MwGwuYkfsB92
            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("fhI1KhYUmu0:APA91bGwKfj18xMUBWF22WvlRetFic8JKizjI-9E7nq6w6G8Z4WAOTN3-3FLDD4Fu5myBumx50I2yAMnym_WOeoP1pXJM8M0yLDq8poqxgo4eSDOQU_FWa0KFZdWFVo0MwGwuYkfsB92")
                                   .WithJson("{\"message\": \" " + message + " \", \"title\": \" my title\", \"msgcnt\": \"1\", \"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

            push.StopAllServices();
        }
Esempio n. 29
0
 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());
     }
 }
Esempio n. 30
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                        "PushDemo.p12"));
            string ipadtoken = "6f22cc6eaff02281125092987dd6b9dc1242722bb455253ff308f71dab296169";
            string iphoneToken = "5477ac3de431bcf89982c569cb33846285565b7f62b235ad10d8737754b8b81a";

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

            push.RegisterAppleService(settings);

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

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

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

            //GCM

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

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

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

            push.StopAllServices();
        }
Esempio n. 31
0
        public static void Main(string[] args)
        {
            //APNS
            var push = new PushBroker();
            var cert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                        "<specify your .p12 file here>"));

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

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

            push.RegisterAppleService(settings);

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

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

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

            //GCM

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

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

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

            push.StopAllServices();
        }
        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;
                }
            });
        }
Esempio n. 33
0
        private static void SendNotification(string deviceToken, string title, string body, int badgeCount, string sound)
        {
            //Create our push services broker
            var push = new PushBroker();

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

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

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

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

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

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

            AppleNotification notification = new AppleNotification();

            notification.ForDeviceToken(deviceToken);

            AppleNotificationAlert alert = new AppleNotificationAlert ();

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

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

                        notification.WithAlert (alert);

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

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

            push.QueueNotification(notification);

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

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

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

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

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

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

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }
Esempio n. 34
0
        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();
        }
Esempio n. 35
0
		public void Test_StopAll()
		{
			var b = new PushBroker();

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

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

			b.StopAllServices ();

			Assert.AreEqual (b.GetAllRegistrations ().Count (), 0, "Expected 0 Registrations");
		}
Esempio n. 36
0
		public void Test_ApplicationId_And_NotificationType_Registrations()
		{
			var b = new PushBroker ();

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

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

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

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


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

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

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


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

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

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

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

			Assert.AreEqual (b.GetAllRegistrations ().Count (), 0, "Expected 0 Registrations");
		}
Esempio n. 37
0
        static void Main(string[] args)
        {
            Process[] localAll = Process.GetProcesses();
            int p = 1;
            foreach (Process pr in localAll)
            {
                if (pr.ProcessName == "sendNotificationiOS")
                {
                    if (p > 1)
                    {
                        Console.Write("\n\n\n \"sendNotificationiOS.exe\" ya esta en ejecución... será cerrada");
                        System.Threading.Thread.Sleep(3000);
                        Environment.Exit(0);
                    }
                    p++;
                }
            }

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

            var push = new PushBroker();

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

            SqlConnection conn = new SqlConnection(connectionString: conex);

            try
            {
                conn.Open();

                while (true)
                {
                    string type = "";

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

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

                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

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

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

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

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

                        command = new SqlCommand(sql, conn);

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

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

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

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

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

                            }
                            finally
                            {

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

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

            }
            catch (Exception ex)
            {
                conn.Close();
                Console.Write(ex.Message);
                push.StopAllServices();
            }
        }
Esempio n. 38
0
        protected void btnPush_Click(object sender, EventArgs e)
        {
            //Create our push services broker
            var push = new PushBroker();
            try
            {
                if (ddlBids.SelectedItem.Value != null && Convert.ToInt32(ddlBids.SelectedItem.Value) != 0)
                {
                    //Wire up the events for all the services that the broker registers
                    push.OnNotificationSent += NotificationSent;
                    push.OnNotificationFailed += NotificationFailed;

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

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

                    push.RegisterWindowsPhoneService();

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

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

                push = null;
            }
        }
Esempio n. 39
0
        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();
        }
Esempio n. 40
0
        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();
            }
        }
Esempio n. 41
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();
        }
Esempio n. 42
0
        private static void PushIOS(string mensaje, string deviceToken)
        {
            //ejemplo de deviceToken c9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc

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

            //Create our push services broker
            var push = new PushBroker();

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

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

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

            //Stop and wait for the queues to drains
            push.StopAllServices();
        }
Esempio n. 43
0
 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();
     }
 }
Esempio n. 44
0
        static void Main(string[] args)
        {
            Process[] localAll = Process.GetProcesses();
            int p = 1;
            foreach (Process pr in localAll)
            {
                if (pr.ProcessName == "sendNotificationiOS")
                {
                    if (p > 1)
                    {
                        Console.Write("\n\n\n \"sendNotificationiOS.exe\" ya esta en ejecución... será cerrada");
                        System.Threading.Thread.Sleep(3000);
                        Environment.Exit(0);
                    }
                    p++;
                }
            }

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

            var push = new PushBroker();

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

            SqlConnection conn = new SqlConnection(connectionString: conex);

            try
            {
                conn.Open();

                while (true)
                {
                    string type = "";

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

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

                    SqlCommand command = new SqlCommand(sqlSelectSchedule, conn);

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

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

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

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

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

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

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

                    if (type != "")
                    {

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

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

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

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

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

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

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

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

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

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

            //                                    }
            //                                }
            //                            }

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

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

            //                                    }
            //                        }

                        int i = 0;

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

                        command = new SqlCommand(sql, conn);

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

                        push.StopAllServices(true);

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

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

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

                            // push.StopAllServices();

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

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

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

                            }
                            finally
                            {

                            }

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

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

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

            }
            catch (Exception ex)
            {
                conn.Close();
                Console.Write(ex.Message);
                string body = "\n Error: " + ex.Message + " \n hora: " + DateTime.Now.ToString();
                Emails.Email.Enviarcorreo("Error envio de push iOS BBVA", "*****@*****.**", body, "Error");
                System.Threading.Thread.Sleep(7000);
                push.StopAllServices(true);
                Environment.Exit(0);
            }
        }