public async Task<IHttpActionResult> CalendarMembers(CalendarMembersDTO model)
        {
            if (!ModelState.IsValid) return BadRequest();

            ValidationResult result = await _memberService.UpdateCalendarMembers(model);

            if (result.Success)
                return Ok();

            return BadRequest(result.Error);
        }
Exemplo n.º 2
0
        public async Task<ValidationResult> UpdateCalendarMembers(CalendarMembersDTO model)
        {
            try
            {
                //First load the member ids
                List<int> memberIds = await _calendarMemberRepo.Get(x => x.CalendarId == model.CalendarId)
                    .Select(x => x.UserId)
                    .ToListAsync();

                //Split the Ids string and create list of integers
                List<int> ids = model.MemberIds.Split(',').Select(int.Parse).ToList();

                //Calculate the members set for removal
                List<int> removedMemberIds = memberIds.Except(ids).ToList();

                foreach (var id in removedMemberIds)
                {
                    //Get all of the members events for the calendar
                    var events = await _calendarRepo.Get(x => x.Id == model.CalendarId)
                        .SelectMany(x => x.Events)
                        .SelectMany(x => x.Members)
                        .Where(m => m.UserId == id)
                        .ToListAsync();

                    //Remove the member from those events
                    foreach (var e in events)
                    {
                        _eventMemberRepo.Delete(e);
                    }

                    //Unlink the member(s) from the calendars
                    CalendarMember calMem =
                        await _calendarMemberRepo.Get(x => x.CalendarId == model.CalendarId && x.UserId == id)
                            .FirstOrDefaultAsync();
                    _calendarMemberRepo.Delete(calMem);
                }

                //Check we have at least the owner member
                if (removedMemberIds.Count >= memberIds.Count) return AddError("Unable to update calendar members");

                await SaveChangesAsync();

                Result.Success = true;
                return Result;
            }
            catch (Exception ex)
            {
                return AddError(ex.Message);
            }
        }