public async Task<IHttpActionResult> CreateComment(NewCommentDTO model) { if (!ModelState.IsValid) return BadRequest(); var result = await _commentService.CreateComment(model); if(result.Success) { return Ok(); } return BadRequest(result.Error); }
public async Task<ValidationResult> CreateComment(NewCommentDTO model) { try { //Firstly check the Event exists Event evnt = await _eventRepo.Get(x => x.Id == model.EventId) .Include(x => x.Comments) .Include(x => x.Members.Select(u => u.User)) .FirstOrDefaultAsync(); if (evnt == null) return AddError("Event does not exist"); //Make sure the creator is a member of the event bool isMember = evnt.Members.Any(x => x.UserId == model.CreatorId); if(!isMember) return AddError("The creator provided isn't a member of the event!"); //Create the new Comment entity EventComment comment = new EventComment { CreatorId = model.CreatorId, EventId = evnt.Id, Body = model.Body, OrderNo = 0 }; //Set the correct order number int nextNo = 0; foreach (var c in evnt.Comments) { nextNo = c.OrderNo > nextNo ? c.OrderNo : nextNo; } comment.OrderNo = nextNo + 1; //Attached comment to event evnt.Comments.Add(comment); //Update database _eventRepo.Update(evnt); await SaveChangesAsync(); //Get members deviceIds List<string> deviceIds = new List<string>(); foreach (var member in evnt.Members) { if(member.UserId != model.CreatorId) deviceIds.Add(member.User.DeviceId); } if (deviceIds.Any()) { //Finally send out notifications to members string authorName = evnt.Members.Where(x => x.UserId == model.CreatorId) .First().User.Name; string message = $"{authorName} has posted a comment on \"{evnt.Title}\""; AndroidGCMPushNotification.SendNotification(deviceIds, message); } Result.Success = true; return Result; } catch (Exception ex) { return AddError(ex.Message); } }