/// <summary> /// Creates a new notifier of the provided type /// </summary> /// <param name="typeId">ID or notifier type</param> /// <exception cref=""></exception> public async Task <string> NewNotifierAsync(string typeId) { // Find the type of notifier data Type notifierDataType = _notifierDefinitionService.GetNotifierDataType(typeId); if (notifierDataType == null) { throw new TypeAccessException("Notifier type is unknown"); } // Get name of notifier type string displayName = $"New {_notifierDefinitionService.GetNotifierTypeName(typeId) ?? "Notifier"}"; // Create a new instance of the notifier data type BaseNotifierData notifier = Activator.CreateInstance(notifierDataType, new object[] { displayName }) as BaseNotifierData; if (notifier == null || string.IsNullOrWhiteSpace(notifier.Id)) { throw new TypeAccessException("Can't create notifier data type"); } // Add notifier await _dbContext.Notifiers.AddAsync(notifier); // Save await _dbContext.SaveChangesAsync(); return(notifier.Id); }
public void Notify(ISubcriber subcriber, BaseNotifierData data) { var emailSubcriber = subcriber as EmailSubcriber; var emailData = data as EmailNotifierData; if(emailData == null || emailSubcriber == null) throw new AntelopeInvalidParameter(); try { var fromAddress = new MailAddress(_emailAddr, _emailDisplayName); var toAddress = new MailAddress(emailSubcriber.Email, emailSubcriber.DisplayName); using (var message = new MailMessage(fromAddress, toAddress) { Subject = emailData.Title, Body = Formatter.Format(emailData.Content) }) { _smtp.Send(message); } } catch(FormatException) { throw new AntelopeInvalidEmailFormat(); } catch(SmtpException ex) { throw new AntelopeSmtpException(ex.ToString()); } catch (Exception ex) { _logger.Error("Caught exception when sending notification through email to {0}: {1}", emailSubcriber.Email, ex.ToString()); } }
public void NotifyAll(BaseNotifierData data) { foreach (var notifierId in _subcribers.Keys) { Notify(notifierId, data); } }
public async void Notify(ISubcriber subcriber, BaseNotifierData data) { var signalrSubcriber = subcriber as SignalRSubcriber; var signalrData = data as MessageNotifierData; if (signalrSubcriber == null || signalrData == null) throw new AntelopeInvalidParameter(); try { _connection = new HubConnection(signalrSubcriber.Url); _proxy = _connection.CreateHubProxy(HubName()); _connection.Closed += OnConnectionClosed; await _connection.Start(); } catch (HttpRequestException) { _logger.Info("Can't connect to {0}", signalrSubcriber.Url); } await _proxy.Invoke(HubMethod(), Formatter.Format(signalrData.Content)); }
/// <summary> /// Adds a new notifier /// </summary> /// <param name="notifier">Notifier data to add</param> public async Task AddNotifierAsync(BaseNotifierData notifier) { // Add notifier _dbContext.Notifiers.Add(notifier); //Save await _dbContext.SaveChangesAsync(); }
/// <summary> /// Tries to get the appropriate notifier service instance for the given notifier data /// </summary> /// <param name="notifierData">Notifier configuration data</param> private INotifier GetNotifier(BaseNotifierData notifierData, IServiceProvider serviceProvider) => notifierData .GetType() .GetCustomAttributes(false) .Where(attr => attr is NotifierAttribute) .Cast <NotifierAttribute>() .Select(na => serviceProvider.GetService(na.NotifierType.GetInterfaces().First())) .Cast <INotifier>() .FirstOrDefault();
/// <summary> /// Send a notification message to each recipient /// </summary> /// <param name="data">Configuration data for the notifier</param> /// <param name="message">Message to send</param> /// <param name="recipients">List of recipients</param> public async Task SendMessageAsync(BaseNotifierData data, Message message, IEnumerable <User> recipients) { if (!typeof(T).IsInstanceOfType(data)) { Logger.LogError("Internal error. Notifier called with wrong data package"); return; } // Cast data T notiferData = (T)data; Logger.LogDebug("Sending message via notifier {}", notiferData.DisplayName); // New notification history entry int historyId = await _notificationHistoryManager.AddHistoryForTypeAsync(typeof(T)); // Start sending messages to each recipient var tasks = GetRecipientTasks(notiferData, message, recipients); // Should have tasks if (!(tasks?.Any() ?? false)) { // Count all recipients as failed in the case of a general error await _notificationHistoryManager.SetHistoryCountsAsync(historyId, 0, recipients.Count()); return; } // wait until all notifications have been send int successCount = 0; int failedCount = 0; await Task.Run(() => tasks.AsParallel().ForAll(task => { try { // wait for successfull completion task.Wait(); Interlocked.Increment(ref successCount); } catch (Exception) { // Should be logged in the notifier itself\ Interlocked.Increment(ref failedCount); } })); // update the history entry with success stats await _notificationHistoryManager.SetHistoryCountsAsync(historyId, successCount, failedCount); }
/// <summary> /// Sends a message on a specific notifier /// </summary> /// <param name="notifier">The notifier to use to send the message</param> /// <param name="message">The message</param> /// <param name="recipients">The recipients of the message</param> private async Task SendMessageAsync(BaseNotifierData notifierData, Message message, IEnumerable <User> recipients) { // Create the correct notifier type using var scope = _serviceProvider.CreateScope(); var notifier = GetNotifier(notifierData, scope.ServiceProvider); if (notifier == null) { _logger.LogError("No notifier found for data class: {class}", notifierData.GetType().FullName); return; } // Send message via notifier await notifier.SendMessageAsync(notifierData, message, recipients); }
/// <summary> /// Deleted a notifier by Id /// </summary> /// <param name="id">ID of notifier to delete</param> public async Task DeleteNotifierByIdAsync(string id) { // Find notifier by Id BaseNotifierData notifier = _dbContext.Notifiers.FirstOrDefault(n => n.Id.Equals(id)); if (notifier == null) { throw new KeyNotFoundException("Notifier not found"); } // Remove notifier _dbContext.Notifiers.Remove(notifier); // Save await _dbContext.SaveChangesAsync(); }
/// <summary> /// Saves changes to a notifier /// </summary> /// <param name="id">ID of changed notifier</param> /// <param name="jsonBody">JSON string with notifier properties and values</param> public async Task <int> ChangeNotifierAsync(string id, string jsonBody) { // Find notifier by Id BaseNotifierData notifier = GetNotifierById(id); if (notifier == null) { throw new KeyNotFoundException("Notifier not found"); } // Apply changes await notifier.ApplyJsonPropertiesAsync(jsonBody); // Save changes return(await _dbContext.SaveChangesAsync()); }
public void Notify(int channel, BaseNotifierData data) { if (!ExistNotifier(channel) || !ExistSubrcibersOn(channel)) return; var notifier = _notifiers[channel]; foreach (var subcriber in _subcribers[channel]) { try { notifier.Notify(subcriber, data); } catch (Exception ex) { _logger.Error("Caught Exception: {0}", ex.ToString()); } } }
public void Notify(ISubcriber subcriber, BaseNotifierData data) { var skypeData = data as SkypeNotifierData; var skypeSubcriber = subcriber as SkypeSubcriber; if (skypeData == null || skypeSubcriber == null) throw new AntelopeInvalidParameter(); if (_friends.Find(fr => fr.Handle == skypeSubcriber.Handle) == null) throw new AntelopeUnknownTarget(); try { _skypeHandler.SendMessage(skypeSubcriber.Handle, Formatter.Format(skypeData.Message)); } catch (Exception ex) { _logger.Error("Caught exception when sending notification through skype to {0}: {1}", skypeSubcriber.Handle, ex.ToString()); } }