//Envio de notificaciones en iOS private bool SendIosNotifications(string title, string message, IEnumerable <PushRegistration> elements, string rootPath) { var res = true; try { //Obtención de los datos de configuración var pathCert = Path.Combine(rootPath, _settings.Value.IOSCertificatePath); var pass = _settings.Value.IOSPassCertificate; var type = _settings.Value.IOSTypeCertificate; ApnsConfiguration.ApnsServerEnvironment typeofCert = ApnsConfiguration.ApnsServerEnvironment.Production; if (type.ToUpper().Equals("SANDBOX")) { typeofCert = ApnsConfiguration.ApnsServerEnvironment.Sandbox; } var config = new ApnsConfiguration(typeofCert, pathCert, pass); var apnsBroker = new ApnsServiceBroker(config); apnsBroker.Start(); JObject jsonObject; //Payload de iOS jsonObject = JObject.Parse("{ \"aps\" : { \"alert\" : {\"title\" : \"" + title + "\", \"body\" :\"" + message + "\"} }}"); foreach (var pushRegistration in elements) { //Envio de notificación apnsBroker.QueueNotification(new ApnsNotification { DeviceToken = pushRegistration.Token, Payload = jsonObject }); //Gestión de errores apnsBroker.OnNotificationFailed += (notification, exception) => { Debug.WriteLine(exception); }; //Gestión de exito apnsBroker.OnNotificationSucceeded += (notification) => { Debug.WriteLine(notification); }; } apnsBroker.Stop(); } catch (Exception e) { res = false; } return(res); }
public void Start() { var settings = ConfigurationManager.AppSettings; bool isDebug = false; var value = settings["isDebug"]; if (value != null) { isDebug = Convert.ToBoolean(value); } string certFile = "aps.p12"; string certPwd = "aps@zonjli"; value = settings["certFile"]; if (value != null) { certFile = value; } value = settings["certPwd"]; if (value != null) { certPwd = value; } ApnsConfiguration.ApnsServerEnvironment env = isDebug ? ApnsConfiguration.ApnsServerEnvironment.Sandbox : ApnsConfiguration.ApnsServerEnvironment.Production; this.apnsConfig = new ApnsConfiguration(env, certFile, certPwd); double interval = 1000 * 60 * 5; value = settings["pushIntervalMinutes"]; if (value != null) { interval = 1000 * 60 * Convert.ToDouble(value); } this.HandleTimer(); this.timer = new Timer(interval); this.timer.Elapsed += (sender, e) => this.HandleTimer(); this.timer.AutoReset = true; this.timer.Start(); }
public static ApnsConfiguration Config(ApnsConfiguration.ApnsServerEnvironment serverEnvironment) { var currentdirectory = @"D:\ITouchPushService"; // вариант для сервиса byte[] appleCert = default(byte[]); string appleCertPsw = "**********"; ApnsConfiguration config = null; try { appleCert = File.ReadAllBytes(currentdirectory + @"\cert\*******************.p12"); } catch (Exception ex) { string description = $"Не удалось считать файл сертификата по адресу [{currentdirectory}]" + Environment.NewLine + ex.Message; throw new Exception(description, ex); } // Configuration(NOTE: .pfx can also be used here) try { config = new ApnsConfiguration( serverEnvironment, appleCert, appleCertPsw); } catch (Exception ex) { string description = $"Не удалось сконфигурировать соединение к серверу APNS" + Environment.NewLine + ex.Message; throw new Exception(description, ex); } #if DEBUG Console.WriteLine($"Сертификат успешно подцеплен. Настроено на {serverEnvironment}"); #endif return(config); }
private void EnsureApnsStarted() { if (_appleStarted) { return; } try { _appleStarted = true; ApnsConfiguration configuration; #if DEBUG // looks like for now we should specify production even in debug, using sandbox messages are not coming through. const ApnsConfiguration.ApnsServerEnvironment environment = ApnsConfiguration.ApnsServerEnvironment.Production; var certificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _serverSettings.ServerData.APNS.DevelopmentCertificatePath); #else const ApnsConfiguration.ApnsServerEnvironment environment = ApnsConfiguration.ApnsServerEnvironment.Production; var certificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _serverSettings.ServerData.APNS.ProductionCertificatePath); #endif // Apple settings placed next for development purpose. (Crashing the method when certificate is missing.) var appleCert = File.ReadAllBytes(certificatePath); configuration = new ApnsConfiguration(environment, appleCert, _serverSettings.ServerData.APNS.CertificatePassword); _apps.Add(iOSApp, new AppPushBrokers { Apns = new ApnsServiceBroker(configuration) }); _apps[iOSApp].Apns.OnNotificationSucceeded += OnApnsNotificationSucceeded; _apps[iOSApp].Apns.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is ApnsNotificationException) { var x = ex as ApnsNotificationException; // Deal with the failed notification ApnsNotification n = x.Notification; string description = "Message: " + x.Message + " Data:" + x.Data.ToString(); _logger.LogMessage(string.Format("Notification Failed: ID={0}, Desc={1}", n.Identifier, description)); } else if (ex is ApnsConnectionException) { var x = ex as ApnsConnectionException; string description = "Message: " + x.Message + " Data:" + x.Data.ToString(); _logger.LogMessage(string.Format("Notification Failed: Connection exception, Desc={0}", description)); } else if (ex is DeviceSubscriptionExpiredException) { LogDeviceSubscriptionExpiredException((DeviceSubscriptionExpiredException)ex); } else if (ex is RetryAfterException) { LogRetryAfterException((RetryAfterException)ex); } else { _logger.LogMessage("Notification Failed for some (Unknown Reason)"); } // Mark it as handled return(true); }); }; _apps[iOSApp].Apns.Start(); } catch (Exception e) { _logger.LogError(e); } }
public static string SendIOSNotify(List <string> devicetokens, IDictionary <string, object> ios, ApnsConfiguration.ApnsServerEnvironment environment, string cetificatePath, string cetificatePwd) { List <int> result = new List <int>(); var config = new ApnsConfiguration(environment, cetificatePath, cetificatePwd); var broker = new ApnsServiceBroker(config); StringBuilder erromsg = new StringBuilder(); // Wire up events broker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is ApnsNotificationException notificationException) { // Deal with the failed notification var apnsNotification = notificationException.Notification; var statusCode = notificationException.ErrorStatusCode; result.Add((int)statusCode); } else { // Inner exception might hold more useful information like an ApnsConnectionException result.Add(10086); Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}"); } // Mark it as handled return(true); }); }; broker.OnNotificationSucceeded += (notification) => { result.Add(0); }; // Start the broker broker.Start(); foreach (var deviceToken in devicetokens) { var paload = Newtonsoft.Json.JsonConvert.SerializeObject(ios); broker.QueueNotification(new ApnsNotification { DeviceToken = deviceToken, Payload = JObject.Parse(paload), Expiration = DateTime.Now.AddDays(2) }); } broker.Stop(); var response = new { ret_code = 0, result = Newtonsoft.Json.JsonConvert.SerializeObject(result) }; return(Newtonsoft.Json.JsonConvert.SerializeObject(response)); }
public void DoWork() { while (!_shouldStop) { ContadorIntentos++; try { byte[] appleCert = null; if (!File.Exists(CertAppleURL)) { EscribirEnLog("hubo Error : No existe el Certificado iOS"); } else { appleCert = File.ReadAllBytes(CertAppleURL); EscribirEnLog("certificado encontrado:" + "iOS:" + CertAppleURL + ", Pass:"******", GCMKeyCliente: " + GCMKeyCliente + ", GCMKeyEmpresa: " + GCMKeyEmpresa + ", GCMKeyConductor: " + GCMKeyConductor + ", Alerta " + alerta); } foreach (var token in Tokens) { if (!TokensSended.Contains(token.TokenID)) { try { string FBSenderAuthToken = ""; switch (token.TipoAplicacion) { case Aplicacion.Usuario: FBSenderAuthToken = GCMKeyCliente; break; case Aplicacion.Conductor: FBSenderAuthToken = GCMKeyConductor; break; case Aplicacion.Administrador: FBSenderAuthToken = GCMKeyCliente; break; case Aplicacion.Encargado: FBSenderAuthToken = GCMKeyEmpresa; break; default: FBSenderAuthToken = GCMKeyCliente; break; } switch (token.TipoDispositivo) { case Dispositivo.Apple: if (appleCert != null) { ApnsConfiguration.ApnsServerEnvironment ambiente = ApplePushProduccion ? ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox; var configApns = new ApnsConfiguration(ambiente, appleCert, CertApplePass, false); apnsPush = new ApnsServiceBroker(configApns); apnsPush.OnNotificationFailed += apnsPush_OnNotificationFailed; apnsPush.OnNotificationSucceeded += apnsPush_OnNotificationSucceeded; apnsPush.Start(); apnsPush.QueueNotification((ApnsNotification)alerta.Notificacion(token)); apnsPush.Stop(); } break; case Dispositivo.Android: var configGCM = new GcmConfiguration(FBSenderAuthToken); configGCM.OverrideUrl("https://fcm.googleapis.com/fcm/send"); configGCM.GcmUrl = "https://fcm.googleapis.com/fcm/send"; gcmPush = new GcmServiceBroker(configGCM); gcmPush.OnNotificationSucceeded += gcmPush_OnNotificationSucceeded; gcmPush.OnNotificationFailed += gcmPush_OnNotificationFailed; gcmPush.Start(); gcmPush.QueueNotification((GcmNotification)alerta.Notificacion(token)); gcmPush.Stop(); break; } } catch (Exception ex) { EscribirEnLog("hubo Error : " + ex.Message); Console.WriteLine(ex.Message); } } } if (todoCorrecto() || (ContadorIntentos >= CantidadIntentos)) { this._shouldStop = true; } else { this.ContadorEnviados = 0; this.ContadorNoEnviados = 0; Thread.Sleep(SegundosReintento * 1000); } } catch (Exception ex) { EscribirEnLog("hubo Error : " + ex.Message); Console.WriteLine(ex.Message); } } }
public void Configure(ApnsConfiguration.ApnsServerEnvironment environment, string p12FilePaht, string p12FilePassword) { _config = new ApnsConfiguration(environment, p12FilePaht, p12FilePassword); }
private static iOSNotificationEndPoint Create(byte[] certificate, string certificatePassword, ApnsConfiguration.ApnsServerEnvironment environment) { Throw.IfArgumentNull(certificate, nameof(certificate)); Throw.IfArgumentNullOrWhitespace(certificatePassword, nameof(certificatePassword)); iOSNotificationEndPoint endPoint = new iOSNotificationEndPoint(); ApnsConfiguration configuration = new ApnsConfiguration(environment, certificate, certificatePassword); endPoint.SetConnection(new ApnsServiceConnection(configuration)); return(endPoint); }