public void SendNotification(string deviceToken, string notificationMsg, int platform, int bageCount) { DevicePlatform type = (DevicePlatform)platform; if (type == DevicePlatform.iOS) { try { //var appleCertificate = File.ReadAllBytes("E:\\APNSDistCertificate.p12"); //_push.RegisterAppleService(new ApplePushChannelSettings(true,appleCertificate, "PowerfulP1234")); _push.QueueNotification(new AppleNotification(deviceToken) .WithAlert(notificationMsg) .WithBadge(bageCount) .WithSound("default")); } catch (Exception ex) { throw ex; } } else if (type == DevicePlatform.Android) { _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken) .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}")); } }
/// <summary> /// Notifies the toi os. /// </summary> /// <param name="devices">The devices.</param> /// <param name="announcement">The announcement.</param> private void NotifyToiOS(IList <DeviceRegistryModel> devices, string notificationToken, PageItemModel announcement) { try { var appleCert = File.ReadAllBytes(Path.Combine (AppDomain.CurrentDomain.BaseDirectory, this.APNSCertificatePath)); this._broker.RegisterAppleService(new ApplePushChannelSettings (!this.APNSUseSandBox, appleCert, this.APNSCertificatePassword, true)); foreach (var device in devices) { _broker.QueueNotification(new AppleNotification() .ForDeviceToken(device.DeviceId) .WithAlert(new AppleNotificationAlert() { LaunchImage = announcement.PageItemImageUrl, Body = announcement.PageHeaderText }) .WithCustomItem(PageItemId, announcement.PageItemId) .WithCustomItem(NotificationToken, notificationToken) .WithBadge(GetUnreadNotification(device)) .WithSound("default")); } } catch (Exception ex) { ex.ExceptionValueTracker(devices, announcement); } }
public void SendPushNotification(int DeviceType, string DeviceToken, string Message, string Data, Guid ID) { var push = new PushBroker(); if (DeviceType == 1) { var obj = new { message = Message, data = Data, Id = ID }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(obj); push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyC-TbyCQ9HdAuYAJm0-gJZFQG4kTgBJ4Dg")); push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(DeviceToken) .WithJson(json) ); } else if (DeviceType == 2) { var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/mobie_development.p12")); push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "mobie1234")); push.QueueNotification(new AppleNotification() .ForDeviceToken(DeviceToken) .WithAlert(Message) .WithBadge(1) .WithSound("sound.caf") .WithCustomItem("data", Data) .WithCustomItem("message", Message) .WithCustomItem("Id", ID) ); } }
private void PushIos(IEnumerable <NotiUserSubscription> pushes, string objectId, string type, string message, int?badge) { //cut length based on utf //ios can get only 256 bytes total (2k for ios8) var oldLen = message.Length; message = message.Utf8Substring(150); if (message.Length != oldLen) { message += "..."; } foreach (var push in pushes) { var noti = new AppleNotification { DeviceToken = push.Token, }; noti.Payload.Alert.Body = message; noti.Payload.Badge = badge; noti.Payload.AddCustom("objectId", objectId); noti.Payload.AddCustom("type", type); noti.Payload.AddCustom("time", DateTime.UtcNow.ToString("s")); pushBroker.QueueNotification(noti); } }
public void SendApplePushMessage(string deviceToken, string msg, string customItemKey = null, params object[] customItemValues) { Console.WriteLine("Sending Apple Push Notification message: " + msg); Console.WriteLine(" to device token: {0}", deviceToken); /* * if (appleDeviceToken.Equals( * "20b6a421eb15ba4ad9556b4d74d8654c1da9529bb071236152660fb751fc0dad", * StringComparison.CurrentCultureIgnoreCase)) * { * System.Diagnostics.Debug.WriteLine("OKKKK"); * } */ if (String.IsNullOrWhiteSpace(customItemKey)) { push.QueueNotification(new AppleNotification() .ForDeviceToken(deviceToken) .WithAlert(msg) .WithSound("default") .WithBadge(1) ); } else { push.QueueNotification(new AppleNotification() .ForDeviceToken(deviceToken) .WithAlert(msg) .WithCustomItem(customItemKey, customItemValues) .WithSound("default") .WithBadge(1) ); } }
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(); }
public void NotifyAndroidUser(string token, string json, NotificationType type) { if (_pushBroker == null) { Configure(); } //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! var noti = new GcmNotification(); //noti.DryRun = true; //PushBroker.QueueNotification(noti.ForDeviceRegistrationId(token).WithJson("{\"alert\":\"" + message + "\",\"badge\":6, \"type\":\"" + type.ToString() + "\"}")); _pushBroker.QueueNotification(noti.ForDeviceRegistrationId(token).WithJson(json)); }
//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!"; }
[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(); }
/// <summary> /// Sends notifications to the specified device token and device platform . /// </summary> /// <param name="notificationType">An enum specifying the notification type.</param> /// <param name="devicePlatform">An enum specifying the device platform.</param> /// <param name="deviceToken">A string containing the device token.</param> /// <param name="data">A dictionary containing the notification data.</param> public void SendNotification() { //string dToken = "69b81fdb67b24b8141f4a4539a558ffe8b19216de0d8ea2985dc1ca1653e75ef"; //var appleCert = System.IO.File.ReadAllBytes(@"E:\Zohaib\Projects\Neeo\Services\Certificate\apn_identity.p12"); //_push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "PowerfulP1234")); //_push.QueueNotification(new AppleNotification() // .ForDeviceToken(dToken) // .WithAlert("Hello World!") // .WithBadge(7) // .WithSound("default")); //Thread.Sleep(10000); //------------------------- // WINDOWS NOTIFICATIONS //------------------------- //Configure and start Windows Notifications _push.RegisterWindowsService(new WindowsPushChannelSettings("POWERFULPALLTD.Neeo", "ms-app://s-1-15-2-1027086546-3793768442-914081366-159525117-234043670-2279954648-2289932992", "zwj31+N0gDU2gFwXXTSFN4wrLkGtKZ1/")); //Fluent construction of a Windows Toast Notification _push.QueueNotification(new WindowsToastNotification() .AsToastText01("Hy i am WNS") .ForChannelUri("https://db3.notify.windows.com/?token=AwYAAAC2cuRUeNPTE1OQAAwC1Lmb5BAD98Mk02%2fGY1HvP360VaRtVQqTWRVHWWfJY6RYwzeUICclQbT2nYKGRui18FGlI%2bM9zQW2vqcb7crbULg4GI7XvrSeJTwdKq9k9waOxAs%3d")); Thread.Sleep(20000); }
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(); }
/// <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."); }
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(); } }
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(); }
public static ResultPush Ios(IosMessage iosMessage) { ResultPush resultPush = new ResultPush(); X509Certificate2 certificate = new X509Certificate2(File.ReadAllBytes(GetConfig.Certificate.IOS), GetConfig.Certificate.IOSPassword); var appleCert = File.ReadAllBytes(GetConfig.Certificate.IOS); PushBroker push = Pusher(resultPush); push.RegisterAppleService(new ApplePushChannelSettings(false, certificate)); AppleNotificationPayload appleNotificationPayload = new AppleNotificationPayload(iosMessage.Alert, iosMessage.Badge.Value, iosMessage.Sound.ToString()); var appleNotification = new AppleNotification() .ForDeviceToken(iosMessage.DeviceToken) .WithPayload(appleNotificationPayload); if (iosMessage.Sound.HasValue) { appleNotification.WithSound(iosMessage.Sound.ToString()); } if (iosMessage.Badge.HasValue) { appleNotification.WithBadge(iosMessage.Badge.Value); } push.QueueNotification(appleNotification); return(resultPush); }
static void Main(string[] args) { //Create our service var push = new PushBroker(); //Wire up the events push.OnNotificationSent += NotificationSent; push.OnNotificationFailed += NotificationFailed; //------------------------- // APPLE NOTIFICATIONS //------------------------- //Configure and start Apple APNS // IMPORTANT: Make sure you use the right Push certificate. Apple allows you to generate one for connecting to Sandbox, // and one for connecting to Production. You must use the right one, to match the provisioning profile you build your // app with! var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../id4test_push_aps_development.p12")); //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server // (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false') // If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server // (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true') push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "WEIWEI")); //Extension method //Fluent construction of an iOS notification //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate // for registered for remote notifications is called, and the device token is passed back to you push.QueueNotification(new AppleNotification() .ForDeviceToken("cde6d75a0fc144b2bd30e10e15855376e4b53d793e6ccf9495787df19ace48d4") .WithAlert("Hello World!") .WithBadge(7) .WithSound("sound.caf")); //Console.ReadKey(); Console.ReadLine(); }
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(); }
public bool Send(WindowsPhoneApiNotificationPayLoad payLoad) { HookEvents(PushBroker); try { PushBroker.RegisterService <WindowsPhoneNotification>(new WindowsPhonePushService()); var notification = new WindowsPhoneToastNotification() .ForEndpointUri(new Uri(payLoad.Token)) .ForOSVersion(WindowsPhoneDeviceOSVersion.MangoSevenPointFive) .WithBatchingInterval(BatchingInterval.Immediate) .WithNavigatePath(payLoad.NavigationPath) .WithText1(payLoad.Message) .WithText2(payLoad.TextMessage2); PushBroker.QueueNotification(notification); } finally { StopBroker(); } return(true); }
static void Main(string[] args) { //Create our push services broker var push = new PushBroker(); var cert = File.ReadAllBytes(@"E:\Projects\PushMessage\Ysd.ApplicationInterface\App_Data\ApplePushCertDev.p12"); push.RegisterAppleService(new ApplePushChannelSettings(false, cert, "your password")); var payload = new AppleNotificationPayload() { Badge = 7, Alert = new AppleNotificationAlert() { Body = "Hello " + Guid.NewGuid(), Title = "my title", LocalizedArgs = new List<object> { "Jenna", "Frank" } }, Sound = "chime.aiff" }; push.QueueNotification( new AppleNotification("74b14f0ff695f71bb0a34925aada53f6eadcfe824bf461959403851e5f85b43d", payload)); Console.WriteLine("Queue Finished, press return to exit..."); Console.ReadLine(); }
/// <summary> /// sending push to IoS /// </summary> /// <param name="deviceRegistrationId"></param> /// <param name="pushNotifyType"></param> /// <param name="pushInformation"></param> private void SendPushToIoS(PushNotificationData pushData) { var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Certificates/Certificates.p12")); m_broker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "")); m_broker.QueueNotification(new AppleNotification().ForDeviceToken(pushData.DevicePushToken).WithAlert(pushData.Message).WithBadge(1)); }
public ActionResult ApplePust(string message) { List<string> deviceToken = ViewBag.deviceTokens; //创建推送对象 var pusher = new PushBroker(); pusher.OnNotificationSent += pusher_OnNotificationSent;//发送成功事件 pusher.OnNotificationFailed += pusher_OnNotificationFailed;//发送失败事件 pusher.OnChannelCreated += pusher_OnChannelCreated; pusher.OnChannelDestroyed += pusher_OnChannelDestroyed; pusher.OnChannelException += pusher_OnChannelException; pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged; pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired; pusher.OnNotificationRequeue += pusher_OnNotificationRequeue; pusher.OnServiceException += pusher_OnServiceException; //注册推送服务 byte[] certificateData = System.IO.File.ReadAllBytes(Server.MapPath("/PushSharpApns/PushSharp.Apns.Production.p12")); pusher.RegisterAppleService(new ApplePushChannelSettings(certificateData, "123")); foreach (string token in deviceToken) { //给指定设备发送消息 pusher.QueueNotification(new AppleNotification() .ForDeviceToken(token) .WithAlert(message) .WithBadge(1) .WithSound("default")); } return View(); }
public Stream SendMessage(Stream messageBody) { try { var doc = new XmlDocument(); doc.Load(messageBody); var msg = new PushMessage(doc, _solution.Name); var push = new PushBroker(); string result = ""; if (msg.HasGcmRecipients) { push.RegisterGcmService(new GcmPushChannelSettings(AndroidServerKey)); string json = "{\"alert\":\"" + msg.Data + "\"}"; foreach (string token in msg.GcmTokens) { push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(token).WithJson(json)); } result += "Android: ok; "; } if (msg.HasApnsRecipients) { var appleCert = Convert.FromBase64String(IosProductionCertificate); push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "h2o+c2h5oh")); foreach (string token in msg.ApnsTokens) { push.QueueNotification(new AppleNotification() .ForDeviceToken(token) .WithAlert(msg.Data) .WithSound("sound.caf")); } result += "IOS: ok; "; } return(Common.Utils.MakeTextAnswer(result)); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e)); } }
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(); }
static void Main(string[] args) { var push = new PushBroker(); //Wire up the events for all the services that the broker registers push.OnNotificationSent += NotificationSent; push.OnChannelException += ChannelException; push.OnServiceException += ServiceException; push.OnNotificationFailed += NotificationFailed; push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired; push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged; push.OnChannelCreated += ChannelCreated; push.OnChannelDestroyed += ChannelDestroyed; //------------------------------------------------ //IMPORTANT NOTE about Push Service Registrations //------------------------------------------------ //Some of the methods in this sample such as 'RegisterAppleServices' depend on you referencing the correct //assemblies, and having the correct 'using PushSharp;' in your file since they are extension methods!!! // If you don't want to use the extension method helpers you can register a service like this: //push.RegisterService<WindowsPhoneToastNotification>(new WindowsPhonePushService()); //If you register your services like this, you must register the service for each type of notification //you want it to handle. In the case of WindowsPhone, there are several notification types! var appleCert = @"C:\apns_prod_cert.p12"; push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "pass1234")); //Extension method DateTime dt = DateTime.UtcNow; List <string> tokens = GetTokens(); foreach (string token in tokens) { push.QueueNotification(new AppleNotification() .ForDeviceToken(token) //.WithAlert("Hello World!") .WithBadge(1)); //.WithSound("sound.caf")); } Console.WriteLine("Waiting for Queue to Finish..."); //Stop and wait for the queues to drains push.StopAllServices(); SetLastRun(dt); Console.WriteLine("Queue Finished, press return to exit..."); //Console.ReadLine(); }
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(); }
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(); }
/// <summary> /// Push data payload to a <paramref name="topic"/>. /// </summary> /// <param name="push"></param> /// <param name="topic">Topic to send to</param> /// <param name="data">Data payload to send</param> /// <param name="collapse">Collapse key to use</param> private static void PushTopics(PushBroker push, string topic, Dictionary <string, string> data, string collapse) { foreach (var pair in data) { push.QueueNotification( new GcmNotification().ForDeviceRegistrationId("/topics/" + topic) .WithCollapseKey(collapse) .WithData(new Dictionary <string, string> { { pair.Key, pair.Value } })); } }
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(); }
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(); }
public void testPush() { using(var push = new PushBroker()) { //**** iOS Notification ****** //Establish the connection to your certificates. Here we make one for dev and another for production byte[] appleCertificate = null; //appleCertificate = Properties.Resources.DEV_CERT_NAME; //appleCertificate = Properties.Resources.PROD_CERT_NAME; //If the file exists, go ahead and use it to send an apple push notification if (appleCertificate != null) { //Give the apple certificate and its password to the push broker for processing push.RegisterAppleService(new ApplePushChannelSettings(appleCertificate, "password")); //Queue the iOS push notification push.QueueNotification(new AppleNotification() .ForDeviceToken("DEVICE_TOKEN_HERE") .WithAlert("Hello World!") .WithBadge(7) .WithSound("sound.caf")); } //********************************* //**** Android Notification ****** //Register the GCM Service and sending an Android Notification with your browser API key found in your google API Console for your app. Here, we use ours. push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyD3J2zRHVMR1BPPnbCVaB1D_qWBYGC4-uU")); //Queue the Android notification. Unfortunately, we have to build this packet manually. push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE_REGISTRATION_ID") .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}")); //********************************* } }
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(); }
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 SendPushMessage(string user_id, string msg, string head) { //Create our push services broker var push = new PushBroker(); MyPush p = MyPush.GetPushInfo(user_id); push.RegisterGcmService(new GcmPushChannelSettings(WebConfigurationManager.AppSettings["apiKey"])); push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(p.Push_str) .WithJson("{\"message\": \" " + msg + " \", \"title\": \" " + head + " \"}")); //Stop and wait for the queues to drains push.StopAllServices(); }
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(); }
public void testPush() { using (var push = new PushBroker()) { //**** iOS Notification ****** //Establish the connection to your certificates. Here we make one for dev and another for production byte[] appleCertificate = null; //appleCertificate = Properties.Resources.DEV_CERT_NAME; //appleCertificate = Properties.Resources.PROD_CERT_NAME; //If the file exists, go ahead and use it to send an apple push notification if (appleCertificate != null) { //Give the apple certificate and its password to the push broker for processing push.RegisterAppleService(new ApplePushChannelSettings(appleCertificate, "password")); //Queue the iOS push notification push.QueueNotification(new AppleNotification() .ForDeviceToken("DEVICE_TOKEN_HERE") .WithAlert("Hello World!") .WithBadge(7) .WithSound("sound.caf")); } //********************************* //**** Android Notification ****** //Register the GCM Service and sending an Android Notification with your browser API key found in your google API Console for your app. Here, we use ours. push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyD3J2zRHVMR1BPPnbCVaB1D_qWBYGC4-uU")); //Queue the Android notification. Unfortunately, we have to build this packet manually. push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE_REGISTRATION_ID") .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}")); //********************************* } }
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(); }
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(); }
protected virtual void QueueNotification(PushBroker push,IJobExecutionContext context) { ILog log = LogManager.GetLogger(typeof(ApnsNotificationJob)); int cursor = 0; int size = JobConfig.DEFAULT_PAGE_SIZE; int successCount = 0; DateTime startDate = DateTime.Today; DateTime endDate = startDate.AddDays(1); Stopwatch sw = new Stopwatch(); sw.Start(); using (var db = new YintaiHangzhouContext("YintaiHangzhouContext")) { var prods = (from p in db.Promotions where (p.StartDate >= startDate && p.StartDate < endDate) && p.Status == 1 select p).OrderByDescending(p=>p.IsTop).ThenByDescending(p=>p.CreatedDate).FirstOrDefault(); if (prods != null) { var devices = (from d in db.DeviceLogs where d.Status == 1 select new {DeviceToken = d.DeviceToken }).Distinct(); int totalCount = devices.Count(); while (cursor < totalCount) { var pageDevices = devices.OrderBy(o=>o.DeviceToken).Skip(cursor).Take(size); foreach (var device in pageDevices) { push.QueueNotification(new AppleNotification() .ForDeviceToken(device.DeviceToken) .WithAlert(prods.Name) .WithBadge(1) .WithCustomItem("from",JsonConvert.SerializeObject(new {targettype=(int)PushSourceType.Promotion,targetvalue=prods.Id.ToString()})) .WithSound("sound.caf")); successCount++; } cursor += size; } } } sw.Stop(); log.Info(string.Format("{0} notifications in {1} => {2} notis/s", successCount, sw.Elapsed, successCount / sw.Elapsed.TotalSeconds)); }
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(); }
protected virtual void QueueNotification(PushBroker push, IJobExecutionContext context) { ILog log = LogManager.GetLogger(typeof(ApnsNotificationJob)); int cursor = 0; int size = 100; int successCount = 0; DateTime startDate = DateTime.Today; DateTime endDate = startDate.AddDays(1); Stopwatch sw = new Stopwatch(); sw.Start(); using (var db = new YintaiHangzhouContext("YintaiHangzhouContext")) { var prods = (from p in db.Promotions where (p.StartDate >= startDate && p.StartDate < endDate) && p.Status == 1 select p).OrderByDescending(p => p.IsTop).ThenByDescending(p => p.CreatedDate).FirstOrDefault(); if (prods != null) { var devices = (from d in db.DeviceLogs where d.Status == 1 select new { DeviceToken = d.DeviceToken }).Distinct(); int totalCount = devices.Count(); while (cursor < totalCount) { var pageDevices = devices.OrderBy(o => o.DeviceToken).Skip(cursor).Take(size); foreach (var device in pageDevices) { push.QueueNotification(new AppleNotification() .ForDeviceToken(device.DeviceToken) .WithAlert(prods.Name) .WithBadge(1) .WithCustomItem("from", JsonConvert.SerializeObject(new { targettype = (int)PushSourceType.Promotion, targetvalue = prods.Id.ToString() })) .WithSound("sound.caf")); successCount++; } cursor += size; } } } sw.Stop(); log.Info(string.Format("{0} notifications in {1} => {2} notis/s", successCount, sw.Elapsed, successCount / sw.Elapsed.TotalSeconds)); }
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(); }
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(); }
public static ResultPush Android(AndroidMessage androidMessage) { ResultPush resultPush = new ResultPush(); if (androidMessage != null) { PushBroker push = Pusher(resultPush); push.RegisterGcmService(new GcmPushChannelSettings(GetConfig.Key.Android)); var jsonObject = JsonConvert.SerializeObject(androidMessage, SerializerSettings()); push.QueueNotification(new GcmNotification() .ForDeviceRegistrationId(androidMessage.DeviceTokens) .WithJson(jsonObject)); } return(resultPush); }
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; }
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; } }); }
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; } }
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(); } }
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(); }
public Stream SendMessage(Stream messageBody) { try { var doc = new XmlDocument(); doc.Load(messageBody); var msg = new PushMessage(doc, _solution.Name); var push = new PushBroker(); string result = ""; if (msg.HasGcmRecipients) { push.RegisterGcmService(new GcmPushChannelSettings(AndroidServerKey)); string json = "{\"alert\":\"" + msg.Data + "\"}"; foreach (string token in msg.GcmTokens) push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(token).WithJson(json)); result += "Android: ok; "; } if (msg.HasApnsRecipients) { var appleCert = Convert.FromBase64String(IosProductionCertificate); push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "h2o+c2h5oh")); foreach (string token in msg.ApnsTokens) { push.QueueNotification(new AppleNotification() .ForDeviceToken(token) .WithAlert(msg.Data) .WithSound("sound.caf")); } result += "IOS: ok; "; } return Common.Utils.MakeTextAnswer(result); } catch (Exception e) { return Common.Utils.MakeExceptionAnswer(e); } }
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(); }
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(); } }
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); } }
protected override void QueueNotification(PushBroker push,IJobExecutionContext context) { ILog log = LogManager.GetLogger(typeof(ApnsNotificationCommonJob)); JobDataMap data = context.JobDetail.JobDataMap; var interval = data.GetIntValue("intervalofsec"); int cursor = 0; int size = JobConfig.DEFAULT_PAGE_SIZE; int successCount = 0; var benchDate = DateTime.Now.AddSeconds(-interval); Stopwatch sw = new Stopwatch(); sw.Start(); using (var db = new YintaiHangzhouContext("YintaiHangzhouContext")) { var prods = (from p in db.NotificationLogs where p.CreateDate>= benchDate && p.Status==(int)NotificationStatus.Default select p); if (prods != null) { int totalCount = prods.Count(); while (cursor < totalCount) { var linq = prods.OrderByDescending(p => p.Id).Skip(cursor).Take(size).ToList(); foreach (var l in linq) { try { if (l.SourceType.Value == (int)SourceType.PMessage) { var device = db.PMessages.Where(p => p.Id == l.SourceId) .Join(db.DeviceLogs, o => o.ToUser, i => i.User_Id, (o, i) => new { D = i,U=o }).FirstOrDefault(); if (device==null) continue; push.QueueNotification(new AppleNotification() .ForDeviceToken(device.D.DeviceToken) .WithAlert("新私信...") .WithBadge(1) .WithCustomItem("from", JsonConvert.SerializeObject(new { targettype = (int)PushSourceType.PMessage, targetvalue =device.U.FromUser})) .WithSound("sound.caf")); successCount++; l.NotifyDate = DateTime.Now; l.Status = (int)NotificationStatus.Notified; db.Entry(l).State = System.Data.EntityState.Modified; db.SaveChanges(); } else if (l.SourceType.Value == (int)SourceType.Comment) { // if it's comment, always notify all comments owners of this item var comment = db.Comments.Find(l.SourceId); if (comment == null) continue; var relatedComments = db.Comments.Where(c => c.SourceType == comment.SourceType && c.SourceId == comment.SourceId && c.User_Id != comment.User_Id) .Join(db.DeviceLogs.Where(d => d.User_Id > 0), o => o.User_Id, i => i.User_Id, (o, i) => new { Token = i.DeviceToken }).ToList(); if (comment.SourceType == (int)SourceType.Product) { var product = db.Products.Where(p => p.Id == comment.SourceId && p.RecommendUser != comment.User_Id) .Join(db.DeviceLogs.Where(d => d.User_Id > 0), o => o.CreatedUser, i => i.User_Id, (o, i) => new { Token = i.DeviceToken }).FirstOrDefault(); if (product != null) relatedComments.Add(new { Token = product.Token }); } else if (comment.SourceType == (int)SourceType.Promotion) { var promotion = db.Promotions.Where(p => p.Id == comment.SourceId && p.RecommendUser != comment.User_Id) .Join(db.DeviceLogs.Where(d => d.User_Id > 0), o => o.CreatedUser, i => i.User_Id, (o, i) => new { Token = i.DeviceToken }).FirstOrDefault(); if (promotion != null) relatedComments.Add(new { Token = promotion.Token }); } foreach (var device in relatedComments.Distinct()) { push.QueueNotification(new AppleNotification() .ForDeviceToken(device.Token) .WithAlert("新评论...") .WithBadge(1) .WithCustomItem("from", JsonConvert.SerializeObject(new { targettype = (int)PushSourceType.SelfComment, targetvalue = comment.SourceId })) .WithSound("sound.caf")); successCount++; } l.NotifyDate = DateTime.Now; l.Status = (int)NotificationStatus.Notified; db.Entry(l).State = System.Data.EntityState.Modified; db.SaveChanges(); } } catch (Exception ex) { log.Info(ex); } } cursor += size; } } } sw.Stop(); log.Info(string.Format("{0} notifications in {1} => {2} notis/s", successCount, sw.Elapsed, successCount / sw.Elapsed.TotalSeconds)); }
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(); } }
internal string SendMessage(int smid, int rmid, string message) { if (IsMemberNotExisting(smid) || IsMemberNotExisting(rmid)) { return MESSAGE_MEMBER_IS_NOT_EXISTING; } MessageQueue messageQueue = new MessageQueue(); messageQueue.message = message; messageQueue.MessageReceiver = GetMember(rmid); messageQueue.MessageSender = GetMember(smid); messageQueue.rmid = rmid; messageQueue.smid = smid; messageQueue.timeStamp = DateTime.Now; GetMessageQueues().Add(messageQueue); try { GetJKLineEntites().SaveChanges(); DisposeJKLineEntities(); string receiverPushToken = messageQueue.MessageReceiver.pushToken; PushBroker push = new PushBroker(); push.RegisterGcmService(new GcmPushChannelSettings("AIzaSyA7dl25oulxDoTpExp9RdAlsCUR-tv61_U")); Dictionary<string, string> pushedMessage = new Dictionary<string, string>(); int unreceiveMessageCount = GetUnreceiveMessageCount(smid, rmid); string jsonString = String.Format("{{\"message\":\"{0}\",\"senderName\":\"{1}\",\"timeStamp\":\"{2}\",\"count\":{3}}}", message, messageQueue.MessageSender.name, messageQueue.timeStamp.ToShortTimeString(), unreceiveMessageCount); push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiverPushToken) .WithJson(jsonString)); return jsonString; } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { System.Diagnostics.Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } GetJKLineEntites().SaveChanges(); return DateTime.Now.ToString(); }