public async Task <IActionResult> SendNotification(SendNotificationRequest request) { LogMethod(Request.Body); await notificationApiClient.SendNotification(request); return(Ok()); }
public async Task WhenNewEventReceivedThenNotificationServiceCalled() { var service = new Mock<INotificationService>(); SendNotificationRequest saveDto = null; service.Setup(c => c.PostAsync(It.IsAny<SendNotificationRequest>())) .Callback<SendNotificationRequest>((dto) => saveDto = dto) .Returns(Task.FromResult(new SendNotificationResponse())); var @event = new ArticleCreatedNotificationEvent { EventType = NotificationEvent.ArticleCreated, RecipientUserId = Guid.NewGuid().ToString(), Parameters = new Dictionary<string, object> { { "ArticleId", Guid.NewGuid() } } }; var handler = new ArticleCreatedNotificationEventHandler(service.Object); await handler.Handle(@event); service.Verify(x=>x.PostAsync(saveDto), Times.Once); Assert.NotNull(saveDto); Assert.Equal(@event.EventType, saveDto.EventType); Assert.Equal(@event.RecipientUserId, saveDto.RecipientUserId); Assert.Equal(@event.Parameters, saveDto.Parameters); }
public async Task PostNotificationTest() { var service = new Mock <INotificationService>(); var response = new SendNotificationResponse { NotificationRecordId = Guid.NewGuid(), Results = new List <NotificationSendingResult>() }; var request = new SendNotificationRequest { EventType = NotificationEvent.ArticleCreated, RecipientUserId = "userId", Parameters = new Dictionary <string, object>() }; SendNotificationRequest req = null; service.Setup(x => x.PostAsync(It.Is <SendNotificationRequest>(notificationRequest => notificationRequest == request))) .Callback <SendNotificationRequest>(r => req = r) .ReturnsAsync(response) .Verifiable(); var controller = new NotificationController(_logger, service.Object).WithUser(); var result = await controller.SendNotificationAsync(request); service.Verify(); Assert.NotNull(req); var res = Assert.IsType <OkObjectResult>(result); Assert.IsType <SendNotificationResponse>(res.Value); Assert.Equal(response, res.Value); }
public async Task DeleteHistoryTest() { var client = GetAuthorizedUserClient(_userId); await EnsureSettingsExist(_userId); var message = new SendNotificationRequest { RecipientUserId = _userId, EventType = NotificationEvent.ArticleCreated, Parameters = new Dictionary <string, object> { { "ArticleId", Guid.NewGuid() } } }; var payload = new ObjectContent <SendNotificationRequest>(message, new JsonMediaTypeFormatter(), "application/json"); var response = await client.PostAsync("api/notifications", payload); var content = await response.Content.ReadAsAsync <SendNotificationResponse>(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(content.NotificationRecordId); response = await client.DeleteAsync("api/notifications/history"); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); }
public Response <EmptyResponse> SendNotification( TxSessionCredentials credentials, string bracketId, string matchId, SendNotificationRequest request) { return(bracketClient.SendNotification(credentials, bracketId, matchId, request)); }
public static async Task Run( [ActivityTrigger] SendNotificationRequest request, ILogger logger) { logger.LogInformation($"Started {nameof(SendNotification)} with recipient: {request.Recipient}."); await Service.SendNotificationAsync(request); }
public async Task <bool> Handle(SendNotificationRequest message, IOutputPort <SendNotificationResponse> outputPort) { var destinations = await _userRepository.GetAllMails(); var _not = new NotificationM(message.MessageContent, message.MessageSubject, destinations); await _mailSenderSrv.SendMail(message.MessageContent, message.MessageSubject, destinations); await _ntfRepository.SaveNotification(_not); return(true); }
public Task Handle(ArticleCreatedNotificationEvent @event) { var model = new SendNotificationRequest { EventType = @event.EventType, Parameters = @event.Parameters, RecipientUserId = @event.RecipientUserId }; return(_service.PostAsync(model)); }
public void SendNotification(SendNotificationRequest request) { logger.LogDebug("Sending notification to all subscribers"); var subscribers = repository.GetAll().GroupBy(x => x.P256Dh).Select(group => group.First()); // todo HACK!! there shouldn't be duplicates in DB, fix this logger.LogDebug($"Sending notification to {subscribers.Count()} subscribers"); foreach (var subscriber in subscribers) { logger.LogDebug($"Sending notification to {JsonSerializerHelper.Serialize(subscriber)}"); WebPushHelper.SendNotification(request.Message, subscriber.Endpoint, subscriber.P256Dh, subscriber.Auth); } }
public IActionResult SendNotification( [Required] string bracketId, [Required] string matchId, [FromBody, Required] SendNotificationRequest request) { var response = bracketService.SendNotification( requestFieldExtractor.ExtractTomUserSessionCredentials(), bracketId, matchId, request); return(Ok(response)); }
public async Task <IActionResult> SendNotification([FromBody] SendNotificationRequest Request) { try { CommunicationResponse Response = await _mediator.Send(Request); return(Ok(Response)); } catch (Exception ex) { return(BadRequest(Response)); } }
public async Task <SendNotificationResponse> SendAsync(SendNotificationRequest request) { try { await _notificationSender.SendAsync(request.ChannelId, request.Text); return(new SendNotificationResponse()); } catch (Exception ex) { _logger.LogError(ex, "Failed to SendMessage {@request}", request); return(new SendNotificationResponse { IsError = true, ErrorMessage = ex.Message }); } }
public async Task <ResponseDTO> SendNotification(SendNotificationRequest request) { WaMessageSender msgSender = new WaMessageSender(); try { var response = msgSender.sendMessage(request.DestinationNumbers, request.TextMessage); return(new ResponseDTO() { IsValid = true, Messages = new List <ApplicationMessage>() { new ApplicationMessage("1", response) } }); } catch (System.Exception ex) { return((new ResponseDTO(false)).WithMessage(ex.Message)); } }
public async Task <SendNotificationResponse> PostAsync(SendNotificationRequest request) { Ensure.That(request, nameof(request)).IsNotNull(); var settings = await _settingsStore.FindAsync(request.RecipientUserId); if (settings == null) { throw new NotFoundException(new ErrorDto(ErrorCode.NotFound, "User settings do not exist.")); } var message = Mapper.Map <NotificationMessage>(request); var response = new SendNotificationResponse(); foreach (var sender in _senders) { var senderResult = await sender.SendAsync(message, settings); if (senderResult.Status != NotificationSendingStatus.Skipped) { response.Results.Add(senderResult); } } if (response.Results.Any(x => x.Status == NotificationSendingStatus.Success)) { var newRecord = Mapper.Map <NotificationRecord>(request); newRecord.UserSettingsId = settings.Id; var record = await _historyStore.SaveAsync(newRecord); response.NotificationRecordId = record.Id; } return(response); }
public SendNotificationResponse SendNotification(SendNotificationRequest request) { try { Guid lRequestId = Guid.Empty; if (request.RequestId != "") { lRequestId = new Guid(request.RequestId); } MaintenanceService.OnTrainNotification( lRequestId, request.NotificationId, request.ElementId, request.Parameter); } catch (System.Exception e) { LogManager.WriteLog(TraceType.EXCEPTION, e.Message, "PIS.Ground.Maintenance.NotificationGroundService.SendNotification", e, EventIdEnum.Maintenance); } return(new SendNotificationResponse()); //always empty response }
public void SendNotification_SendsNotification() { // Arrange var controller = new Mock <TwilioController> (_ctrlOptions) { CallBase = true }; controller.Setup(x => x.CreateNotification(It.IsAny <string>())) .Returns(NotificationResource.FromJson("")); var sendNotificationRequest = new SendNotificationRequest() { identity = "0000001" }; // Act var result = controller.Object.SendNotification(sendNotificationRequest); // Assert var sendNotificationResult = (Dictionary <string, string>)result.Value; Assert.Equal(sendNotificationResult["message"], "Successful sending of notification."); }
public ServiceResponse SendNotification(SendNotificationRequest request) { NotificationRow objNotif = new NotificationRow { SentTo = request.Username, Details = request.Message }; using (var connection = SqlConnections.NewFor <NotificationRow>()) { connection.Insert(objNotif); } NotificationHub objNotifHub = new NotificationHub(); objNotifHub.SendNotification(objNotif.SentTo); //var query = (from t in context.Notifications // select t).ToList(); //return Request.CreateResponse(HttpStatusCode.OK, new { query }); return(new ServiceResponse { }); }
public IActionResult SendNotification(SendNotificationRequest request) { LogMethod(Request.Body); notificationLogic.SendNotification(request); return(Ok()); }
/// <summary>Sends a notification.</summary> /// <param name="request">The input request.</param> /// <returns>An empty response.</returns> public SendNotificationResponse SendNotification(SendNotificationRequest request) { LiveVideoControlService.SendElementIdNotificationToGroundApp(request.RequestId, (PIS.Ground.GroundCore.AppGround.NotificationIdEnum)request.NotificationId, request.ElementId); return(new SendNotificationResponse()); // Always an empty response }
public virtual async Task <Status> HandleChargeFailed(IEnterprisesBillingManagerService entBillingMgr, IIdentityAccessService idMgr, string entLookup, string userEmail, Stripe.Event stripeEvent) { string fromEmail = "*****@*****.**"; string supportEmail = "*****@*****.**"; State.SuspendAccountOn = DateTime.Now.AddDays(15); string suspendOnStr = State.SuspendAccountOn.ToString(); State.PaymentStatus = Status.Conflict; log.LogInformation($"Users State {State.ToJSON()}"); var usersLics = await entBillingMgr.GetCustomersIncompleteLicenseTypes(userEmail, entLookup); log.LogInformation($"Users licenses {usersLics}"); if (usersLics.Model.IsNullOrEmpty()) { //existing user with license //email the user that their cc needs to be updated and the charge failed with link to update cc var suspensionNotice = new SendNotificationRequest() { EmailFrom = fromEmail, EmailTo = userEmail, dynamic_template_data = new TemplateDataModel { suspendOn = suspendOnStr }, template_id = "d-b7fb6618e8d3466b94bffd27e5a43f16" }; await SendTemplateEmail(entBillingMgr, entLookup, suspensionNotice); //email fathym support about the card failure var cardFailedNotice = new SendNotificationRequest() { EmailFrom = fromEmail, EmailTo = supportEmail, dynamic_template_data = new TemplateDataModel { userName = userEmail, suspendOn = suspendOnStr }, template_id = "d-8048d19cfc264ca6a364a964d1deec76" }; await SendTemplateEmail(entBillingMgr, entLookup, cardFailedNotice); } if (!usersLics.Model.IsNullOrEmpty()) { //new user signup that failed var ccFailedNotice = new SendNotificationRequest() { EmailFrom = fromEmail, EmailTo = userEmail, dynamic_template_data = new TemplateDataModel { }, template_id = "d-ecd308931cc54e4f91f5d795f323cd95" }; await SendTemplateEmail(entBillingMgr, entLookup, ccFailedNotice); } //TODO automate pause the users account with fathym after 15 day grace period once event is recieved //TODO automate once 15 day grace period has passed suspend the users account and notify the user. return(Status.Success); // throw new NotImplementedException(); }
public async Task WhenSenderSucceedsThenRecordCreatedTest() { var userId = Guid.NewGuid().ToString(); var request = new SendNotificationRequest { EventType = NotificationEvent.ArticleCreated, RecipientUserId = userId, Parameters = new Dictionary <string, object> { { "testKey", "testValue" } } }; var store = new Mock <ISettingsDataStore>(); store.Setup(x => x.FindAsync(It.Is <string>(s => s == userId))) .ReturnsAsync(new UserSettings { Id = Guid.NewGuid(), UserId = userId }); NotificationRecord newRecord = null; var historyStore = new Mock <INotificationHistoryDataStore>(); historyStore.Setup(x => x.SaveAsync(It.IsAny <NotificationRecord>())) .Callback <NotificationRecord>(record => { newRecord = record; newRecord.Id = Guid.NewGuid(); }) .ReturnsAsync(() => newRecord); var skippedResult = new NotificationSendingResult(NotificationType.Email); skippedResult.Skip(); var sender1 = new Mock <INotificationSender>(); sender1.Setup(x => x.SendAsync(It.IsAny <NotificationMessage>(), It.IsAny <UserSettings>())) .ReturnsAsync(skippedResult); var successfulResult = new NotificationSendingResult(NotificationType.Push); var sender2 = new Mock <INotificationSender>(); sender2.Setup(x => x.SendAsync(It.IsAny <NotificationMessage>(), It.IsAny <UserSettings>())) .ReturnsAsync(successfulResult); var senders = new List <INotificationSender> { sender1.Object, sender2.Object }; var service = new NotificationService(store.Object, senders, historyStore.Object, DefaultMapper); var result = await service.PostAsync(request); Assert.NotNull(result); historyStore.Verify(x => x.SaveAsync(It.IsAny <NotificationRecord>()), Times.Once); sender1.Verify(x => x.SendAsync(It.IsAny <NotificationMessage>(), It.IsAny <UserSettings>()), Times.Once); sender2.Verify(x => x.SendAsync(It.IsAny <NotificationMessage>(), It.IsAny <UserSettings>()), Times.Once); Assert.NotNull(result.NotificationRecordId); Assert.Equal(1, result.Results.Count); Assert.DoesNotContain(skippedResult, result.Results); Assert.Contains(successfulResult, result.Results); Assert.Equal(newRecord.Id, result.NotificationRecordId); Assert.Equal(request.RecipientUserId, newRecord.OwnerUserId); Assert.Equal(request.Parameters, newRecord.Parameters); }
// public virtual async Task<Status> SendNotification(IEnterprisesBillingManagerService entMgr, string entLookup, string username, SendNotificationRequest notification) // { // // Send email from app manager client // var model = new MetadataModel(); // model.Metadata.Add(new KeyValuePair<string, JToken>("SendNotificationRequest", JToken.Parse(JsonConvert.SerializeObject(notification)))); // await entMgr.SendNotificationEmail(model, entLookup); // return Status.Success; // } public virtual async Task <Status> SendTemplateEmail(IEnterprisesBillingManagerService entBillingMgr, string entLookup, SendNotificationRequest notification) { // Send email from app manager client var model = new MetadataModel(); model.Metadata.Add(new KeyValuePair <string, JToken>("TemplateEmail", JToken.Parse(JsonConvert.SerializeObject(notification)))); // await entBillingMgr.SendTemplateEmail(model, entLookup); return(Status.Success); }
public bool ValidateRequest(SendNotificationRequest request) { return(request.Emails?.Count > 0); }
public async Task SendNotification(SendNotificationRequest request, string subject, string body) { await SendEmail(request.Emails, subject, body); }
public async Task <ActionResult <SendNotificationResponse> > Send([FromBody] SendNotificationRequest request) { var responseValue = new SendNotificationResponse(); // create new guid and insert into postgres table var pgDataRow = new NotificationRequest { Id = Guid.NewGuid(), ApplicationId = request.ApplicationId, NotificationStatusId = Convert.ToInt32(NotificationStatus.New), NotificationTypeId = request.NotificationTypeId, CountryCode = request.CountryCode, FromEmail = request.FromEmail?.Trim(), Attributes = request.Attributes, RequestData = request.RequestData, RecipientList = request.RecipientList.Select(x => new Recipient { Email = x.Email?.Trim(), Name = x.Name, Language = x.Language, SendCode = x.SendCode }) }; bool success; try { success = await pgClient.Insert(new InsertNotificationRequest(), pgDataRow, CancellationToken.None) > 0; } catch (Exception e) { if (e.Message.Contains("violates foreign key")) { responseValue.ValidationResult = $"Send failed with : An ID in this request violates a foreign key constraint"; return(StatusCode(StatusCodes.Status400BadRequest, responseValue)); } LambdaLogger.Log($"Email Api: Send failed when inserting into database: {e.Message}"); throw; } if (!success) { LambdaLogger.Log($"Email Api: Send failed with : Could not insert request into postgres environment name- {Config.EnvironmentName}"); responseValue.ValidationResult = $"Send failed with : Could not insert request into postgres environment name- {Config.EnvironmentName}"; return(StatusCode(StatusCodes.Status503ServiceUnavailable, responseValue)); } // insert into SQS for processor to pick up var newMessage = new QueueMessage { RequestId = pgDataRow.Id }; var serializedMessage = JsonConvert.SerializeObject(newMessage); success = await queueService.SendMessage(serializedMessage, Config.EmailServiceSqsUrl); // if not successful warn the caller if (!success) { LambdaLogger.Log($"Email Api: Send failed with : Could not insert message into queue - {Config.EmailServiceSqsUrl}"); responseValue.ValidationResult = $"Send failed with : Could not insert message into queue"; return(StatusCode(StatusCodes.Status503ServiceUnavailable, responseValue)); } // on success return the Guid so that the caller can use to check the message status LambdaLogger.Log($"Email Api: Send succeeded with guid : {serializedMessage}"); responseValue.RequestId = pgDataRow.Id; return(Ok(responseValue)); }
public async Task SendNotificationAsync(SendNotificationRequest request) { // Simulate successfull sending of a notification. await Task.CompletedTask; }
public async Task SendNotification(SendNotificationRequest request) { var address = configuration.NotificationApiAddress + "SendNotification"; await HttpClientHelper.PostAsync <SendNotificationRequest, object>(request, address); }
public async Task <IActionResult> SendNotificationAsync([FromBody][Required] SendNotificationRequest request) { var result = await _notificationService.PostAsync(request); return(Ok(result)); }
public async Task On_Successful_Send_Should_Respond_With_New_Guid_For_Request() { // arrange var goodRequest = new SendNotificationRequest { ApplicationId = 1, NotificationTypeId = new Guid("00000000-0000-0000-0000-000000000002"), CountryCode = "test", FromEmail = "*****@*****.**", Attributes = new Dictionary <string, string> { { "ApplicationName", "test" }, { "MachineName", "test" } }, RecipientList = new List <Recipient> { new Recipient { Email = "*****@*****.**", Name = "recipient 1", SendCode = SendCode.To }, new Recipient { Email = "*****@*****.**", Name = "recipient 2", SendCode = SendCode.CC }, new Recipient { Email = "*****@*****.**", Name = "recipient 3", SendCode = SendCode.BCC } } }; _pgClient.Setup(x => x.Insert( It.IsAny <InsertNotificationRequest>(), It.IsAny <NotificationRequest>(), It.IsAny <CancellationToken>())) .ReturnsAsync(1); _queueService.Setup(x => x.SendMessage(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(true); // act var result = await testEmailController.Send(goodRequest); // assert _pgClient.Verify(x => x.Insert( It.IsAny <InsertNotificationRequest>(), It.Is <NotificationRequest>( request => request.RecipientList.Any(recipient => recipient.Email.Equals("*****@*****.**") && recipient.SendCode == SendCode.CC)), It.IsAny <CancellationToken>()), Times.Once); Assert.IsNotNull(result); Assert.IsInstanceOf <OkObjectResult>(result.Result); Assert.AreNotEqual(((SendNotificationResponse)((OkObjectResult)result.Result).Value).RequestId, Guid.Empty); }
public Response <EmptyResponse> SendNotification(TxSessionCredentials credentials, string bracketId, string matchId, SendNotificationRequest request) { client.DefaultRequestHeaders.Add("UserId", credentials.UserId); client.DefaultRequestHeaders.Add("SessionId", credentials.SessionId); var response = client.PostAsync($"bracket/{bracketId}/match/{matchId}/notification", RequestSerializer.Content(request)).Result; if (response.IsSuccessStatusCode) { return(Newtonsoft.Json.JsonConvert.DeserializeObject <Response <EmptyResponse> >(response.Content.ReadAsStringAsync().Result)); } return(new Response <EmptyResponse>(response.RequestMessage.ToString(), (int)response.StatusCode)); }