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); }
public static void NotifyIOSUser(string token, string message, NotificationType type) { /// /Fluent construction of an iOS notification ////IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate //// for registered for remote notifications is called, and the device token is passed back to you //------------------------- // APPLE NOTIFICATIONS //------------------------- //Configure and start Apple APNS // IMPORTANT: Make sure you use the right Push certificate. Apple allows you to //generate one for connecting to Sandbox, and one for connecting to Production. You must // use the right one, to match the provisioning profile you build your // app with! var appleCert = File.ReadAllBytes(HostingEnvironment.MapPath(APNSCerticateFile)); //IMPORTANT: If you are using a Development provisioning Profile, you must use // the Sandbox push notification server // (so you would leave the first arg in the ctor of ApplePushChannelSettings as // 'false') // If you are using an AdHoc or AppStore provisioning profile, you must use the //Production push notification server // (so you would change the first arg in the ctor of ApplePushChannelSettings to //'true') var payLoad = new AppleNotificationPayload(); payLoad.AddCustom("NotificationType", NotificationType.MessageAlert); payLoad.AddCustom("Badge", 7); payLoad.AddCustom("DeviceID", token); PushBroker.QueueNotification(new AppleNotification(token, payLoad) //the recipient device id .WithAlert(message) //the message .WithBadge(7) .WithCategory(type.ToString()) .WithSound("sound.caf") ); }
public static AppleNotification WithPasskitUpdate(this AppleNotification n) { var payLoad = new AppleNotificationPayload(); payLoad.AddCustom("aps", string.Empty); n.Payload = payLoad; return(n); }
public void Push(DeviceSubscription subscription, Payload payload) { var context = new PushContext { Subscription = subscription, Payload = payload }; if (OperationContext.Current != null) { context.Callback = OperationContext.Current.GetCallbackChannel <IPushCallback>(); } if (subscription.Channel.PlatformType == PlatformType.Apple) { var notification = new AppleNotification(subscription.SubscriptionId) { Tag = context }; if (payload != null) { var p = new AppleNotificationPayload(); p.Alert = new AppleNotificationAlert { Body = payload.Alert }; p.Badge = payload.Badge; p.Sound = payload.Sound; p.CustomJson = payload.Custom; //https://github.com/caniusq/PushSharp notification.Payload = p; } PushBrokerManager.Broker.QueueNotification(notification, subscription.Channel.ApplicationId); } else if (subscription.Channel.PlatformType == PlatformType.Beyondbit) { var notification = new BeyondBit.PushClientLib.BeyondBitNotification { DeviceToken = subscription.SubscriptionId, Tag = context }; if (payload != null) { var bnp = new BeyondBit.PushClientLib.BeyondbitNotificationPayload(); bnp.Alert = payload.Alert; bnp.Badge = payload.Badge; bnp.Sound = payload.Sound; bnp.CustomJson = payload.Custom; notification.Payload = bnp; } PushBrokerManager.Broker.QueueNotification(notification, subscription.Channel.ApplicationId); } else { throw new NotImplementedException(); } }
public void NotifyIOSUserCustom(string token, string message, NotificationType type, IOSNOtifcationModel requestModel) { /// /Fluent construction of an iOS notification ////IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate //// for registered for remote notifications is called, and the device token is passed back to you //------------------------- // APPLE NOTIFICATIONS //------------------------- //Configure and start Apple APNS // IMPORTANT: Make sure you use the right Push certificate. Apple allows you to //generate one for connecting to Sandbox, and one for connecting to Production. You must // use the right one, to match the provisioning profile you build your // app with! var appleCert = File.ReadAllBytes(HostingEnvironment.MapPath(APNSCerticateFile)); //IMPORTANT: If you are using a Development provisioning Profile, you must use // the Sandbox push notification server // (so you would leave the first arg in the ctor of ApplePushChannelSettings as // 'false') // If you are using an AdHoc or AppStore provisioning profile, you must use the //Production push notification server // (so you would change the first arg in the ctor of ApplePushChannelSettings to //'true') var payLoad = new AppleNotificationPayload(); payLoad.AddCustom("NotificationType", requestModel.Request.NotificationType); payLoad.AddCustom("SenderName", requestModel.Request.SenderName); payLoad.AddCustom("Badge", requestModel.Request.Badge); payLoad.AddCustom("SenderID", requestModel.Request.SenderID); payLoad.AddCustom("Message", requestModel.Request.Message); payLoad.AddCustom("DeviceType", requestModel.DeviceModel.DeviceType); payLoad.AddCustom("ExpertResponse", requestModel.Request.ExpertResponse); payLoad.AddCustom("DeviceToken", requestModel.DeviceModel.DeviceToken); payLoad.AddCustom("WorkOrderScopeID", requestModel.Request.WorkOrderScopeID); payLoad.AddCustom("ExpertID", requestModel.Request.ExpertID); payLoad.AddCustom("ReceiverROle", requestModel.Request.ReceiverRole); if (_pushBroker == null) { Configure(); } //_pushBroker = new PushBroker(); _pushBroker.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, APNSCerticateFilePassword, true)); _pushBroker.QueueNotification(new AppleNotification(token, payLoad) //the recipient device id .WithAlert(message) //the message .WithBadge(requestModel.Request.Badge) .WithCategory(type.ToString()) .WithSound("sound.caf") ); }
public static async Task Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, [NotificationHub(ConnectionStringSetting = "NotificationHubConnectionString", HubName = "%NotificationHubName%")] IAsyncCollector <Notification> notification, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); const string message = "A new software update is available."; NotificationPayloadBase payload = new GcmNotificationPayload(message); await notification.AddAsync(new GcmNotification(JsonConvert.SerializeObject(payload))); payload = new AppleNotificationPayload(message); await notification.AddAsync(new AppleNotification(JsonConvert.SerializeObject(payload))); }
public static async Task SoftwareUpdateNotification( [EventGridTrigger] EventGridEvent eventGridEvent, [NotificationHub(ConnectionStringSetting = "NotificationHubConnectionString", HubName = "%NotificationHubName%")] IAsyncCollector <Notification> notification, ILogger log) { log.LogInformation("EventGridEvent trigger." + $"\n\tId:{eventGridEvent.Id}" + $"\n\tTopic:{eventGridEvent.Topic}" + $"\n\tSubject:{eventGridEvent.Subject}" + $"\n\tType:{eventGridEvent.EventType}" + $"\n\tData:{JsonConvert.SerializeObject(eventGridEvent.Data)}"); // TODO: check event grid data for correct data - and use file version info to embed it in the push payload const string message = "A new software update is available."; NotificationPayloadBase payload = new GcmNotificationPayload(message); await notification.AddAsync(new GcmNotification(JsonConvert.SerializeObject(payload))); payload = new AppleNotificationPayload(message); await notification.AddAsync(new AppleNotification(JsonConvert.SerializeObject(payload))); }
public static AppleNotification WithPayload(this AppleNotification n, AppleNotificationPayload payload) { n.Payload = payload; return(n); }
public static String SendAPNSBroadCast(String message, int baget, bool mute, List <String> devices) { ApplePushChannelSettings setting = new ApplePushChannelSettings(true, KEYPATH, PASS, true); ApplePushService service = new ApplePushService(setting); AppleNotificationPayload payload = new AppleNotificationPayload(); List <String> valids = new List <string>(); List <String> invalids = new List <string>(); if (mute) { payload.Sound = ""; payload.Alert = new AppleNotificationAlert() { Body = "" }; } else { payload.Sound = "default"; payload.Alert = new AppleNotificationAlert() { Body = message }; } payload.Badge = baget; object obj = new object(); int total = 0; service.OnNotificationFailed += (object sender, INotification notification, Exception error) => { lock (obj) { total++; invalids.Add((String)notification.Tag); } Console.WriteLine("Fail / " + notification.Tag + "/ " + total); }; service.OnNotificationSent += (object sender, INotification notification) => { lock (obj) { total++; valids.Add((String)notification.Tag); } Console.WriteLine("Ok / " + total); }; foreach (var item in devices) { AppleNotification sendNotify = new AppleNotification(item, payload); sendNotify.Tag = item; service.QueueNotification(sendNotify); } while (total != devices.Count) { ; } System.Threading.Thread.Sleep(3000); service.Stop(); PushCallBack pushcallback = new APNSCallBack("iOS") { valids = valids, invalids = invalids, success = valids.Count, failure = invalids.Count, Devices = devices }; return(JsonConvert.SerializeObject(pushcallback)); }
/// <summary> /// The main processor method used to process a single push notification, checks if the processing will be an immediate single push or regular thread looping model. /// Looks up for a single (or more if you wish) entity in the databae which has not been processed. /// Puts the fetched unprocessed push notification entity to processing over the Push Sharp API. /// Finally saves the state of processing. /// </summary> /// <param name="databaseContext">The current database context to be used for processing to the database.</param> /// <param name="pushNotification">A single push notification entity to be processed and saved.</param> /// <param name="isDirectSinglePush">Decides wethere the processing will take place immediately for the sent notification or will the method lookup from the database for a first unprocessed push notification.</param> /// <returns>True if all OK, false if not.</returns> public bool ProcessNotification(PushSharpDatabaseContext dbContext, PushNotification pushNotification = null, bool isDirectSinglePush = false) { _databaseContext = dbContext; _isDirectSinglePush = isDirectSinglePush; if (_isDirectSinglePush) { InitBroker(); } On(DisplayMessage, "Checking for unprocessed notifications..."); PushNotification notificationEntity = pushNotification; try { if (notificationEntity != null) { // save a new immediate unprocessed push notification _databaseContext.PushNotification.Add(pushNotification); _databaseContext.SaveChanges(); // reload the entity notificationEntity = _databaseContext.PushNotification .Where(x => x.ID == pushNotification.ID) .Include(x => x.MobileDevice) .Include(x => x.MobileDevice.Client) .FirstOrDefault(); } else // take one latest unprocessed notification, this can be changed to take any set size instead of one { notificationEntity = _databaseContext.PushNotification.FirstOrDefault(s => s.Status == (int)PushNotificationStatus.Unprocessed && s.CreatedAt <= DateTime.Now); } } catch (Exception ex) { On(DisplayErrorMessage, "EX. ERROR: Check for unprocessed notifications: " + ex.Message); SimpleErrorLogger.LogError(ex); } // Process i.e. push the push notification via PushSharp... if (notificationEntity != null) { bool messagePushed = true; On(DisplayStatusMessage, "Processing notification..."); On(DisplayMessage, "ID " + notificationEntity.ID + " for " + notificationEntity.MobileDevice.Client.Username + " -> " + notificationEntity.Message); //--------------------------- // ANDROID GCM NOTIFICATIONS //--------------------------- if (notificationEntity.MobileDevice.SmartphonePlatform == "android") { var gcmNotif = new GcmNotification() { Tag = notificationEntity.ID }; string msg = JsonConvert.SerializeObject(new { message = notificationEntity.Message }); gcmNotif.ForDeviceRegistrationId(notificationEntity.MobileDevice.PushNotificationsRegistrationID) .WithJson(msg); _broker.QueueNotification(gcmNotif); UpdateNotificationQueued(notificationEntity); } ////------------------------- //// APPLE iOS NOTIFICATIONS ////------------------------- else if (notificationEntity.MobileDevice.SmartphonePlatform == "ios") { var appleNotif = new AppleNotification() { Tag = notificationEntity.ID }; var msg = new AppleNotificationPayload(notificationEntity.Message); appleNotif.ForDeviceToken(notificationEntity.MobileDevice.PushNotificationsRegistrationID) .WithPayload(msg) .WithSound("default"); _broker.QueueNotification(appleNotif); UpdateNotificationQueued(notificationEntity); } //---------------------- // WINDOWS NOTIFICATIONS //---------------------- else if (notificationEntity.MobileDevice.SmartphonePlatform.Equals("wp") || notificationEntity.MobileDevice.SmartphonePlatform.Equals("wsa")) { var wNotif = new WindowsToastNotification() { Tag = notificationEntity.ID }; wNotif.ForChannelUri(notificationEntity.MobileDevice.PushNotificationsRegistrationID) .AsToastText02("PushSharp Notification", notificationEntity.Message); _broker.QueueNotification(wNotif); UpdateNotificationQueued(notificationEntity); } else { On(DisplayErrorMessage, "ERROR: Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform); notificationEntity.Status = (int)PushNotificationStatus.Error; notificationEntity.ModifiedAt = DateTime.Now; notificationEntity.Description = "(Processor) Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform; SimpleErrorLogger.LogError(new Exception("EX. ERROR: " + notificationEntity.Description)); messagePushed = false; } try { // Save changes to DB to keep the correct state of messages _databaseContext.SaveChanges(); // bubble out the single push error, else return true to continue iteration if (_isDirectSinglePush) { return(messagePushed); } return(true); } catch (Exception ex) { On(DisplayErrorMessage, "EX. ERROR: Updating notification, DB save failed: " + ex.Message); SimpleErrorLogger.LogError(ex); // bubble out the single push error, else return true to continue iteration if (_isDirectSinglePush) { return(false); } return(true); } finally { if (_isDirectSinglePush) { KillBroker(_databaseContext); } } } else { if (_isDirectSinglePush) { KillBroker(_databaseContext); } // no messages were queued, take a nap... return(false); } }