//Create Notification for posting private async Task SendNotification(Post post) { var follows = await _followService.GetBySubjectId(post.OwnerId); //Create notification for each follower of Post owner foreach (FollowResponse follow in follows) { var notification = new CreateNotificationRequest { //Post Owner ActionOwnerId = post.OwnerId, NotificationType = NotificationType.Posted, PostId = post.Id, ReiceiverId = follow.FollowerId, Created = DateTime.Now, Status = Status.Created }; await _notificationService.CreateNotification(notification); var connections = await _tracker.GetConnectionForUser(notification.ReiceiverId); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewNotification", notification); } } }
//Create public async Task <NotificationResponse> CreateNotification(CreateNotificationRequest model) { var oldNotification = await _context.Notifications.Where(n => n.NotificationType == model.NotificationType && n.ActionOwnerId == model.ActionOwnerId && n.ReiceiverId == model.ReiceiverId).ToListAsync(); _context.RemoveRange(oldNotification); var notification = _mapper.Map <Notification>(model); if (notification == null) { throw new AppException("Create Notification failed"); } _context.Notifications.Add(notification); await _context.SaveChangesAsync(); var notificationResponse = _mapper.Map <NotificationResponse>(notification); var actionOwner = await _accountService.GetById(notificationResponse.ActionOwnerId); bool IsActionOwnerNameNull = actionOwner.Name == null; notificationResponse.ActionOwnerName = IsActionOwnerNameNull ? "" : actionOwner.Name; notificationResponse.ActionOwnerAvatarPath = actionOwner.AvatarPath; var receiver = await _accountService.GetById(notificationResponse.ReiceiverId); bool IsReceiverNull = receiver.Name == null; notificationResponse.ReiceiverName = IsReceiverNull ? "" : receiver.Name; return(notificationResponse); }
public async Task <ApiResult <bool> > Create(CreateNotificationRequest request) { var query = from n in _context.Notifications where n.Id_BLE == request.Id_BLE && n.Status == true select new { n }; if (query.Count() > 0) { return(new ApiSuccessResult <bool>("thiết bị đang được xử lý")); } var equipment = await _context.Equipment.FindAsync(request.Id_BLE); if (equipment == null || equipment.Id_Student != request.Id_User) { return(new ApiErrorResult <bool>("Không tìm thấy thiết bị")); } var notification = new Notification() { Id_BLE = request.Id_BLE, Id_User = request.Id_User, Reason = request.Reason, DateCreate = DateTime.UtcNow.AddHours(7), DateUpdate = DateTime.UtcNow.AddHours(7), Status = true }; equipment.Status = false; _context.Notifications.Add(notification); await _context.SaveChangesAsync(); return(new ApiSuccessResult <bool>("Tạo thành thành công")); }
public async Task <Notification> CreateAsync(CreateNotificationRequest createNotificationRequest) { var notification = await base.CreateAsync(new Notification { UserId = createNotificationRequest.UserId, RequestId = createNotificationRequest.RequestId, Type = createNotificationRequest.Type, Severity = createNotificationRequest.Severity, MetaDeta1 = createNotificationRequest.MetaDeta1, MetaDeta2 = createNotificationRequest.MetaDeta2, MetaDeta3 = createNotificationRequest.MetaDeta3, Content = createNotificationRequest.Content?.ToJson(), }); if (createNotificationRequest.Users?.Count > 0) { var userNotifications = createNotificationRequest.Users.Select(x => new UserNotification { IsRead = false, NotificationId = notification.Id, UserId = x, }).ToList(); await _userNotificationService.BulkCreateAsync(userNotifications); } return(notification); }
/// <summary> /// Creates a notification. You must create the budget before you create the associated /// notification. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateNotification service method.</param> /// /// <returns>The response from the CreateNotification service method, as returned by Budgets.</returns> /// <exception cref="Amazon.Budgets.Model.CreationLimitExceededException"> /// You've exceeded the notification or subscriber limit. /// </exception> /// <exception cref="Amazon.Budgets.Model.DuplicateRecordException"> /// The budget name already exists. Budget names must be unique within an account. /// </exception> /// <exception cref="Amazon.Budgets.Model.InternalErrorException"> /// An error on the server occurred during the processing of your request. Try again later. /// </exception> /// <exception cref="Amazon.Budgets.Model.InvalidParameterException"> /// An error on the client occurred. Typically, the cause is an invalid input value. /// </exception> /// <exception cref="Amazon.Budgets.Model.NotFoundException"> /// We can’t locate the resource that you specified. /// </exception> public virtual CreateNotificationResponse CreateNotification(CreateNotificationRequest request) { var marshaller = CreateNotificationRequestMarshaller.Instance; var unmarshaller = CreateNotificationResponseUnmarshaller.Instance; return(Invoke <CreateNotificationRequest, CreateNotificationResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// Initiates the asynchronous execution of the CreateNotification operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateNotification operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual Task <CreateNotificationResponse> CreateNotificationAsync(CreateNotificationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateNotificationRequestMarshaller.Instance; var unmarshaller = CreateNotificationResponseUnmarshaller.Instance; return(InvokeAsync <CreateNotificationRequest, CreateNotificationResponse>(request, marshaller, unmarshaller, cancellationToken)); }
internal virtual CreateNotificationResponse CreateNotification(CreateNotificationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateNotificationRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateNotificationResponseUnmarshaller.Instance; return(Invoke <CreateNotificationResponse>(request, options)); }
/// <summary> /// Creates a notification. You must create the budget before you create the associated /// notification. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateNotification service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateNotification service method, as returned by Budgets.</returns> /// <exception cref="Amazon.Budgets.Model.AccessDeniedException"> /// You are not authorized to use this operation with the given parameters. /// </exception> /// <exception cref="Amazon.Budgets.Model.CreationLimitExceededException"> /// You've exceeded the notification or subscriber limit. /// </exception> /// <exception cref="Amazon.Budgets.Model.DuplicateRecordException"> /// The budget name already exists. Budget names must be unique within an account. /// </exception> /// <exception cref="Amazon.Budgets.Model.InternalErrorException"> /// An error on the server occurred during the processing of your request. Try again later. /// </exception> /// <exception cref="Amazon.Budgets.Model.InvalidParameterException"> /// An error on the client occurred. Typically, the cause is an invalid input value. /// </exception> /// <exception cref="Amazon.Budgets.Model.NotFoundException"> /// We can’t locate the resource that you specified. /// </exception> public virtual Task <CreateNotificationResponse> CreateNotificationAsync(CreateNotificationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateNotificationRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateNotificationResponseUnmarshaller.Instance; return(InvokeAsync <CreateNotificationResponse>(request, options, cancellationToken)); }
public void When_ValidCreateNotificationRequestEvent_Then_HaveValidData() { var createNotificationEvent = CreateNotificationEventData.GetValidEvent(); var createNotificationRequest = CreateNotificationRequest.Make(createNotificationEvent); Assert.Equal(createNotificationEvent.NotificationType, createNotificationRequest.NotificationType); Assert.Equal(createNotificationEvent.TemplateType, createNotificationRequest.TemplateType); Assert.Equal(createNotificationEvent.TemplateVersion, createNotificationRequest.TemplateVersion); Assert.Equal(createNotificationEvent.TemplateMapper, createNotificationRequest.TemplateMapper); Assert.Equal(createNotificationEvent.Receiver, createNotificationRequest.Receiver); }
public async Task When_CreateNotificationWithInvalidRequest_Then_ThrowsInvalidRequestException() { var useCase = GetUseCase(); var createNotificationRequest = new CreateNotificationRequest(0, 0, 0, null, null); await Assert.ThrowsAsync <InvalidRequestException>(() => useCase.ExecuteAsync(createNotificationRequest)); _templateRepositoryPortMock.Verify(x => x.GetByTypeAsync(It.IsAny <NotificationType>(), It.IsAny <TemplateType>(), It.IsAny <TemplateVersion>()), Times.Never); _templateRenderProviderPortMock.Verify(x => x.Render(It.IsAny <string>()), Times.Never); _emailNotificationPortMock.Verify(x => x.DispatchAsync(It.IsAny <DispatchData>()), Times.Never); }
public async Task <IActionResult> Create(CreateNotificationRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _notificationService.Create(request); if (result.IsSuccessed == false) { return(BadRequest(result)); } return(Ok(result)); }
public async Task CreateNotification_ShouldThrowExceptionWhenUserIdIsZeroAsync() { // Arrange var requestDto = new CreateNotificationRequest( "Notification Test", NotificationTypeEnum.Email, this._mockedDate, 0 ); // Act var exception = await Assert.ThrowsAsync <InvalidUserIdException>(() => _sut.CreateNotification(requestDto)); // Assert Assert.Equal("UserID is invalid", exception.Message); }
public async Task CreateNotification_ShouldThrowExceptionWhenPayloadIsNullAsync() { // Arrange var requestDto = new CreateNotificationRequest( null, NotificationTypeEnum.Email, this._mockedDate, 1 ); // Act var exception = await Assert.ThrowsAsync <InvalidPayloadException>(() => _sut.CreateNotification(requestDto)); // Assert Assert.Equal("Payload cannot be null or empty", exception.Message); }
/// <inheritdoc /> public async Task <CreateNotificationResponse> CreateNotification(CreateNotificationRequest request) { var newNot = new Models.Notification.Notification(); newNot.NotificationPayload = request.Payload; newNot.NotificationType = request.Type; newNot.CreatedDate = request.DateCreated; newNot.UserID = request.UserId; _context.Notifications.Add(newNot); await _context.SaveChanges(); CreateNotificationResponse response = new CreateNotificationResponse(HttpStatusCode.Created); return(response); }
public async Task <CreateNotificationResponse> CreateNotification(CreateNotificationRequest request) { if (request == null) { throw new InvalidNotificationRequestException("Invalid CreateNotificationRequest object"); } if (request.UserId is 0 or < 0) { throw new InvalidUserIdException("UserID is invalid"); } if (string.IsNullOrEmpty(request.Payload)) { throw new InvalidPayloadException("Payload cannot be null or empty"); } return(await _repository.CreateNotification(request)); }
private async Task <GenericResult <notificationModels.Notification, string> > CreateNotification(UserEvent userEvent, userModels.User follower, userModels.User followee) { // TODO: ideally these notificationtypeids should be fetched from persistent layer. long notificationType = userEvent.EventType == UserEventType.FollowRequestCreate ? 1 : 2; var content = notificationType == 1 ? $"{follower.DisplayName} has requested to follow you" : $"{followee.DisplayName} has accepted your follow request"; long userId = userEvent.EventType == UserEventType.FollowRequestCreate ? followee.Id : follower.Id; var createNotificationRequest = new CreateNotificationRequest { UserId = userId, Content = content, Type = notificationType }; return(await _notificationsLogic.Create(createNotificationRequest)); }
public async Task CreateNotification_ShouldReturnCreatedStatusCodeAsync() { // Arrange var requestDto = new CreateNotificationRequest( "Notification Test", NotificationTypeEnum.Email, this._mockedDate, 1 ); var responseDto = new CreateNotificationResponse(HttpStatusCode.Created); _notificationRepoMock.Setup(n => n.CreateNotification(requestDto)).ReturnsAsync(responseDto); // Act var createdNotification = await _sut.CreateNotification(requestDto); // Assert Assert.Equal(responseDto, createdNotification); }
private async Task SendNotification(int commentOwnerId, Post model) { var createnotificationRequest = new CreateNotificationRequest { ActionOwnerId = commentOwnerId, NotificationType = NotificationType.Commented, PostId = model.Id, ReiceiverId = model.OwnerId, Created = DateTime.Now, Status = Status.Created }; var notification = await _notificationService.CreateNotification(createnotificationRequest); var connections = await _tracker.GetConnectionForUser(notification.ReiceiverId); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewNotification", notification); } }
//Helper methods private async Task SendNotification(Follow model) { var notification = new CreateNotificationRequest { ActionOwnerId = model.FollowerId, NotificationType = NotificationType.FollowRequest, PostId = 0, ReiceiverId = model.SubjectId, Created = DateTime.Now, Status = Status.Created }; await _notificationService.CreateNotification(notification); var connections = await _tracker.GetConnectionForUser(notification.ReiceiverId); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewNotification", notification); } }
private async Task SendNotification(int reactionOwnerId, Reaction model) { var notification = new CreateNotificationRequest { ActionOwnerId = reactionOwnerId, Created = DateTime.Now, Status = Status.Created }; if (model.Target == ReactionTarget.Post) { notification.NotificationType = NotificationType.ReactedPost; notification.PostId = model.TargetId; var receiver = await _context.Posts.FindAsync(model.TargetId); notification.ReiceiverId = receiver.OwnerId; } if (model.Target == ReactionTarget.Comment) { notification.NotificationType = NotificationType.ReactedComment; notification.CommentId = model.TargetId; var post = await _context.Comments.FindAsync(model.TargetId); notification.PostId = post.PostId; var receiver = await _context.Comments.FindAsync(model.TargetId); notification.ReiceiverId = receiver.OwnerId; } await _notificationService.CreateNotification(notification); var connections = await _tracker.GetConnectionForUser(notification.ReiceiverId); if (connections != null) { await _presenceHub.Clients.Clients(connections).SendAsync("NewNotification", notification); } }
public async Task <DispatchData> Make(CreateNotificationRequest request, Template template) { var title = template.Title; var templateRendering = template.IsRendered ? await _templateRenderProviderPort.Render(template.Content) : template.Content; var templateMapper = request.TemplateMapper; if (templateMapper != null) { templateMapper.Message?.ForEach(x => templateRendering = templateRendering.Replace(x.Key, x.Value)); templateMapper.Title?.ForEach(x => title = title.Replace(x.Key, x.Value)); } return(new DispatchData( (NotificationType)request.NotificationType, request.Receiver, title, templateRendering )); }
public override async Task Handle(CreateNotificationEvent message, EventHeader header) { try { var request = CreateNotificationRequest.Make(message); if (request.ValidationResult.IsInvalid()) { var errors = request.ValidationResult.GetErrors(); _logger.LogWarning("[NotificationApp][ICreateNotificationEvent]\nInvalid request\n{@request}\n{@errors}", request, errors); return; } _logger.LogInformation("[NotificationApp][ICreateNotificationEvent] Execute UseCase\n{@request}", request); await _createNotificationUseCase.ExecuteAsync(CreateNotificationRequest.Make(message)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); throw; } }
public async Task ExecuteAsync(CreateNotificationRequest request) { if (request is null) { throw new EmptyRequestException(nameof(CreateNotificationRequest)); } if (request.ValidationResult.IsInvalid()) { throw new InvalidRequestException(request.ValidationResult.Stringify()); } var template = await _retrieveTemplateRule.RetrieveTemplateAsync(request.NotificationType, request.TemplateType, request.TemplateVersion); if (template is null) { throw new TemplateNotFoundException(request.TemplateType, request.TemplateVersion); } var dispatchData = await _makeDispatchDataNotificationRule.Make(request, template); await _dispatchNotificationRule.DispatchAsync(dispatchData); }
/// <summary> /// Create a new notification on the Plot back-end server /// </summary> /// <param name="notification">Entity containing the v1 data of the notification to create</param> /// <returns>ID (string) of the created v1 notification</returns> public string CreateNotification(CreateNotificationV1 notification) { const string FunctionAdmin = "createNotification"; const string Function = "notification"; notification.Check(); CreateNotificationRequest request = new CreateNotificationRequest() { placeId = notification.StoreId, message = notification.Message, timespans = (notification.Timespans == null || notification.Timespans.Count() == 0) ? new CreateNotificationRequest.Timespan[] { } : notification.Timespans.Select(t => new CreateNotificationRequest.Timespan() { start = t.Start.AsString(), end = t.End.AsString() }).ToArray(), data = notification.Data, matchRange = notification.MatchRange, published = notification.Published }; HttpWebRequest webRequest = GetWebRequestAndSendRequest("POST", isAdminConnection ? FunctionAdmin : Function, request); CreateNotificationResponse response = GetJSONresponse <CreateNotificationResponse>(webRequest); // check the result codes: response.Check(); string ret = response.Result; if (string.IsNullOrWhiteSpace(ret)) { throw new Exception("No ID returned."); } return(ret); }
public async Task <IActionResult> CreateAsync([FromBody] CreateNotificationRequest request) { try { request.ValidateSchema(); if (request.ValidationResult.IsInvalid()) { var errors = request.ValidationResult.GetErrors(); _logger.LogWarning("[NotificationController][CreateAsync]\nInvalid request\n{@request}\n{@errors}", request, errors); return(BadRequest(errors)); } _logger.LogInformation("[NotificationController][CreateAsync] Execute UseCase\n{@request}", request); await _eventBus.Publish <CreateNotificationEvent>(request); return(Ok()); } catch (Exception ex) { _logger.LogError(ex.Message, ex); return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public async Task <ActionResult <NotificationResponse> > Create(CreateNotificationRequest model) { var notification = await _notificationService.CreateNotification(model); return(Ok(notification)); }
private notificationModels.Notification GetNotificationFromCreateNotificationRequest(CreateNotificationRequest createNotificationRequest) => new notificationModels.Notification { Id = _identityFactory.NextId(), Content = createNotificationRequest.Content, Type = createNotificationRequest.Type, Url = createNotificationRequest.Url, UserId = createNotificationRequest.UserId };
public async Task <GenericResult <notificationModels.Notification, string> > Create(CreateNotificationRequest createNotificationRequest) { if (createNotificationRequest == null) { throw new ArgumentNullException("createNotificationRequest"); } var result = new GenericResult <notificationModels.Notification, string>(); var notification = GetNotificationFromCreateNotificationRequest(createNotificationRequest); await _notificationRepository.Create(notification); // TODO: Generate a notification event, so the EventsService can deliver the notification to the user. _eventsLogic.CreateClientEvent(GetPublishEventRequestFromNotification(MapNotification(notification), createNotificationRequest.UserId)); result.SuccessResult = notification; return(result); }
/// <summary> /// Create Notification /// </summary> /// <param name="request">Request</param> public void CreateNotification(CreateNotificationRequest request) { Channel.CreateNotification(request); }
public async Task <CreateNotificationResponse> CreateNotification([FromBody] CreateNotificationRequest request) { return(await _service.CreateNotification(request)); }