public void FiveYearPassByMinute()
        {
            try
            {
                string recurr = "[{\"Recurrence\":\"FREQ=MINUTELY;BYMINUTE=0,4,8,12,16,20,24,28,32,36,40,44,48,52,56;X-EWSOFTWARE-DTSTART=00010101T080000Z\"}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset previous = RecurrenceHelper.GetNextOccurence(DateTimeOffset.UtcNow, "Eastern Standard Time", recurrenceList);

                while (previous < DateTimeOffset.UtcNow.AddYears(5))
                {
                    DateTimeOffset next = RecurrenceHelper.GetNextOccurence(previous, "Eastern Standard Time", recurrenceList);

                    if ((next - previous).TotalMinutes != 4)
                    {
                        Assert.Fail();
                    }

                    previous = next;
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
        public static IQueryable <SqlAppointment> GetSqlAppointmentsByRange(DateTime start, DateTime end)
        {
            var ids = GetSqlAppointmentsIdsByRange(start, end);

            var result = context.SqlAppointments.Where(a => ids.Contains(a.SqlAppointmentId)).ToList <SqlAppointment>();

            // Load the recurrent appointments
            foreach (var item in context.SqlAppointments.Where(a => !string.IsNullOrEmpty(a.RecurrencePattern)))
            {
                if (RecurrenceHelper.IsOccurrenceInRange(item.RecurrencePattern, start, end) && !result.Contains(item))
                {
                    result.Add(item);
                }
            }

            // Load the exceptions
            foreach (var item in context.SqlAppointments.Where(a => a.Start < end && a.SqlExceptionOccurrences.Count != 0))
            {
                if (item.SqlExceptionOccurrences.Any(e => e.SqlExceptionAppointment != null &&
                                                     e.SqlExceptionAppointment.Start >= start &&
                                                     e.SqlExceptionAppointment.End <= end) &&
                    !result.Contains(item))
                {
                    result.Add(item);
                }
            }

            return(result.AsQueryable <SqlAppointment>());
        }
Exemple #3
0
        public async Task <string> SaveScheduleValidation(InspectionScheduleViewModel data)
        {
            var testInspectionSchedule = new InspectionSchedule
            {
                InspectionScheduleId = data.Id,
                ProcessId            = data.ProcessId,
                StartDate            = data.StartTime,
                Timeslot             = (await _prepareService.GetTimeslots(data.TimeslotId)).FirstOrDefault(),
                RecurrenceRule       = data.RecurrenceRule,
                RecurrenceException  = data.RecurrenceException
            };
            var schedules = (await _prepareService.GetInspectionSchedulesNonFilter()).Where(_ => _.ProcessId == data.ProcessId);

            if (data.Id > 0)
            {
                schedules = schedules.Where(s => s.InspectionScheduleId != data.Id);
            }
            //Check validation if schedule data have same inspection in the same timeslot in the same day + recurrence
            var dataDates = RecurrenceHelper.GetRecurrenceDateTimeCollection(testInspectionSchedule);

            foreach (var schedule in schedules)
            {
                var dates     = RecurrenceHelper.GetRecurrenceDateTimeCollection(schedule);
                var intersect = dataDates.Intersect(dates);
                if (intersect.Any())
                {
                    return("L'horaire pour l'inspection sélectionnée, le créneau horaire et la date existe déjà");
                }
            }
            return(string.Empty);
        }
        private void button4_Click(object sender, EventArgs e)
        {
            RecurrenceInfo info = RecurrenceHelper.GetFriendlySeriesInfo(txtGetRecurrenceValues.Text);

            pgrpropertyGrid1.SelectedObject = info;
            tabMain.SelectedTab             = tabProperty;
        }
        private void cmdAdjustEndDateForStartDate_Click(object sender, EventArgs e)
        {
            RecurrenceValues values;

            if (chkUseAdjustedStartDate.Checked)
            {
                values = RecurrenceHelper.GetRecurrenceValues(txtGetRecurrenceValues.Text, dateTimePickerStartDate.Value, dateTimePickerStartDateEndDate.Value);
            }
            else
            {
                values = RecurrenceHelper.GetRecurrenceValues(txtGetRecurrenceValues.Text, dateTimePickerStartDateEndDate.Value);
            }

            txtGetRecurrenceValues.Text = values.GetSeriesInfo();
            lstRecurrenceValues.Items.Clear();
            foreach (DateTime dt in values.Values)
            {
                lstRecurrenceValues.Items.Add(new DateItem(dt));
            }
            if (lstRecurrenceValues.Items.Count > 0)
            {
                lstRecurrenceValues.SelectedIndex = 0;
            }
            txtAdjustedTotal.Text = lstRecurrenceValues.Items.Count.ToString();
        }
        public void InvalidTimePass()
        {
            try
            {
                string recurr = "[{\"Recurrence\":\"FREQ=MINUTELY;BYMINUTE=0,4,8,12,16,20,24,28,32,36,40,44,48,52,56;X-EWSOFTWARE-DTSTART=00010101T080000Z\"}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset justBefore = DateTimeOffset.Parse("3/13/2016 6:59:00 AM +00:00");

                DateTimeOffset drawOpen  = RecurrenceHelper.GetNextOccurence(justBefore, "Eastern Standard Time", recurrenceList);
                DateTimeOffset drawClose = RecurrenceHelper.GetNextOccurence(drawOpen, "Eastern Standard Time", recurrenceList);

                DateTimeOffset expectedOpen  = DateTimeOffset.Parse("3/13/2016 3:00:00 AM -04:00");
                DateTimeOffset expectedClose = DateTimeOffset.Parse("3/13/2016 3:04:00 AM -04:00");

                Assert.AreEqual <DateTimeOffset>(expectedOpen, drawOpen);
                Assert.AreEqual <DateTimeOffset>(expectedClose, drawClose);
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
        // in the instance that a single shift from a recurring set needs to have its reminder scheduled
        // (e.g. when a shift is having its original properties restored),
        // the datetime of the selected shift will be passed in
        public bool ScheduleReminder(Shift shift)
        {
            try
            {
                //schedule email notification for shift if shift is after todays date if it's not an open shift
                if (shift.VolunteerProfileId != null || shift.VolunteerProfileId > 0)
                {
                    // if shift is recurring, check each child shift to see if the recurrence period requires reminders
                    if (shift.IsRecurrence)
                    {
                        var recurrenceDates = RecurrenceHelper.GetRecurrenceDateTimeCollection(shift.RecurrenceRule, shift.StartTime);
                        if (recurrenceDates.Any(d => d > DateTime.Now.AddDays(1).Date))
                        {
                            var volunteerAccount = _context.Users.FirstOrDefault(u => u.VolunteerProfile.Id == shift.VolunteerProfileId);
                            ScheduleReminderForRecurringShifts(volunteerAccount, shift);
                        }
                    }
                    // if it isn't recurring then simply schedule a reminder
                    else if (shift.StartTime > DateTime.Now.AddDays(1).Date)
                    {
                        var volunteerAccount = _context.Users.FirstOrDefault(u => u.VolunteerProfile.Id == shift.VolunteerProfileId);
                        ScheduleReminderForSingleShift(volunteerAccount, shift);
                    }
                }

                _logger.LogInformation($"A new reminder was successfully scheduled for shift {shift.Id} on {shift.StartTime.Date.AddHours(-6)}");
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to schedule a new reminder for shift {shift.Id} on {shift.StartTime.Date.AddHours(-6)} \n Error Message: {ex.Message}");
                return(true);
            }
        }
Exemple #8
0
        public JsonResult getDates(string dates)
        {
            var recurrenceRule = JsonConvert.DeserializeObject <string>(dates);
            var dateCollection = RecurrenceHelper.GetRecurrenceDateTimeCollection(recurrenceRule, DateTime.Now);

            return(Json(dateCollection, JsonRequestBehavior.AllowGet));
        }
        private async Task ScheduleReminderForRecurringShifts(AppUser volunteer, Shift shift)
        {
            // then schedule a reminder for each child shift that needs one
            var childShiftDates = RecurrenceHelper.GetRecurrenceDateTimeCollection(shift.RecurrenceRule, shift.StartTime);

            foreach (var date in childShiftDates)
            {
                // only schedule a reminder if the date is the next day or after, and if there isn't already a scheduled reminder
                // there might already be a scheduled reminder since the caller might removing a shift from a recurring set
                bool isFutureShift       = date > DateTime.Now.AddDays(1).Date;
                bool noScheduledReminder = !_context.Reminders.Any(r => r.ShiftId == shift.Id && r.ShiftDate == date);
                if (isFutureShift && noScheduledReminder)
                {
                    string idForRecurring = "";
                    if (!_isTesting)
                    {
                        idForRecurring = BackgroundJob.Schedule(() =>
                                                                _emailSender.SendEmailAsync(volunteer.Email, "Volunteering Reminder - MHFB", CreateEmail(volunteer, shift)),
                                                                date.AddHours(-6));
                    }

                    var reminders = await _context.Reminders.ToListAsync();

                    idForRecurring = (reminders.Max(p => p.Id) + 1).ToString();

                    _context.Add(new Reminder()
                    {
                        ShiftId = shift.Id, ShiftDate = date, HangfireJobId = idForRecurring
                    });
                }
            }

            _context.SaveChanges();
        }
        public void FiveYearPassBySecond()
        {
            try
            {
                string recurr = "[{\"Recurrence\":\"FREQ=SECONDLY;BYSECOND=50;X-EWSOFTWARE-DTSTART=20160108T210153Z\"}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset previous = RecurrenceHelper.GetNextOccurence(DateTimeOffset.UtcNow, "Eastern Standard Time", recurrenceList);

                while (previous < DateTimeOffset.UtcNow.AddYears(5))
                {
                    DateTimeOffset next = RecurrenceHelper.GetNextOccurence(previous, "Eastern Standard Time", recurrenceList);

                    if ((next - previous).TotalMinutes != 1)
                    {
                        Assert.Fail();
                    }

                    previous = next;
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            string pattern = RecurrenceHelper.GetPatternDefinitioin(txtGetRecurrenceValues.Text);
            PatternDefinitionViewer frm = new PatternDefinitionViewer();

            frm.LoadPattern(pattern);
            frm.Show(this);
        }
        public List <Shift> GetWorkablShiftsForVolunteer(VolunteerProfile volunteer)
        {
            // find all nonrecurring shifts that agree with the given availabilites
            if (_context.Shifts.Any())
            {
                _context.Entry(volunteer).Collection(v => v.Availabilities).Load();
                _context.Entry(volunteer).Reference(v => v.Positions).Load();

                List <Shift> availableShifts = new List <Shift>();

                foreach (var shift in _context.Shifts.Where(s => string.IsNullOrEmpty(s.RecurrenceRule)))
                {
                    if (shift.Volunteer == null &&
                        shift.StartTime > DateTime.Now &&
                        volunteer.Availabilities
                        .Any(a =>
                             shift.StartTime.TimeOfDay >= a.StartTime &&
                             shift.EndTime.TimeOfDay <= a.EndTime &&
                             Enum.GetName(typeof(DayOfWeek), shift.StartTime.DayOfWeek).ToLower() == a.AvailableDay) &&
                        volunteer.Positions.Any(p => p.Id == shift.PositionId))
                    {
                        availableShifts.Add(shift);
                    }
                }

                // find all recurring shifts that agree with the given availabilities
                foreach (var recurringShift in _context.Shifts.Where(s => !string.IsNullOrWhiteSpace(s.RecurrenceRule)))
                {
                    var childShiftDates = RecurrenceHelper.GetRecurrenceDateTimeCollection(recurringShift.RecurrenceRule, recurringShift.StartTime);
                    foreach (var date in childShiftDates)
                    {
                        bool dateIsAvailable = recurringShift.Volunteer == null && date > DateTime.Now.Date.AddDays(1) &&
                                               volunteer.Availabilities
                                               .Any(a => recurringShift.StartTime.TimeOfDay >= a.StartTime && recurringShift.EndTime.TimeOfDay <= a.EndTime) &&
                                               volunteer.Positions.Any(p => p.Id == recurringShift.PositionId);

                        if (dateIsAvailable)
                        {
                            var availableShift = new Shift()
                            {
                                StartTime = date + recurringShift.StartTime.TimeOfDay,
                                EndTime   = date + recurringShift.EndTime.TimeOfDay,
                                Position  = recurringShift.Position
                            };

                            availableShifts.Add(availableShift);
                        }
                    }
                }

                // order shifts by ascending date
                return(availableShifts.OrderBy(s => s.StartTime).ToList());
            }
            return(null);
        }
        public IActionResult Put(ScheduleModel model)
        {
            model.UserProfileId = User.Identity.GetUserProfileId() ?? default(long);
            if (ModelState.IsValid)
            {
                var dates = model.RecurrenceRule != null?RecurrenceHelper.GetRecurrenceDateTimeCollection(model.RecurrenceRule, model.StartDate) : null;

                var result = _scheduleService.EditSchedule(model, dates);

                return(Json(result));
            }
            return(PartialView("_EditPartial", model));
        }
        private void btnGetRecurrenceValues_Click(object sender, EventArgs e)
        {
            RecurrenceValues values = RecurrenceHelper.GetRecurrenceValues(txtGetRecurrenceValues.Text);

            lstRecurrenceValues.Items.Clear();
            foreach (DateTime dt in values.Values)
            {
                lstRecurrenceValues.Items.Add(new DateItem(dt));
            }
            if (lstRecurrenceValues.Items.Count > 0)
            {
                lstRecurrenceValues.SelectedIndex = 0;
            }
            txtAdjustedTotal.Text = lstRecurrenceValues.Items.Count.ToString();
        }
        private void button1_Click_2(object sender, EventArgs e)
        {
            RecurrenceValues values = RecurrenceHelper.GetPostRecurrenceValues(txtGetRecurrenceValues.Text, dateTimePicker1.Value);

            txtGetRecurrenceValues.Text = values.GetSeriesInfo();
            lstRecurrenceValues.Items.Clear();
            foreach (DateTime dt in values.Values)
            {
                lstRecurrenceValues.Items.Add(new DateItem(dt));
            }
            if (lstRecurrenceValues.Items.Count > 0)
            {
                lstRecurrenceValues.SelectedIndex = 0;
            }
            txtAdjustedTotal.Text = lstRecurrenceValues.Items.Count.ToString();
        }
        public void PreviousSuccess()
        {
            try
            {
                string recurr = "[{\"Recurrence\":\"FREQ=MINUTELY;BYMINUTE=0,4,8,12,16,20,24,28,32,36,40,44,48,52,56;X-EWSOFTWARE-DTSTART=00010101T080000Z\"}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset previous = RecurrenceHelper.GetPreviousOccurence(DateTimeOffset.UtcNow, "Eastern Standard Time", recurrenceList);
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
        public void FiveYearPassByWeek()
        {
            try
            {
                string timeZoneId = "Eastern Standard Time";

                TimeZoneInfo authorityTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);

                int hour = 21;

                string recurr = $"[{{\"Recurrence\":\"FREQ=WEEKLY;BYDAY=SA;BYHOUR={hour}\"}}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset previous = RecurrenceHelper.GetNextOccurence(DateTimeOffset.UtcNow, timeZoneId, recurrenceList);

                while (previous < DateTimeOffset.UtcNow.AddYears(5))
                {
                    DateTimeOffset next = RecurrenceHelper.GetNextOccurence(previous, timeZoneId, recurrenceList);

                    DateTime authorityTime = TimeZoneInfo.ConvertTimeFromUtc(next.UtcDateTime, authorityTimeZone);

                    Debug.WriteLine($"{authorityTime} {next.Offset}");

                    if (authorityTime.Hour != hour)
                    {
                        Assert.Fail();
                    }

                    if (authorityTime.DayOfWeek != DayOfWeek.Saturday)
                    {
                        Assert.Fail();
                    }

                    previous = next;
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
        public void OccurrsOnSuccess()
        {
            try
            {
                string recurr = "[{\"Recurrence\":\"FREQ=MINUTELY;BYMINUTE=0,4,8,12,16,20,24,28,32,36,40,44,48,52,56;X-EWSOFTWARE-DTSTART=00010101T080000Z\"}]";

                var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

                DateTimeOffset now = new DateTimeOffset(2019, 1, 1, 1, 4, 0, TimeSpan.Zero);

                bool occursOn = RecurrenceHelper.OccursOn(recurrenceList, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), now);

                Assert.IsTrue(occursOn);
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Assert.Fail();
            }
        }
Exemple #19
0
        // private methods exclusive to this class
        // this method cancels the reminder for the shift being removed as a side effect
        private async Task <bool?> CheckIfShiftIsBeingRemovedFromRecurringSet(ShiftReadEditDto newShiftDto, Shift shiftBeingUpdated)
        {
            // determine if the shift selected for change is a shift that's being removed from its recurring set.
            // this is done by comparing the amount of exdates in the old recshift to the amount in the new recshift.
            // if the new shift has more exdates than the old shift, a child shift is being removed
            var oldExDates = shiftBeingUpdated.RecurrenceException == null ?
                             new List <DateTime>() :
                             RecurrenceHelper.ConvertExDateStringToDateTimes(shiftBeingUpdated.RecurrenceException);

            var newExDates = newShiftDto.RecurrenceException == null ?
                             new List <DateTime>() :
                             RecurrenceHelper.ConvertExDateStringToDateTimes(newShiftDto.RecurrenceException);

            bool shiftIsBeingRemovedFromRecurringSet = newExDates.Count() > oldExDates.Count();

            // if shift is being removed, pass in the date of the last shift excluded when cancelling reminder and update exdate list
            try
            {
                if (shiftIsBeingRemovedFromRecurringSet)
                {
                    var newExDate = newExDates.Last();
                    _reminderManager.CancelReminder(shiftBeingUpdated, newExDate);

                    shiftBeingUpdated.RecurrenceException = newShiftDto.RecurrenceException;
                    await _context.SaveChangesAsync();

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong when trying to cancel a reminder for a shift being removed from its recurring set. \nError Message:\n{ex.Message}");
                return(null);
            }
        }
        public void AmbiguousTimeSuccess()
        {
            string recurr = "[{\"Recurrence\":\"FREQ=MINUTELY;BYMINUTE=0,4,8,12,16,20,24,28,32,36,40,44,48,52,56;X-EWSOFTWARE-DTSTART=00010101T080000Z\"}]";

            var recurrenceList = JsonConvert.DeserializeObject <List <Recurrence> >(recurr);

            DateTimeOffset justBefore = DateTimeOffset.Parse("11/6/2016 4:59:00 AM +00:00");

            DateTimeOffset drawOpen  = RecurrenceHelper.GetNextOccurence(justBefore, "Eastern Standard Time", recurrenceList);
            DateTimeOffset drawClose = RecurrenceHelper.GetNextOccurence(drawOpen, "Eastern Standard Time", recurrenceList);

            DateTimeOffset expectedOpen  = DateTimeOffset.Parse("11/6/2016 1:00:00 AM -04:00");
            DateTimeOffset expectedClose = DateTimeOffset.Parse("11/6/2016 1:04:00 AM -04:00");

            Assert.AreEqual <DateTimeOffset>(expectedOpen, drawOpen);
            Assert.AreEqual <DateTimeOffset>(expectedClose, drawClose);

            justBefore = DateTimeOffset.Parse("11/6/2016 5:59:00 AM +00:00");

            drawOpen  = RecurrenceHelper.GetNextOccurence(justBefore, "Eastern Standard Time", recurrenceList);
            drawClose = RecurrenceHelper.GetNextOccurence(drawOpen, "Eastern Standard Time", recurrenceList);

            expectedOpen  = DateTimeOffset.Parse("11/6/2016 1:00:00 AM -05:00");
            expectedClose = DateTimeOffset.Parse("11/6/2016 1:04:00 AM -05:00");

            Assert.AreEqual <DateTimeOffset>(expectedOpen, drawOpen);
            Assert.AreEqual <DateTimeOffset>(expectedClose, drawClose);

            justBefore = DateTimeOffset.Parse("11/6/2016 6:59:00 AM +00:00");

            drawOpen  = RecurrenceHelper.GetNextOccurence(justBefore, "Eastern Standard Time", recurrenceList);
            drawClose = RecurrenceHelper.GetNextOccurence(drawOpen, "Eastern Standard Time", recurrenceList);

            expectedOpen  = DateTimeOffset.Parse("11/6/2016 2:00:00 AM -05:00");
            expectedClose = DateTimeOffset.Parse("11/6/2016 2:04:00 AM -05:00");

            Assert.AreEqual <DateTimeOffset>(expectedOpen, drawOpen);
            Assert.AreEqual <DateTimeOffset>(expectedClose, drawClose);
        }
        public async Task <IActionResult> GetSalary(Guid userId, DateTime from, DateTime to)
        {
            var result = (await _schedulerAppointmentService.GetAllAsync(userId))
                         .Select((x) => new SchedulerAppointmentEntity
            {
                TaskName            = x.task_name,
                Price               = x.price,
                Start               = x.start,
                End                 = x.end,
                RecurrenceId        = x.recurrence_id,
                RecurrenceRule      = x.recurrence_rule,
                RecurrenceException = x.recurrence_exception,
                IsAllDay            = x.is_all_day,
                IsOff               = x.is_off,
                Notes               = x.notes
            })
                         .Where(x => x.Start.Date >= from.Date && x.Start.Date <= to.Date)
                         .ToList();

            var eventItems = result
                             .Where(x => string.IsNullOrEmpty(x.RecurrenceRule))
                             .Select(x => new SalaryItem
            {
                TaskName = x.TaskName,
                Price    = x.Price,
                Start    = x.Start,
                End      = x.End,
                IsAllDay = x.IsAllDay,
                IsOff    = x.IsOff,
                Notes    = x.Notes
            })
                             .ToList();

            var recurrenceEvents = result.Where(x => !string.IsNullOrEmpty(x.RecurrenceRule));

            foreach (var item in recurrenceEvents)
            {
                IEnumerable <DateTime> fromCollection = null;
                var itemCount   = 0;
                var loopAttempt = 0;
                do
                {
                    itemCount += 100;
                    if (!string.IsNullOrEmpty(item.RecurrenceException))
                    {
                        fromCollection = RecurrenceHelper.GetRecurrenceDateTimeCollection(item.RecurrenceRule, item.Start, item.RecurrenceException, itemCount)
                                         .Where(x => x.Date <= to.Date);
                    }
                    else
                    {
                        fromCollection = RecurrenceHelper.GetRecurrenceDateTimeCollection(item.RecurrenceRule, item.Start, itemCount)
                                         .Where(x => x.Date <= to.Date);
                    }
                    loopAttempt++;
                } while (loopAttempt < 2 && fromCollection.Count() == 0);

                var recurrenceItems = fromCollection.Select(x => new SalaryItem
                {
                    TaskName = item.TaskName,
                    Price    = item.Price,
                    Start    = new DateTime(x.Date.Year, x.Date.Month, x.Date.Day, item.Start.Hour, item.Start.Minute, item.Start.Second),
                    End      = new DateTime(x.Date.Year, x.Date.Month, x.Date.Day, item.End.Hour, item.End.Minute, item.End.Second),
                    IsAllDay = item.IsAllDay,
                    IsOff    = item.IsOff,
                    Notes    = item.Notes
                })
                                      .ToList();
                eventItems.AddRange(recurrenceItems);
            }
            return(Ok(eventItems.OrderByDescending(x => x.Start)));
        }
        public async Task <JsonResult> OnPostGetShifts([FromBody] CRUDModel model)
        {
            List <Shift> displayedShifts = new List <Shift>();

            if (model.Params.ContainsKey("type"))
            {
                if (model.Params["type"].ToString() == "open")
                {
                    var openShifts = _context.Shifts.Where(s => s.VolunteerProfileId == null).ToList();
                    displayedShifts = FilterShiftsByDate(openShifts);
                }
                else
                {
                    var user = await _userManager.GetUserAsync(User);

                    await _context.Entry(user).Reference(u => u.VolunteerProfile).LoadAsync();

                    await _context.Entry(user.VolunteerProfile).Collection(v => v.Shifts).LoadAsync();

                    var userShifts = user.VolunteerProfile.Shifts;
                    displayedShifts = FilterShiftsByDate(userShifts);
                }
            }
            else if (model.Params.ContainsKey("shiftId"))
            {
                var user = await _userManager.GetUserAsync(User);

                await _context.Entry(user).Reference(u => u.VolunteerProfile).LoadAsync();

                int   shiftId       = Convert.ToInt32(model.Params["shiftId"]);
                Shift selectedShift = await _context.Shifts.FirstOrDefaultAsync(s => s.Id == shiftId);

                if (model.Params.ContainsKey("startDate"))
                {
                    var selectedStartDate = ConvertSyncfusionDateStringToDateTime(model.Params["startDate"].ToString());
                    var excludedShift     = new Shift()
                    {
                        StartTime    = selectedStartDate,
                        EndTime      = selectedStartDate + selectedShift.EndTime.Date.TimeOfDay,
                        IsAllDay     = selectedShift.IsAllDay,
                        IsBlock      = selectedShift.IsBlock,
                        Subject      = selectedShift.Subject,
                        Position     = selectedShift.Position,
                        Volunteer    = user.VolunteerProfile,
                        RecurrenceID = selectedShift.Id
                    };

                    selectedShift.RecurrenceException += RecurrenceHelper.ConvertDateTimeToExDateString(selectedStartDate);
                    _context.Add(excludedShift);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    selectedShift.Volunteer = user.VolunteerProfile;
                }

                var openShifts = _context.Shifts.Where(s => s.VolunteerProfileId == null).ToList();
                displayedShifts = FilterShiftsByDate(openShifts);
            }
            else
            {
                var user = await _userManager.GetUserAsync(User);

                await _context.Entry(user).Reference(u => u.VolunteerProfile).LoadAsync();

                await _context.Entry(user.VolunteerProfile).Collection(v => v.Shifts).LoadAsync();

                var userShifts = user.VolunteerProfile.Shifts;
                displayedShifts = FilterShiftsByDate(userShifts);
            }

            return(new JsonResult(_mapper.Map <List <ShiftReadEditDto> >(displayedShifts)));
        }
        private void button1_Click(object sender, EventArgs e)
        {
            RecurrenceValues values = null;

            switch (tabControl1.SelectedIndex)
            {
            case 0:     // Daily
                DailyRecurrenceSettings da;
                if (radioOccurrences.Checked)
                {
                    da = new DailyRecurrenceSettings(dtStartDate.Value, Convert.ToInt32(txtOccurrences.Text));
                }
                else
                {
                    da = new DailyRecurrenceSettings(dtStartDate.Value, dtEndDate.Value);
                }

                if (radioButton1.Checked)
                {
                    values = da.GetValues(int.Parse(textBox1.Text));
                }
                else
                {
                    values = da.GetValues(1, DailyRegenType.OnEveryWeekday);
                }
                break;

            case 1:     // Weekly
                WeeklyRecurrenceSettings we;
                SelectedDayOfWeekValues  selectedValues = new SelectedDayOfWeekValues();

                if (radioOccurrences.Checked)
                {
                    we = new WeeklyRecurrenceSettings(dtStartDate.Value, Convert.ToInt32(txtOccurrences.Text));
                }
                else
                {
                    we = new WeeklyRecurrenceSettings(dtStartDate.Value, dtEndDate.Value);
                }

                selectedValues.Sunday    = chkSunday.Checked;
                selectedValues.Monday    = chkMonday.Checked;
                selectedValues.Tuesday   = chkTuesday.Checked;
                selectedValues.Wednesday = chkWednesday.Checked;
                selectedValues.Thursday  = chkThursday.Checked;
                selectedValues.Friday    = chkFriday.Checked;
                selectedValues.Saturday  = chkSaturday.Checked;

                values = we.GetValues(int.Parse(txtWeeklyRegenXWeeks.Text), selectedValues);
                break;

            case 2:     // Monthly
                MonthlyRecurrenceSettings mo;
                if (radioOccurrences.Checked)
                {
                    mo = new MonthlyRecurrenceSettings(dtStartDate.Value, Convert.ToInt32(txtOccurrences.Text));
                }
                else
                {
                    mo = new MonthlyRecurrenceSettings(dtStartDate.Value, dtEndDate.Value);
                }


                if (radioButton3.Checked)
                {
                    values = mo.GetValues(int.Parse(textBox4.Text), Convert.ToInt32(textBox2.Text));
                }
                else
                {
                    // Get the adjusted values
                    mo.AdjustmentValue = int.Parse(txtMonthlyAdjustedValue.Text);
                    values             = mo.GetValues((MonthlySpecificDatePartOne)comboBox2.SelectedIndex, (MonthlySpecificDatePartTwo)comboBox3.SelectedIndex, int.Parse(textBox3.Text));
                }
                break;

            case 3:     // Yearly
                YearlyRecurrenceSettings yr;
                if (radioOccurrences.Checked)
                {
                    yr = new YearlyRecurrenceSettings(dtStartDate.Value, Convert.ToInt32(txtOccurrences.Text));
                }
                else
                {
                    yr = new YearlyRecurrenceSettings(dtStartDate.Value, dtEndDate.Value);
                }


                if (radioYearlyEvery.Checked)
                {
                    values = yr.GetValues(int.Parse(txtYearEvery.Text), cboYearEveryMonth.SelectedIndex + 1);
                }
                else
                {
                    // Get the adjusted value
                    yr.AdjustmentValue = int.Parse(txtYearlyAdjustedValue.Text);
                    values             = yr.GetValues((YearlySpecificDatePartOne)comboBox5.SelectedIndex, (YearlySpecificDatePartTwo)comboBox4.SelectedIndex, (YearlySpecificDatePartThree)(comboBox6.SelectedIndex + 1));
                }
                break;
            }

            txtSeriesInfo.Text          = values.GetSeriesInfo();
            txtGetRecurrenceValues.Text = txtSeriesInfo.Text;

            lstResults.Items.Clear();
            DateTime[] bolded  = new DateTime[values.Values.Count];
            int        counter = 0;

            foreach (DateTime dt in values.Values)
            {
                bolded[counter] = dt;
                lstResults.Items.Add(new DateItem(dt));
                counter++;
            }
            monthCalendar1.BoldedDates = bolded;

            if (lstResults.Items.Count > 0)
            {
                lstResults.SelectedIndex = 0;
            }

            txtTotal.Text          = lstResults.Items.Count.ToString();
            txtEndDate.Text        = values.EndDate.ToShortDateString();
            txtStartDate.Text      = values.StartDate.ToShortDateString();
            btnGetNextDate.Enabled = lstResults.Items.Count > 0;
            txtNextDate.Text       = string.Empty;
            lstRecurrenceValues.Items.Clear();
            tabMain.SelectedTab   = tabSecond;
            txtAdjustedTotal.Text = lstRecurrenceValues.Items.Count.ToString();

            // Get reccurrence info object to use for setting controls
            RecurrenceInfo info = RecurrenceHelper.GetFriendlySeriesInfo(values.GetSeriesInfo());

            dateTimePickerStartDate.Value = info.StartDate;
            if (info.EndDate.HasValue)
            {
                dateTimePickerStartDateEndDate.Value = info.EndDate.Value;
                dtAdjustedDateTime.Value             = info.EndDate.Value;
                dateTimePicker1.Value = info.EndDate.Value;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            DateItem dt = (DateItem)lstResults.SelectedItem;

            txtNextDate.Text = RecurrenceHelper.GetNextDate(dt.Value, txtSeriesInfo.Text).ToString("d MMM, yyyy   ddd");
        }