public async Task<IHttpActionResult> Create(EventCreateDTO model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var result = await _eventService.CreateEvent(model); if (result.Success) { return Ok(); } return BadRequest(result.Error); }
public async Task<ValidationResult> CreateEvent(EventCreateDTO model) { try { //Parse guid(s) Guid? id = ParseGuid(model.Id); if (id == null) { Result.Error = "Failed to parse provided Id"; return Result; } Guid? calId = ParseGuid(model.CalendarId); if (calId == null) { Result.Error = "Failed to parse provided CalendarId"; return Result; } //Load the calendar Calendar cal = await _calendarRepo.Get(x => x.Id == calId.Value) .Include(x => x.Members.Select(m => m.User)) .FirstOrDefaultAsync(); if (cal == null) { Result.Error = "404 : Calendar not found"; return Result; } Event newEvent = new Event { Id = id.Value, CreatorId = model.CreatorId, Title = model.Title, Body = model.Body, Location = model.Location, AllDay = model.AllDay, StartDateTime = ParseUKDate(model.StartDateTime), EndDateTime = ParseUKDate(model.EndDateTime), ColourId = model.ColourId }; //Add the creator as a member User creator = await UoW.Repository<User>().GetByIdAsync(model.CreatorId); if (creator == null) return AddError("Creator doesn't exist"); EventMember member = new EventMember { UserId = creator.Id }; newEvent.Members.Add(member); //Add linked calendar members to the new event foreach (var mem in cal.Members) { //Ignore creator (we just added them) if (mem.UserId == model.CreatorId) continue; //Add all other linked calendar members newEvent.Members.Add(new EventMember { UserId = mem.UserId }); } //Add the parent calendar newEvent.Calendars.Add(cal); //If all day event override start/end times if (newEvent.AllDay) { newEvent.StartDateTime = newEvent.StartDateTime.Date; //Trims the time off the date newEvent.EndDateTime= newEvent.EndDateTime.Date.AddDays(1);//Rounds to the start of the next day } _eventRepo.Insert(newEvent); await SaveChangesAsync(); //Now send out notification to calendar members string message = $"{creator.Name} has created a new event on calendar \"{cal.Name}\""; List<string> deviceIds = new List<string>(); //Build list of device ids (ignoring creator) foreach (var mem in cal.Members) { if (mem.UserId == creator.Id) continue; deviceIds.Add(mem.User.DeviceId); } AndroidGCMPushNotification.NewEventNotification(deviceIds, message, newEvent.Id); Result.Success = true; return Result; } catch (Exception ex) { Result.Error = ex.Message; if (ex.InnerException != null) Result.Error += "\nInner exception: " + ex.InnerException; return Result; } }