static async Task TrySendAppleSilentNotification(NotificationHubClient client, ILogger log) { try { log.LogInformation("Sending Silent Apple Push Notifications"); var jsonPayload = JsonConvert.SerializeObject(new ApplePushNotification()); var notification = new AppleNotification(jsonPayload, new Dictionary <string, string> { { "apns-push-type", "background" }, { "apns-priority", "5" } }); var appleNotificationResult = await client.SendNotificationAsync(notification).ConfigureAwait(false); log.LogInformation("Apple Notifications Sent"); } catch (Exception e) { log.LogInformation($"Apple Notification Failed\n{e}"); } }
internal static Notification BuildNotificationFromString(string notificationAsString, NotificationPlatform platform) { Notification notification = null; if (platform == 0) { JObject jobj = JObject.Parse(notificationAsString); Dictionary <string, string> templateProperties = jobj.ToObject <Dictionary <string, string> >(); notification = new TemplateNotification(templateProperties); } else { switch (platform) { case NotificationPlatform.Wns: notification = new WindowsNotification(notificationAsString); break; case NotificationPlatform.Apns: notification = new AppleNotification(notificationAsString); break; case NotificationPlatform.Gcm: notification = new GcmNotification(notificationAsString); break; case NotificationPlatform.Adm: notification = new AdmNotification(notificationAsString); break; case NotificationPlatform.Mpns: notification = new MpnsNotification(notificationAsString); break; } } return(notification); }
public async Task <HttpResponseMessage> SchedulePushNotificationAlert(int userId) { var schedulerepo = new UserTrackingScheduleRepository(); var userrepo = new UserRepository(); var user = userrepo.Get(userId); NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString("<connection string with full access>", "<hub name>"); var schedule = user.UserTrackingSchedules.Where(_ => _.Enabled).FirstOrDefault(); if (schedule != null && schedule.Enabled) { Notification notification = new AppleNotification("{\"aps\":{\"alert\":\"Happy birthday!\"}}"); var scheduledTime = new DateTimeOffset(DateTime.Today.AddDays(schedule.ScheduledDays - 1), new TimeSpan(schedule.ScheduledHours, 0, 0)); var scheduled = await hub.ScheduleNotificationAsync(notification, scheduledTime); schedule.ScheduledNotificationId = scheduled.ScheduledNotificationId; schedulerepo.AddEdit(schedule); } return(Request.CreateResponse(HttpStatusCode.OK)); }
/// <summary> /// Converts the message of this class to Apple Notification /// </summary> /// <returns></returns> public static AppleNotification ConvertToAppleNotification(MobileNotificationMessage message) { AppleNotification appleMessage = new AppleNotification(); appleMessage.DeviceToken = message.DevicePushToken; if (message.TimeToLiveSeconds.HasValue) { if (message.TimeToLiveSeconds.Value != 0) // 0 means instant sending in GCM, but here it just expires the message { appleMessage.Expiration = DateTime.UtcNow.AddSeconds(message.TimeToLiveSeconds.Value); } } appleMessage.Payload = new AppleNotificationPayload(message.Alert, message.Badge, message.Sound); return(appleMessage); //return new AppleNotification() // .ForDeviceToken(this.DevicePushToken) // .WithAlert(this.MessageBody) // .WithBadge(this.Badge) // .WithSound(this.Sound); }
public bool Send(AppleApiNotificationPayLoad payLoad) { HookEvents(PushBroker); try { PushBroker.RegisterService <AppleNotification>(new ApplePushService(new ApplePushChannelSettings(_Settings.CertificateContents, _Settings.CertificatePassword))); var notification = new AppleNotification() .ForDeviceToken(payLoad.Token) .WithAlert(payLoad.Message) .WithSound(payLoad.SoundFile) .WithBadge(payLoad.BadgeNo); PushBroker.QueueNotification(notification); } finally { StopBroker(); } return(true); }
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(); }
/// <summary> /// Logs the notification. /// </summary> /// <param name="notification">The notification.</param> private void LogNotification(INotification notification) { try { Func <AppleNotificationPayload, string, string> parseApplePayload = (payload, key) => payload.CustomItems[key].FirstOrDefault().ToString(); Func <string, string, string> parseAndroidPayload = (payload, key) => { var data = (JObject)JsonConvert.DeserializeObject(payload); return(data[key].Value <string>()); }; NotificationLogModel notificationLog = new NotificationLogModel(); if (notification is GcmNotification) { GcmNotification gcmNotification = (GcmNotification)notification; notificationLog.DeviceId = gcmNotification.RegistrationIds.FirstOrDefault(); notificationLog.NotifiactionToken = parseAndroidPayload(gcmNotification.JsonData, NotificationToken); notificationLog.PageItemId = int.Parse(parseAndroidPayload(gcmNotification.JsonData, PageItemId)); } else if (notification is AppleNotification) { AppleNotification appleNotification = (AppleNotification)notification; notificationLog.DeviceId = appleNotification.DeviceToken; notificationLog.NotifiactionToken = parseApplePayload(appleNotification.Payload, NotificationToken); notificationLog.PageItemId = int.Parse(parseApplePayload(appleNotification.Payload, PageItemId)); } this._notificationLogDataRepository.InsertNotificationLog(notificationLog); } catch (Exception ex) { ex.ExceptionValueTracker(notification); } }
internal static Notification BuildNotificationFromString(string notificationAsString, NotificationPlatform platform) { Notification notification = null; if (platform == 0) { return(BuildTemplateNotificationFromJsonString(notificationAsString)); } else { switch (platform) { case NotificationPlatform.Wns: notification = new WindowsNotification(notificationAsString); break; case NotificationPlatform.Apns: notification = new AppleNotification(notificationAsString); break; case NotificationPlatform.Gcm: notification = new GcmNotification(notificationAsString); break; case NotificationPlatform.Adm: notification = new AdmNotification(notificationAsString); break; case NotificationPlatform.Mpns: notification = new MpnsNotification(notificationAsString); break; } } return(notification); }
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(); }
/// <summary> /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>. /// </summary> /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param> /// <returns>The resulting <see cref="Notification"/>.</returns> protected virtual Notification CreateNotification(IPushMessage message) { if (message == null) { throw new ArgumentNullException("message"); } Notification notification = null; ApplePushMessage apnsPush; WindowsPushMessage wnsPush; MpnsPushMessage mpnsPush; TemplatePushMessage templatePush; if ((wnsPush = message as WindowsPushMessage) != null) { notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers); } else if ((mpnsPush = message as MpnsPushMessage) != null) { notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers); } else if ((apnsPush = message as ApplePushMessage) != null) { DateTime? expiration = null; if (apnsPush.Expiration.HasValue) { expiration = apnsPush.Expiration.Value.DateTime; } notification = new AppleNotification(message.ToString(), expiration); } else if (message is GooglePushMessage) { notification = new GcmNotification(message.ToString()); } else if ((templatePush = message as TemplatePushMessage) != null) { notification = new TemplateNotification(templatePush); } else { throw new InvalidOperationException(GetUnknownPayloadError(message)); } return notification; }
// uses .NET serializer to serialize the message. // here is how it should look like {"aps": {"badge":3, "alert":"This is my alert", "sound":"default"}} private static string ToJson(iPhoneMessage message) { JavaScriptSerializer js = new JavaScriptSerializer(); AppleNotification an = new AppleNotification(); if (!string.IsNullOrEmpty(message.Alert)) { an.Aps.Alert = message.Alert; } else { an.Aps.Alert = string.Empty; } if (!string.IsNullOrEmpty(message.Badge)) { an.Aps.Badge = int.Parse(message.Badge, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(message.Sound)) { an.Aps.Sound = message.Sound; } else { an.Aps.Sound = string.Empty; } string str = js.Serialize(an); return str; }
/// <summary> /// Apns the s_ is payload length valid. /// </summary> public void APNS_IsPayloadLengthValid() { var n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test"); }
static async Task Main(string[] args) { // Getting connection key from the new resource var config = LoadConfiguration(args); var nhClient = NotificationHubClient.CreateClientFromConnectionString(config.PrimaryConnectionString, config.HubName); // Register some fake devices var fcmDeviceId = Guid.NewGuid().ToString(); var fcmInstallation = new Installation { InstallationId = "fake-fcm-install-id", Platform = NotificationPlatform.Fcm, PushChannel = fcmDeviceId, PushChannelExpired = false, Tags = new[] { "fcm" } }; await nhClient.CreateOrUpdateInstallationAsync(fcmInstallation); var appleDeviceId = "00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0"; var apnsInstallation = new Installation { InstallationId = "fake-apns-install-id", Platform = NotificationPlatform.Apns, PushChannel = appleDeviceId, PushChannelExpired = false, Tags = new[] { "apns" } }; await nhClient.CreateOrUpdateInstallationAsync(apnsInstallation); switch ((SampleConfiguration.Operation)Enum.Parse(typeof(SampleConfiguration.Operation), config.SendType)) { case SampleConfiguration.Operation.Broadcast: // Notification groups should be created on client side var outcomeFcm = await nhClient.SendFcmNativeNotificationAsync(FcmSampleNotificationContent); var outcomeSilentFcm = await nhClient.SendFcmNativeNotificationAsync(FcmSampleSilentNotificationContent); var fcmOutcomeDetails = await WaitForThePushStatusAsync("FCM", nhClient, outcomeFcm); var fcmSilentOutcomeDetails = await WaitForThePushStatusAsync("FCM", nhClient, outcomeSilentFcm); PrintPushOutcome("FCM", fcmOutcomeDetails, fcmOutcomeDetails.FcmOutcomeCounts); PrintPushOutcome("FCM Silent ", fcmSilentOutcomeDetails, fcmSilentOutcomeDetails.FcmOutcomeCounts); // Send groupable notifications to iOS var notification = new AppleNotification(AppleSampleNotificationContent); if (!string.IsNullOrEmpty(config.AppleGroupId)) { notification.Headers.Add("apns-collapse-id", config.AppleGroupId); } var outcomeApns = await nhClient.SendNotificationAsync(notification); var outcomeSilentApns = await nhClient.SendAppleNativeNotificationAsync(AppleSampleSilentNotificationContent); var apnsOutcomeDetails = await WaitForThePushStatusAsync("APNS", nhClient, outcomeApns); var apnsSilentOutcomeDetails = await WaitForThePushStatusAsync("APNS", nhClient, outcomeSilentApns); PrintPushOutcome("APNS", apnsOutcomeDetails, apnsOutcomeDetails.ApnsOutcomeCounts); PrintPushOutcome("APNS Silent", apnsSilentOutcomeDetails, apnsSilentOutcomeDetails.ApnsOutcomeCounts); var outcomeWns = await nhClient.SendWindowsNativeNotificationAsync(WnsSampleNotification); var wnsOutcomeDetails = await WaitForThePushStatusAsync("WNS", nhClient, outcomeWns); PrintPushOutcome("WNS", wnsOutcomeDetails, wnsOutcomeDetails.WnsOutcomeCounts); break; case SampleConfiguration.Operation.SendByTag: // Send notifications by tag var outcomeFcmByTag = await nhClient.SendFcmNativeNotificationAsync(FcmSampleNotificationContent, config.Tag ?? "fcm"); var fcmTagOutcomeDetails = await WaitForThePushStatusAsync("FCM Tags", nhClient, outcomeFcmByTag); PrintPushOutcome("FCM Tags", fcmTagOutcomeDetails, fcmTagOutcomeDetails.FcmOutcomeCounts); var outcomeApnsByTag = await nhClient.SendAppleNativeNotificationAsync(AppleSampleNotificationContent, config.Tag ?? "apns"); var apnsTagOutcomeDetails = await WaitForThePushStatusAsync("APNS Tags", nhClient, outcomeApnsByTag); PrintPushOutcome("APNS Tags", apnsTagOutcomeDetails, apnsTagOutcomeDetails.ApnsOutcomeCounts); break; case SampleConfiguration.Operation.SendByDevice: // Send notifications by deviceId var outcomeFcmByDeviceId = await nhClient.SendDirectNotificationAsync(CreateFcmNotification(), config.FcmDeviceId ?? fcmDeviceId); var fcmDirectSendOutcomeDetails = await WaitForThePushStatusAsync("FCM direct", nhClient, outcomeFcmByDeviceId); PrintPushOutcome("FCM Direct", fcmDirectSendOutcomeDetails, fcmDirectSendOutcomeDetails.ApnsOutcomeCounts); var outcomeApnsByDeviceId = await nhClient.SendDirectNotificationAsync(CreateApnsNotification(), config.AppleDeviceId ?? appleDeviceId); var apnsDirectSendOutcomeDetails = await WaitForThePushStatusAsync("APNS direct", nhClient, outcomeApnsByDeviceId); PrintPushOutcome("APNS Direct", apnsDirectSendOutcomeDetails, apnsDirectSendOutcomeDetails.ApnsOutcomeCounts); break; default: Console.WriteLine("Invalid Sendtype"); break; } }
//[HttpGet] //[Route("AppleNotificaion")] private async Task ApplePushNotification(string deviceToken, Notification notification) { try { HttpClient httpClient = new HttpClient(); ApnSettings apnSettings = new ApnSettings() { AppBundleIdentifier = "com.nextleveltraining", P8PrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgZ1ugPXE4Hhh3L1embZmjfUdYBij8HbsrolZnzfR49X6gCgYIKoZIzj0DAQehRANCAARbCwj0VnMCOzw/Tyx4GsS4W+QN4LLCe6RRgIR/LZBJQqKi0q4XWg/p4Qa6JQAdKOZziemK4/dJZaqH/EFijM1S", P8PrivateKeyId = "FQ6ZXC7U8L", ServerType = ApnServerType.Production, TeamId = "Y77A2C426U" }; AppleNotification appleNotification = new AppleNotification(); appleNotification.Aps.AlertBody = notification.Text; appleNotification.Notification = JsonConvert.SerializeObject(notification); var apn = new ApnSender(apnSettings, httpClient); var result = await apn.SendAsync(appleNotification, deviceToken.Trim()); if (!result.IsSuccess) { ApnSettings devApnSettings = new ApnSettings() { AppBundleIdentifier = "com.nextleveltraining", P8PrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgZ1ugPXE4Hhh3L1embZmjfUdYBij8HbsrolZnzfR49X6gCgYIKoZIzj0DAQehRANCAARbCwj0VnMCOzw/Tyx4GsS4W+QN4LLCe6RRgIR/LZBJQqKi0q4XWg/p4Qa6JQAdKOZziemK4/dJZaqH/EFijM1S", P8PrivateKeyId = "FQ6ZXC7U8L", ServerType = ApnServerType.Development, TeamId = "Y77A2C426U" }; AppleNotification appleNotificationDev = new AppleNotification(); appleNotificationDev.Aps.AlertBody = notification.Text; appleNotificationDev.Notification = JsonConvert.SerializeObject(notification); var apnDev = new ApnSender(devApnSettings, httpClient); var resultDev = await apnDev.SendAsync(appleNotificationDev, deviceToken.Trim()); if (!resultDev.IsSuccess) { var notificationError = result.Error.Reason; var device_Token = deviceToken; var user = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower()); string path = Directory.GetCurrentDirectory(); var num = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString(); var email = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString(); string newPath = path + "\\wwwroot\\ErrorLogFile\\AppleErrorDevices.txt"; using (StreamWriter writer = new StreamWriter(newPath, true)) { writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine("Email : " + email.ToString()); writer.WriteLine("Mobile_No : " + num); writer.WriteLine("Device_Token : " + device_Token.ToString()); writer.WriteLine("Error : " + notificationError.ToString()); writer.WriteLine("Mode : Development"); writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine(); } } else { var notificationError = result.Error.Reason; var device_Token = deviceToken; var user = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower()); string path = Directory.GetCurrentDirectory(); var num = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString(); var email = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString(); string newPath = path + "\\wwwroot\\ErrorLogFile\\AppleWorkingDevices.txt"; using (StreamWriter writer = new StreamWriter(newPath, true)) { writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine("Email : " + email.ToString()); writer.WriteLine("Mobile_No : " + num); writer.WriteLine("Device_Token : " + device_Token.ToString()); writer.WriteLine("Mode : Development"); writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine(); } } } else { var device_Token = deviceToken; var user = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower()); string path = Directory.GetCurrentDirectory(); var num = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString(); var email = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString(); string newPath = path + "\\wwwroot\\ErrorLogFile\\AppleWorkingDevices.txt"; using (StreamWriter writer = new StreamWriter(newPath, true)) { writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine("Email : " + email); writer.WriteLine("Mobile_No : " + num); writer.WriteLine("Device_Token : " + device_Token.ToString()); writer.WriteLine("Mode : Production"); writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine(); } } } catch (Exception ex) { string path = Directory.GetCurrentDirectory(); string newPath = path + "\\wwwroot\\ErrorLogFile\\ErrorLogs.txt"; using (StreamWriter writer = new StreamWriter(newPath, true)) { writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine("Message : " + ex.Message.ToString()); writer.WriteLine("Eception : " + ex.ToString()); writer.WriteLine("-----------------------------------------------------------------------------"); writer.WriteLine(); } } }
private async void btnSend_Click(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; btnRegistrations.Enabled = false; btnSend.Enabled = false; btnRefresh.Enabled = false; btnCreateDelete.Enabled = false; btnCancelUpdate.Enabled = false; if (notificationHubClient == null) { return; } Notification notification = null; string[] tags = null; string tagExpression = null; switch (mainTabControl.SelectedTab.Name) { case TemplateNotificationPage: var properties = NotificationInfo.TemplateProperties.ToDictionary(p => p.Name, p => p.Value); if (properties.Count > 0) { var headers = NotificationInfo.TemplateHeaders.ToDictionary(p => p.Name, p => p.Value); tags = NotificationInfo.TemplateTags.Select(t => t.Tag).ToArray(); tagExpression = txtTemplateTagExpression.Text; notification = new TemplateNotification(properties) {Headers = headers}; } else { writeToLog(NotificationPayloadCannotBeNull, false); } break; case WindowsPhoneNativeNotificationPage: if (!string.IsNullOrWhiteSpace(mpnsPayload)) { var headers = NotificationInfo.MpnsHeaders.ToDictionary(p => p.Name, p => p.Value); tags = NotificationInfo.MpnsTags.Select(t => t.Tag).ToArray(); tagExpression = txtMpnsTagExpression.Text; notification = new MpnsNotification(mpnsPayload, headers); } else { writeToLog(NotificationPayloadCannotBeNull, false); } break; case WindowsNativeNotificationPage: if (!string.IsNullOrWhiteSpace(wnsPayload)) { var headers = NotificationInfo.WnsHeaders.ToDictionary(p => p.Name, p => p.Value); tags = NotificationInfo.WnsTags.Select(t => t.Tag).ToArray(); tagExpression = txtWnsTagExpression.Text; notification = new WindowsNotification(wnsPayload, headers); } else { writeToLog(NotificationPayloadCannotBeNull, false); } break; case AppleNativeNotificationPage: if (!string.IsNullOrWhiteSpace(apnsPayload)) { var serializer = new JavaScriptSerializer(); try { serializer.Deserialize<dynamic>(apnsPayload); } catch (Exception) { writeToLog(PayloadIsNotInJsonFormat); return; } var headers = NotificationInfo.ApnsHeaders.ToDictionary(p => p.Name, p => p.Value); tags = NotificationInfo.ApnsTags.Select(t => t.Tag).ToArray(); tagExpression = txtAppleTagExpression.Text; notification = new AppleNotification(apnsPayload) { Headers = headers }; } else { writeToLog(JsonPayloadTemplateCannotBeNull, false); } break; case GoogleNativeNotificationPage: if (!string.IsNullOrWhiteSpace(gcmPayload)) { var serializer = new JavaScriptSerializer(); try { serializer.Deserialize<dynamic>(gcmPayload); } catch (Exception) { writeToLog(PayloadIsNotInJsonFormat); return; } var headers = NotificationInfo.GcmHeaders.ToDictionary(p => p.Name, p => p.Value); tags = NotificationInfo.GcmTags.Select(t => t.Tag).ToArray(); tagExpression = txtGcmTagExpression.Text; notification = new GcmNotification(gcmPayload) { Headers = headers }; } else { writeToLog(JsonPayloadTemplateCannotBeNull, false); } break; } if (notification == null) { return; } NotificationOutcome notificationOutcome; if (!string.IsNullOrWhiteSpace(tagExpression)) { notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tagExpression); WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags); return; } if (tags.Any()) { notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tags); WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags); return; } notificationOutcome = await notificationHubClient.SendNotificationAsync(notification); WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags); } catch (Exception ex) { writeToLog(ex.Message); } finally { btnRegistrations.Enabled = true; btnSend.Enabled = true; btnRefresh.Enabled = true; btnCreateDelete.Enabled = true; btnCancelUpdate.Enabled = true; Cursor.Current = Cursors.Default; } }
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)); }
public void PushApple(IEnumerable <string> deviceTokens, PushMessage pushmessage) { //if (ConfigurationManager.AppSettings["EnableApplePushNotification"].ToLower() == "no") // return; if (deviceTokens == null) { return; } if (deviceTokens != null && !deviceTokens.Any()) { return; } //try //{ //------------------------- // 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! //So we will use dev certificate if server run under debug mode otherwise use Production certificate var APPLE_CERTIFICATE_PASSWORD = ""; byte[] appleCert = new byte[0]; //#if DEBUG // if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Certificates\\apsDev.p12")) // return; // APPLE_CERTIFICATE_PASSWORD = "******"; // appleCert = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "\\Certificates\\apsDev.p12"); //#else if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Certificates\\apsPro.p12")) { return; } appleCert = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "\\Certificates\\apsPro.p12"); APPLE_CERTIFICATE_PASSWORD = "******"; //#endif //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server // (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false') // If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server // (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true') //#if DEBUG // push.RegisterAppleService(new ApplePushChannelSettings(appleCert, APPLE_CERTIFICATE_PASSWORD, true)); //#else push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, APPLE_CERTIFICATE_PASSWORD, true)); //#endif //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 //var deviceToken = "fa8a40bdaae917919a0965c3f2292f790891cf6d7d3d0973bfdd1b5625c097c1"; foreach (var token in deviceTokens) { var notification = new AppleNotification() .ForDeviceToken(token) .WithAlert(pushmessage.Alert) .WithBadge(pushmessage.Badge) .WithSound(pushmessage.Sound); push.QueueNotification(notification); } push.StopAllServices(); //} //catch(Exception ex) //{ // Console.WriteLine("Push error: " + ex.ToString()); //} }
public void TestNotifications(int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null) { testPort++; int pushFailCount = 0; int pushSuccessCount = 0; int serverReceivedCount = 0; int serverReceivedFailCount = 0; int serverReceivedSuccessCount = 0; var notification = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test"); var len = notification.ToBytes().Length; var server = new TestServers.ApnsTestServer(); server.ResponseFilters.Add(new ApnsResponseFilter() { IsMatch = (identifier, token, payload) => { var id = identifier; Console.WriteLine("Server Received: id=" + id + ", payload= " + payload + ", token=" + token); if (token.StartsWith("b", StringComparison.InvariantCultureIgnoreCase)) { return(true); } return(false); }, Status = ApnsResponseStatus.InvalidToken }); var waitServerFinished = new ManualResetEvent(false); Task.Factory.StartNew(() => { try { server.Start(testPort, len, (success, identifier, token, payload) => { serverReceivedCount++; if (success) { serverReceivedSuccessCount++; } else { serverReceivedFailCount++; } }); } catch (Exception ex) { Console.WriteLine(ex); } waitServerFinished.Set(); }).ContinueWith(t => { var ex = t.Exception; Console.WriteLine(ex); }, TaskContinuationOptions.OnlyOnFaulted); var settings = new ApplePushChannelSettings(false, appleCert, "pushsharp", true); settings.OverrideServer("localhost", testPort); settings.SkipSsl = true; var push = new ApplePushService(settings, new PushServiceSettings() { AutoScaleChannels = false, Channels = 1 }); push.OnNotificationFailed += (sender, notification1, error) => pushFailCount++; push.OnNotificationSent += (sender, notification1) => pushSuccessCount++; for (int i = 0; i < toQueue; i++) { INotification n; if (indexesToFail != null && indexesToFail.Contains(i)) { n = new AppleNotification("bff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test"); } else { n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test"); } push.QueueNotification(n); } push.Stop(); push.Dispose(); server.Dispose(); waitServerFinished.WaitOne(); Console.WriteLine("TEST-> DISPOSE."); Assert.AreEqual(toQueue, serverReceivedCount, "Server - Received Count"); Assert.AreEqual(expectFailed, serverReceivedFailCount, "Server - Failed Count"); Assert.AreEqual(expectSuccessful, serverReceivedSuccessCount, "Server - Success Count"); Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count"); Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count"); }
public static AppleNotification ForDeviceToken(this AppleNotification n, string deviceToken) { n.DeviceToken = deviceToken; return(n); }
public void TestNotifications(int toQueue, int expectSuccessful, int expectFailed, int[] idsToFail = null, bool waitForScaling = false, bool autoScale = false) { var testServer = new ApnsNodeTestServer("http://localhost:8888/"); testServer.Reset(); testServer.Setup(idsToFail ?? new int[] {}); var started = DateTime.UtcNow; int pushFailCount = 0; int pushSuccessCount = 0; AppleNotification.ResetIdentifier(); var settings = new ApplePushChannelSettings(false, appleCert, "pushsharp", true); settings.OverrideServer("localhost", 2195); settings.SkipSsl = true; settings.MillisecondsToWaitBeforeMessageDeclaredSuccess = 5000; var serviceSettings = new PushServiceSettings(); if (!autoScale) { serviceSettings.AutoScaleChannels = false; serviceSettings.Channels = 1; } var push = new ApplePushService(settings, serviceSettings); push.OnNotificationFailed += (sender, notification1, error) => { Console.WriteLine("NOTIFICATION FAILED: " + ((AppleNotification)notification1).Identifier); pushFailCount++; }; push.OnNotificationSent += (sender, notification1) => { pushSuccessCount++; }; push.OnNotificationRequeue += (sender, e) => { Console.WriteLine("REQUEUE: " + ((AppleNotification)e.Notification).Identifier); }; for (int i = 0; i < toQueue; i++) { var n = new AppleNotification("aff441e214b2b2283df799f0b8b16c17a59b7ac077e2867ea54ebf6086e55866").WithAlert("Test"); push.QueueNotification(n); } if (waitForScaling) { while (push.QueueLength > 0) { Thread.Sleep(500); } Console.WriteLine("Sleeping 3 minutes for autoscaling..."); Thread.Sleep(TimeSpan.FromMinutes(3)); Console.WriteLine("Channel Count: " + push.ChannelCount); Assert.IsTrue(push.ChannelCount <= 1); } push.Stop(); push.Dispose(); Console.WriteLine("Avg Queue Wait Time: " + push.AverageQueueWaitTime + " ms"); Console.WriteLine("Avg Send Time: " + push.AverageSendTime + " ms"); var span = DateTime.UtcNow - started; var info = testServer.GetInfo(); Console.WriteLine("Test Time: " + span.TotalMilliseconds + " ms"); Console.WriteLine("Client Failed: {0} Succeeded: {1} Sent: {2}", pushFailCount, pushSuccessCount, toQueue); Console.WriteLine("Server Failed: {0} Succeeded: {1} Received: {2} Discarded: {3}", info.FailedIds.Length, info.SuccessIds.Length, info.Received, info.Discarded); //Assert.AreEqual(toQueue, info.Received, "Server - Received Count"); Assert.AreEqual(expectFailed, info.FailedIds.Length, "Server - Failed Count"); Assert.AreEqual(expectSuccessful, info.SuccessIds.Length, "Server - Success Count"); Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count"); Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count"); }
public static AppleNotification WithTag(this AppleNotification n, object tag) { n.Tag = tag; return(n); }
private async Task SendNotificationsForDevices(List <Device> devices, string message, string type, Dictionary <string, string> payload) { if (devices.Count == 0) { return; } var iosPayload = new AppleNotification { Aps = new ApsPayload { Alert = message, }, Type = type, Params = payload, }; var androidPayload = new FirebaseNotification { Android = new FirebaseAndroidPayload { Notification = new FirebaseAndroidNotification { Body = message, ChannelId = "GENERAL" }, Priority = 10, Data = new FirebasePayload { Type = type, Params = payload } }, Notification = new FirebaseNotificationInfo { Body = message } }; var iOSDevices = devices.Where(d => d.Platform == 1).ToList(); using var apn = new ApnSender( settings.Connection.ApplePushKey, settings.Connection.ApplePushKeyId, settings.Connection.ApplePushTeamId, settings.Connection.ApplePushBundleId, ApnServerType.Production ); await Task.WhenAll(iOSDevices.Select(device => Policy .HandleResult <ApnsResponse>(r => !r.IsSuccess) .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, (exception, timeSpan) => { var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture); Logger.LogWarning($"Failed to send iOS notification to device id {device.Token} in {time}: {exception?.Result?.Error?.Reason}"); }) .ExecuteAsync(() => apn.SendAsync(iosPayload, device.Token)) ).ToArray()) .ConfigureAwait(false); var androidDevices = devices.Where(d => d.Platform == 2).ToList(); using var fcm = new FcmSender(settings.Connection.FirebaseServerKey, settings.Connection.FirebaseSenderId); await Task.WhenAll(androidDevices.Select(device => Policy .HandleResult <FcmResponse>(r => r.Failure > 0) .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, (_, timeSpan) => { var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture); Logger.LogWarning($"Failed to send Android notification to device id {device.Token} in {time}"); }) .ExecuteAsync(() => fcm.SendAsync(device.Token, androidPayload)) ).ToArray()) .ConfigureAwait(false); }
/// <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); } }
public ActionResult Approve(int ID) { var actionCodes = RoleModuleMappingService.Instance.GetActionCodesOfModule(User.Identity.Name, ModuleRoleConstants.Module_LeaveRequest); var hasViewAccess = actionCodes.Data.Contains(ModuleRoleConstants.ActionView); var hasUpdateAccess = actionCodes.Data.Contains(ModuleRoleConstants.ActionUpdate); if (!hasViewAccess || !hasUpdateAccess) { this.ShowMessage(false, "", ModuleRoleConstants.NoAccessErrorMsg); return(View("Index")); } ViewBag.Title = "Leave Approval"; var model = new List <LeaveApplicationObj>(); bool isSuccess = false; try { var result = LeaveService.Instance.ApproveLeaveApplication(ID); if (result.IsSuccess) { isSuccess = true; ViewBag.IsShowSuccessfullMessage = true; ViewBag.Message = string.Format("Leave application {0} to {1} has been approved.", result.Data.StartDate.ToString("yyyy-MM-dd"), result.Data.EndDate.ToString("yyyy-MM-dd")); var leaveRecord = LeaveService.Instance.GetLeaveApplication(ID); if (leaveRecord.IsSuccess) { var broadCastRecord = BroadcastService.Instance.GetBusCaptainGCMID(leaveRecord.Data.PersonnelNumber); var err = GoogleNotification.CallGoogleAPI(broadCastRecord.Data.GcmID, "Leave Approval", ViewBag.Message); var broadcast = new BroadcastController(); bool apnsErr = AppleNotification.Push(broadCastRecord.Data.GcmID, ViewBag.Message); if (err != "") { _log.ErrorFormat("error while doing google notification on leave approval"); } } else { ViewBag.IsShowErrorMessage = true; ViewBag.Message = leaveRecord.ErrorInfo; } } else { ViewBag.IsShowErrorMessage = true; ViewBag.Message = result.ErrorInfo; } } catch (Exception ex) { ViewBag.IsShowErrorMessage = true; ViewBag.Message = this.CleanJavaScriptString(ex.ToString()); _log.Error(ex); } BusCaptainService.Instance.saveActivity(Activities.LeaveApprove.ToString(), User.Identity.Name, "", "", isSuccess, ID); return(View("Index", model)); }
public async Task AddAsync(AppleNotification notification) { }
public static AppleNotification WithPayload(this AppleNotification n, AppleNotificationPayload payload) { n.Payload = payload; return(n); }
public List <RemoteNotificationResult> Send() { foreach (RemoteNotification notif in m_notifications) { PlatformType platformType = PlatformConverter.FromDeviceType(notif.DeviceType); switch (platformType) { case PlatformType.Apple: EnsureiOS(); AppleNotification n = NotificationFactory.Apple(); n.DeviceToken = notif.DeviceToken; n.Payload = new AppleNotificationPayload(); if (!string.IsNullOrEmpty(notif.Message)) { n.Payload.Alert = new AppleNotificationAlert() { Body = notif.Message } } ; if (!string.IsNullOrEmpty(notif.Sound)) { n.Payload.Sound = notif.Sound; } if (!string.IsNullOrEmpty(notif.Action) && notif.Action.Trim().Length > 0) { n.Payload.AddCustom("a", notif.Action); if (notif.Parameters != null && notif.Parameters.Names.Count > 0) { n.Payload.AddCustom("p", notif.Parameters.ToJObject()); } } if (!string.IsNullOrEmpty(notif.Badge)) { int badgeInt; if (int.TryParse(notif.Badge, out badgeInt)) { n.Payload.Badge = badgeInt; } else if (notif.Badge == "!") { n.Payload.Badge = -1; } } if (notif.ExecutionTime != 0) { n.Payload.ContentAvailable = 1; } Service.QueueNotification(n); break; case PlatformType.AndroidGcm: EnsureAndroid(); GcmNotification g = NotificationFactory.Google(); g.RegistrationIds.Add(notif.DeviceToken); g.JsonData = string.Format("{{ \"payload\":\"{0}\",\"action\":\"{1}\",\"parameters\": {2} ,\"executiontime\": {3} ,\"priority\": {4} }}" , notif.Message, notif.Action, notif.Parameters.ToJson(), notif.ExecutionTime.ToString(), notif.Delivery.Priority); g.CollapseKey = "NONE"; Service.QueueNotification(g); break; case PlatformType.WindowsPhone: EnsureWindows(); WindowsNotification w = NotificationFactory.Windows(); w.ChannelUri = notif.DeviceToken; w.Message = notif.Message; w.Title = notif.Title; w.ImageUri = notif.Icon; w.Badge = notif.Badge; w.Sound = notif.Sound; w.Action = notif.Action; w.Parameters = notif.Parameters; w.ExecutionTime = notif.ExecutionTime; Service.QueueNotification(w); break; default: RemoteNotificationResult result = RemoteNotificationResult.ForDevice(notif.DeviceType, notif.DeviceToken); result.ErrorCode = INVALID_DEVICE_TYPE; result.ErrorDescription = GetErrorDescription(INVALID_DEVICE_TYPE); SetResult(result); break; } } Service.StopAllServices(true); return(m_results); }
public static AppleNotification WithExpiry(this AppleNotification n, DateTime expiryDate) { n.Expiration = expiryDate; return(n); }
/// <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(NotificationType notificationType, DevicePlatform devicePlatform, string deviceToken, Dictionary <string, string> data) { int mcrCount = 0; switch (notificationType) { case NotificationType.IM: int badgeCount = 0; string notificationMsg = data[NeeoConstants.Alert]; if (!NeeoUtility.IsNullOrEmpty(notificationMsg) && Int32.TryParse(data[NeeoConstants.Badge], out badgeCount)) { if (notificationMsg.Length > 50) { notificationMsg = notificationMsg.Substring(0, 50) + "..."; } // mcrCount = call to service to get mcr count badgeCount += mcrCount; if (devicePlatform == DevicePlatform.iOS) { if (_iosApplicationDefaultTone == null) { _iosApplicationDefaultTone = ConfigurationManager.AppSettings[NeeoConstants.IosApplicationDefaultTone]; } _push.QueueNotification(new AppleNotification(deviceToken) .WithAlert(notificationMsg) .WithBadge(badgeCount) .WithSound(_iosApplicationDefaultTone) .WithCustomItem(NotificationID, NotificationType.IM.ToString("D"))); } else if (devicePlatform == DevicePlatform.Android) { //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken) // .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}")); } else { //do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; case NotificationType.IncomingSipCall: string callerID; string callName; if (_incomingCallingMsgText == null) { _incomingCallingMsgText = ConfigurationManager.AppSettings[NeeoConstants.IncomingCallingMsgText]; } callerID = data["CallerID"]; if (!NeeoUtility.IsNullOrEmpty(callerID)) { // Get the name of the user from data base. string userProfileName = ""; if (devicePlatform == DevicePlatform.iOS) { if (_actionKeyText == null) { _actionKeyText = ConfigurationManager.AppSettings[NeeoConstants.ActionKeyText]; } if (_iosIncomingCallingTone == null) { _iosIncomingCallingTone = ConfigurationManager.AppSettings[NeeoConstants.IosIncomingCallingTone]; } var i = new AppleNotification(deviceToken) .WithAlert(_incomingCallingMsgText + userProfileName, _actionKeyText) .WithSound(_iosIncomingCallingTone) .WithCustomItem(NotificationID, NotificationType.IncomingSipCall.ToString("D")); _push.QueueNotification(i); } else if (devicePlatform == DevicePlatform.Android) { //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken) // .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}")); } else { // do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; case NotificationType.MCR: if (_mcrMsgText == null) { _mcrMsgText = ConfigurationManager.AppSettings[NeeoConstants.McrMsgText]; } // mcrCount = call to service to get mcr count\ mcrCount = 8; if (devicePlatform == DevicePlatform.iOS) { if (_iosApplicationDefaultTone == null) { _iosApplicationDefaultTone = ConfigurationManager.AppSettings[NeeoConstants.IosApplicationDefaultTone]; } _push.QueueNotification(new AppleNotification(deviceToken) .WithAlert("text") .WithSound(_iosApplicationDefaultTone) .WithCustomItem(NotificationID, NotificationType.MCR.ToString("D"))); } else if (devicePlatform == DevicePlatform.Android) { //_push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(deviceToken) // .WithJson("{\"alert\":\"" + notificationMsg + "\",\"badge\":" + bageCount + ",\"sound\":\"sound.caf\"}")); } else { //do nothing } break; } }