public void AnniversaryTest2()
        {
            var anniversary = new Anniversary()
            {
                Day = 5,
                Month = 6
            };

            var aEvent = new Event()
            {
                ID = 1,
                Title = "Give Flowers to Wife",
                Frequency = 16, // yearly
                Anniversary = anniversary
            };

            var schedule = new Schedule(aEvent);
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2009, 6, 4)));

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2010, 1, 1),
                EndDateTime = new DateTime(2020, 12, 31)
            };

            var occurrences = schedule.Occurrences(range).ToList();
            Assert.IsTrue(occurrences.Count.Equals(11));
        }
        /// <summary>
        /// The canonical Critical Mass monthly bicycle ride
        /// </summary>
        public static void Run()
        {
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Running monthly scenario 1.");
            Console.WriteLine(Environment.NewLine);

            var aEvent = new Event()
            {
                ID = 1,
                Title = "Critical Mass",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                MonthlyIntervalOptions = MonthlyIntervalEnum.Last,
                DaysOfWeekOptions = DayOfWeekEnum.Fri
            };

            var during = new DateRange()
            {
                StartDateTime = new DateTime(2013, 12, 1),
                EndDateTime = new DateTime(2013, 12, 31)
            };

            var schedule = new Schedule(aEvent);
            var dates = schedule.Occurrences(during);
            foreach (var date in dates)
            {
                Console.WriteLine(date.ToShortDateString());
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Printed out all dates between {0} and {1}", 
                during.StartDateTime.ToShortDateString(), 
                during.EndDateTime.ToShortDateString());
        }
Beispiel #3
0
        public void YearTest2()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 2",
                FrequencyTypeOptions = FrequencyTypeEnum.Yearly,
                Anniversary = new Anniversary()
                {
                    Month = 9,
                    Day = 27
                }
            };

            var schedule = new Schedule(aEvent);
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2014, 9, 27)));
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2015, 9, 27)));
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2016, 9, 27)));

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2012, 1, 1),
                EndDateTime = new DateTime(2016, 12, 31)
            };

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(5, occurrences.Count());
            Assert.AreEqual(new DateTime(2012, 9, 27), occurrences.First());
            Assert.AreEqual(new DateTime(2016, 9, 27), occurrences.Last());
        }
        public void OneTimeOnlyTest2()
        {
            var laborDay = new DateTime(2012, 9, 1);

            var aEvent = new Event()
            {
                ID = 1,
                Title = "Labor Day Extravaganza",
                Frequency = 0,        // one-time only
                OneTimeOnlyEventDate = laborDay,
                MonthlyInterval = 0,  // not applicable
                DaysOfWeek = 0        // not applicable
            };

            var schedule = new Schedule(aEvent);

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2012, 8, 1),
                EndDateTime = new DateTime(2012, 10, 1)
            };

            var occurrences = schedule.Occurrences(range);
            var count = 0;
            using (var items = occurrences.GetEnumerator())
            {
                while (items.MoveNext())
                    count++;
            }

            Assert.IsTrue(count > 0);
        }
        public void EventOptionsPreviousOccurrenceTest()
        {
            var holidays = GetHolidays();
            var aEvent = CreateStreetCleaningEvent();
            var schedule = new Schedule(aEvent, holidays);

            Assert.IsNotNull(holidays);
            Assert.IsNotNull(aEvent);
            Assert.IsNotNull(schedule);

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2016, 1, 1),
                EndDateTime = new DateTime(2016, 12, 31)
            };

            foreach (var item in schedule.Occurrences(range))
            {
                System.Diagnostics.Debug.WriteLine(item);
            }

            var prev = schedule.PreviousOccurrence(new DateTime(2016, 6, 6));
            Assert.IsTrue(prev.Equals(new DateTime(2016, 5, 16)));
            Assert.IsFalse(prev.Equals(new DateTime(2016, 6, 6)));
            Assert.IsFalse(prev.Equals(new DateTime(2016, 6, 20)));
        }
Beispiel #6
0
        public void MonthTest1()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 1",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                MonthlyIntervalOptions = MonthlyIntervalEnum.EveryWeek,
                DaysOfWeekOptions = DayOfWeekEnum.Mon | DayOfWeekEnum.Fri
            };

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2013, 1, 15),
                EndDateTime = new DateTime(2013, 4, 30)
            };

            var occurringDate = new DateTime(2013, 1, 21);

            var schedule = new Schedule(aEvent);
            Assert.IsTrue(schedule.IsOccurring(occurringDate));

            var previousOccurrence = schedule.PreviousOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 1, 18), previousOccurrence.Value);

            var nextOccurrence = schedule.NextOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 1, 25), nextOccurrence.Value);

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(30, occurrences.Count());
            Assert.AreEqual(new DateTime(2013, 1, 18), occurrences.First());
            Assert.AreEqual(new DateTime(2013, 4, 29), occurrences.Last());
        }
        public static void Run()
        {
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Running daily scenario 1 with a StartDateTime value of 12/1/2013");
            Console.WriteLine(Environment.NewLine);

            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 1",
                Frequency = 1,        // daily
                MonthlyInterval = 0,  // not applicable
                DaysOfWeek = 127,     // every day of week
                StartDateTime = new DateTime(2013, 12, 1)
            };

            var during = new DateRange()
            {
                StartDateTime = new DateTime(2013, 12, 1),
                EndDateTime = new DateTime(2013, 12, 31)
            };

            var schedule = new Schedule(aEvent);
            var dates = schedule.Occurrences(during);
            foreach (var date in dates)
            {
                Console.WriteLine(date.ToShortDateString());
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Printed out all dates between {0} and {1}",
                during.StartDateTime.ToShortDateString(),
                during.EndDateTime.ToShortDateString());
        }
Beispiel #8
0
 /// <summary>
 /// GetCompressedDateRange,
 /// This will compress the specified date range to fit inside of the specified limits.
 /// If these two date ranges do not overlap, this will throw an ArgumentOutOfRangeException.
 /// </summary>
 public static DateRange GetCompressedDateRange(DateRange suppliedRange, DateRange newLimits)
 {
     if (!DoDateRangesOverlap(suppliedRange, newLimits))
         throw new ArgumentOutOfRangeException();
     DateRange resultRange = new DateRange();
     resultRange.StartDateTime = (suppliedRange.StartDateTime < newLimits.StartDateTime) ?
         newLimits.StartDateTime : suppliedRange.StartDateTime;
     if (resultRange.StartDateTime > newLimits.EndDateTime)
         resultRange.StartDateTime = newLimits.EndDateTime;
     resultRange.EndDateTime = (suppliedRange.EndDateTime > newLimits.EndDateTime) ?
         newLimits.EndDateTime : suppliedRange.EndDateTime;
     if (resultRange.EndDateTime < newLimits.StartDateTime)
         resultRange.EndDateTime = newLimits.StartDateTime;
     return resultRange;
 }
        public void TestMontlyCalendar()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Critical Mass",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                MonthlyIntervalOptions = MonthlyIntervalEnum.First,
                DaysOfWeekOptions = DayOfWeekEnum.Fri
            }; var schedule = new Schedule(aEvent);
            var range = new DateRange()
            {
                StartDateTime = DateTime.Now,
                EndDateTime = DateTime.Now.AddYears(1)
            };
            var occurrences = schedule.Occurrences(range);

        }
 private IEnumerable<object> GetSpecificNumberOfOccurrencesForDateRange(ScheduleDTO scheduleDTO, DateRange range)
 {
     var calendarObjects = new List<object>();
     var occurrences = scheduleDTO.Schedule.Occurrences(range).ToArray();
     for (var i = 0; i < scheduleDTO.NumberOfOccurrences; i++)
     {
         var date = occurrences.ElementAtOrDefault(i);
         calendarObjects.Add(new
         {
             id = scheduleDTO.ID,
             title = scheduleDTO.Title,
             start = ToUnixTimestamp(date + scheduleDTO.StartTime),
             end = ToUnixTimestamp(date + scheduleDTO.EndTime),
             url = Url.Action("ScheduleOccurrence", "Home", new { id = scheduleDTO.ID, occurrenceDate = date }),
             allDay = false
         });
     }
     return calendarObjects;
 }
        public JsonResult GetSchedules(double start, double end)
        {
            var calendarObjects = new List<object>();  

            var range = new DateRange()
            {
                StartDateTime = FromUnixTimestamp(start),
                EndDateTime = FromUnixTimestamp(end)
            };
            
            var repository = new ScheduleRepository();
            var schedules = repository.GetAllSchedules().ToList();
            foreach (var schedule in schedules)
            {
                calendarObjects
                    .AddRange(schedule.NumberOfOccurrences > 0 
                    ? GetSpecificNumberOfOccurrencesForDateRange(schedule, range)
                    : GetAllOccurrencesForDateRange(schedule, range));
            }

            return Json(calendarObjects.ToArray(), JsonRequestBehavior.AllowGet);
        }
Beispiel #12
0
        public void MonthTest2()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 2",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                RepeatInterval = 2,
                MonthlyIntervalOptions = MonthlyIntervalEnum.Last,
                DaysOfWeekOptions = DayOfWeekEnum.Mon | DayOfWeekEnum.Fri,
                StartDateTime = new DateTime(2013, 1, 15)
            };

            var range = new DateRange()
            {
                StartDateTime = aEvent.StartDateTime.Value,
                EndDateTime = new DateTime(2013, 4, 30)
            };

            var nonOccurringDate = new DateTime(2013, 1, 29);

            var schedule = new Schedule(aEvent);
            Assert.IsFalse(schedule.IsOccurring(nonOccurringDate));

            var previousOccurrence = schedule.PreviousOccurrence(nonOccurringDate, range);
            Assert.AreEqual(new DateTime(2013, 1, 28), previousOccurrence.Value);

            var nextOccurrence = schedule.NextOccurrence(nonOccurringDate, range);
            Assert.AreEqual(new DateTime(2013, 3, 25), nextOccurrence.Value);

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(4, occurrences.Count());
            Assert.AreEqual(new DateTime(2013, 1, 25), occurrences.First());
            Assert.AreEqual(new DateTime(2013, 3, 29), occurrences.Last());
        }
        private List<EventsOverviewModel> GetRecurringEvents(int id, int start = 0, int end = 0)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;

            //Handle recurring events
            List<EventsOverviewModel> events = new List<EventsOverviewModel>();

            DateTime startDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            startDate = startDate.AddSeconds(start);
            DateTime endDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            endDate = endDate.AddSeconds(end);

            DateRange range = new DateRange();
            range.StartDateTime = startDate;
            range.EndDateTime = endDate;

            var calendar = db.SingleOrDefault<ECalendar>(id);
            var recurring_events = db.Query<RecurringEvent>("SELECT * FROM ec_recevents WHERE calendarId = @0 ORDER BY id DESC", id).ToList();
            foreach (var e in recurring_events)
            {
                var schedule = new Schedule(
                    new ScheduleWidget.ScheduledEvents.Event()
                    {
                        Title = e.title,
                        ID = e.Id,
                        DaysOfWeekOptions = (DayOfWeekEnum)e.day,
                        FrequencyTypeOptions = (FrequencyTypeEnum)e.frequency,
                        MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                    });
                foreach (var tmp in schedule.Occurrences(range))
                {
                    events.Add(new EventsOverviewModel()
                    {
                        title = e.title,
                        id = e.Id,
                        allDay = e.allDay,
                        //description = e.description,
                        start = tmp,
                        type = EventType.Recurring,
                        color = !String.IsNullOrEmpty(calendar.Color) ? calendar.Color : "",
                        calendar = e.calendarId
                    });
                }
            }
            return events;
        }
 /// <summary>
 /// Return all occurrences within the given date range.
 /// </summary>
 /// <param name="during">DateRange</param>
 /// <returns></returns>
 public IEnumerable<DateTime> Occurrences(DateRange during)
 {
     return EachDay(during.StartDateTime, during.EndDateTime).Where(IsOccurring);
 }
Beispiel #15
0
        /// <summary>
        /// Returns the date of last occurrence of the event.
        /// This method uses NumberOfOccurrences property to decide the last date.
        /// </summary>
        /// <returns>The date of last occurrence of the event.</returns>
        public DateTime? GetLastOccurrenceDate()
        {
            DateTime? firstDateTime = _event.FirstDateTime;
            if (!firstDateTime.HasValue)
            {
                return null;
            }
            DateTime startDateTime = firstDateTime.Value;
            FrequencyTypeEnum frequencyType = _event.FrequencyTypeOptions;
            if (frequencyType == FrequencyTypeEnum.None)
            {
                return firstDateTime;
            }

            if (!_event.NumberOfOccurrences.HasValue)
            {
                return firstDateTime;
            }

            int interval;
            int occurences = _event.NumberOfOccurrences.Value;
            DateRange dateRange = null;

            switch (frequencyType)
            {
                case FrequencyTypeEnum.Daily:
                    interval = _event.DayInterval + 1;
                    dateRange = new DateRange { StartDateTime = startDateTime, EndDateTime = startDateTime.AddDays(interval * occurences) };
                    break;
                case FrequencyTypeEnum.Weekly:
                case FrequencyTypeEnum.EveryWeekDay:
                case FrequencyTypeEnum.EveryMonWedFri:
                case FrequencyTypeEnum.EveryTuTh:
                    interval = (_event.WeeklyInterval + 1) * 7;
                    dateRange = new DateRange { StartDateTime = startDateTime, EndDateTime = startDateTime.AddDays(interval * occurences) };
                    break;
                case FrequencyTypeEnum.Monthly:
                    interval = _event.MonthInterval + 1;
                    dateRange = new DateRange { StartDateTime = startDateTime, EndDateTime = startDateTime.AddMonths(interval * occurences) };
                    break;
                case FrequencyTypeEnum.Quarterly:
                    //Assign a default value as there is no interval option available for this frequency type now.
                    interval = 12;
                    dateRange = new DateRange { StartDateTime = startDateTime, EndDateTime = startDateTime.AddMonths(interval * occurences) };
                    break;
                case FrequencyTypeEnum.Yearly:
                    interval = _event.YearInterval + 1;
                    dateRange = new DateRange { StartDateTime = startDateTime, EndDateTime = startDateTime.AddYears(interval * occurences) };
                    break;
            }

            IEnumerable<DateTime> items = Occurrences(dateRange);
            DateTime enddate = startDateTime;
            if (items != null)
            {
                enddate = items.ElementAtOrDefault(occurences-1);
            }
            return enddate;
        }
Beispiel #16
0
        public void MonthTest4()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 4",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                RepeatInterval = 3,
                DayOfMonth = 30,
                StartDateTime = new DateTime(2013, 2, 1)
            };

            var range = new DateRange()
            {
                StartDateTime = aEvent.StartDateTime.Value,
                EndDateTime = new DateTime(2014, 12, 31)
            };

            var occurringDate = new DateTime(2014, 2, 28);

            var schedule = new Schedule(aEvent);
            Assert.IsTrue(schedule.IsOccurring(occurringDate));

            var previousOccurrence = schedule.PreviousOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 11, 30), previousOccurrence.Value);

            var nextOccurrence = schedule.NextOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2014, 5, 30), nextOccurrence.Value);

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(8, occurrences.Count());
            Assert.AreEqual(new DateTime(2013, 2, 28), occurrences.First());
            Assert.AreEqual(new DateTime(2014, 11, 30), occurrences.Last());
        }
        private IEnumerable<object> GetAllOccurrencesForDateRange(ScheduleDTO scheduleDTO, DateRange range)
        {
            var calendarObjects = new List<object>();  
            foreach (var date in scheduleDTO.Schedule.Occurrences(range))
            {
                calendarObjects.Add(new
                {
                    id = scheduleDTO.ID,
                    title = scheduleDTO.Title,
                    start = ToUnixTimestamp(date + scheduleDTO.StartTime),
                    end = ToUnixTimestamp(date + scheduleDTO.EndTime),
                    url = Url.Action("ScheduleOccurrence", "Home", new { id = scheduleDTO.ID, occurrenceDate = date }),
                    allDay = false
                });
            }

            return calendarObjects;
        }
Beispiel #18
0
        public void DailyEventTest7()
        {
            // FirstDateTime should be optional for daily events
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 1",
                Frequency = 1,        // daily
                MonthlyInterval = 0,  // not applicable
                DaysOfWeek = 127      // every day of week
            };

            var schedule = new Schedule(aEvent);

            var during = new DateRange()
            {
                StartDateTime = DateTime.Now.AddDays(-30),
                EndDateTime = DateTime.Now.AddDays(30)
            };

            var occurrences = schedule.Occurrences(during);

            Assert.IsTrue(occurrences.Any());
        }
        public string GetCalendarEventsAsJson(int id,int start = 0, int end = 0)
        {
            DateTime startDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            startDate =  startDate.AddSeconds(start);
            DateTime endDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            endDate = endDate.AddSeconds(end);

            List<EventsOverviewModel> events = new List<EventsOverviewModel>();
            List<Schedule> schedules = new List<Schedule>();
            DateRange range = new DateRange();
            range.StartDateTime = startDate;
            range.EndDateTime = endDate;

            //Handle normal events
            var normal_events = this._db.Query<CalendarEntry>("SELECT * FROM ec_events WHERE calendarId = @0", id).ToList();
            foreach (var ne in normal_events)
            {
                events.Add(
                    new EventsOverviewModel()
                    {
                        type = EventType.Normal,
                        title = ne.title,
                        allDay = ne.allDay,
                        description = ne.description,
                        end = ne.end,
                        start = ne.start,
                        id = ne.Id
                    });
            }

            //Handle recurring events
            var recurring_events = this._db.Query<RecurringEvent>("SELECT * FROM ec_recevents WHERE calendarId = @0 ORDER BY id DESC", id).ToList();
            foreach(var e in recurring_events) {
                var schedule = new Schedule(
                    new Event()
                    {
                        Title = e.title,
                        ID = e.Id,
                        DaysOfWeekOptions = (DayOfWeekEnum)e.day,
                        FrequencyTypeOptions = (FrequencyTypeEnum)e.frequency,
                        MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                    });
                foreach (var tmp in schedule.Occurrences(range))
                {
                    events.Add(new EventsOverviewModel()
                    {
                        title = e.title,
                        id = e.Id,
                        allDay = e.allDay,
                        description = e.description,
                        start = tmp,
                        type = EventType.Recurring
                    });
                }
            }

            string json = JsonConvert.SerializeObject(events);
            return json;
        }
Beispiel #20
0
 /// <summary>
 /// Return all occurrences within the given date range.
 /// </summary>
 /// <param name="during">DateRange</param>
 /// <returns></returns>
 public IEnumerable <DateTime> Occurrences(DateRange during)
 {
     return(EachDay(during.StartDateTime, during.EndDateTime).Where(IsOccurring));
 }
Beispiel #21
0
        public void MonthTest3()
        {
            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 3",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                DayOfMonth = 3
            };

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2013, 1, 1),
                EndDateTime = new DateTime(2014, 12, 31)
            };

            var occurringDate = new DateTime(2013, 12, 3);

            var schedule = new Schedule(aEvent);
            Assert.IsTrue(schedule.IsOccurring(occurringDate));

            var previousOccurrence = schedule.PreviousOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 11, 3), previousOccurrence.Value);

            var nextOccurrence = schedule.NextOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2014, 1, 3), nextOccurrence.Value);

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(24, occurrences.Count());
            Assert.AreEqual(new DateTime(2013, 1, 3), occurrences.First());
            Assert.AreEqual(new DateTime(2014, 12, 3), occurrences.Last());
        }
        /// <summary>
        /// gets the public calendar of the league
        /// </summary>
        /// <param name="leagueId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static List<CalendarViewEventJson> GetPublicCalendarOfLeagueScheduleForView(Guid leagueId, DateTime startDate, DateTime endDate)
        {
            List<CalendarViewEventJson> events = new List<CalendarViewEventJson>();
            try
            {
                var dc = new ManagementContext();
                var calDb = (from xx in dc.CalendarLeagueOwners
                             where xx.League.LeagueId == leagueId
                             select new
                             {
                                 Events = xx.Calendar.CalendarEvents.Where(x => x.StartDate >= startDate && x.EndDate <= endDate && x.IsRemovedFromCalendar == false && x.IsPublicEvent),
                                 EventsReocurring = xx.Calendar.CalendarEventsReocurring.Where(x => (x.EndReocurring >= startDate || x.EndReocurring == null) && x.StartReocurring <= endDate && x.IsRemovedFromCalendar == false && x.IsPublic),
                             }).FirstOrDefault();

                string baseUrl = VirtualPathUtility.ToAbsolute("~/roller-derby-event/");
                if (calDb != null)
                {
                    //adds all the events from the database that were in the date range selected.
                    foreach (var ev in calDb.Events)
                    {
                        CalendarViewEventJson calEvent = new CalendarViewEventJson();
                        if (ev.Color != null)
                        {
                            var c = Color.FromArgb(ev.Color.ColorIdCSharp);
                            calEvent.backColor = ColorTranslator.ToHtml(c);
                        }
                        calEvent.title = ev.Name;
                        //removes length less than 14 chars 
                        //because the title is too long for the calendar display.
                        if (ev.Name.Length > 10)
                            calEvent.title = calEvent.title.Remove(10);
                        calEvent.id = ev.CalendarItemId;
                        if (ev.ReocurringEvent != null)
                            calEvent.ReocurringId = ev.ReocurringEvent.CalendarItemId;
                        calEvent.url = baseUrl + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(ev.Name) + "/" + ev.CalendarItemId.ToString().Replace("-", "");
                        if (!ev.IsInUTCTime)
                        {
                            calEvent.start = ev.StartDate.ToString("o");
                            calEvent.end = ev.EndDate.ToString("o");
                        }
                        else
                        {
                            calEvent.start = (ev.StartDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0)).ToString("o");
                            calEvent.end = (ev.EndDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0)).ToString("o");
                        }
                        events.Add(calEvent);
                    }
                    foreach (var ev in calDb.EventsReocurring)
                    {
                        if (ev.LastDateEventsWereCreated.GetValueOrDefault() < endDate)
                        {
                            Guid locationId = new Guid();
                            if (ev.Location != null)
                            {
                                locationId = ev.Location.LocationId;
                            }
                            var aEvent = new CalendarViewEventJson()
                            {
                                id = ev.CalendarItemId,
                                Title = ev.Name,
                                Frequency = ev.FrequencyReocurring,
                                DaysOfWeek = ev.DaysOfWeekReocurring,
                                MonthlyInterval = ev.MonthlyIntervalReocurring
                            };
                            var schedule = new Schedule(aEvent);

                            var range = new DateRange()
                            {
                                StartDateTime = ev.StartReocurring
                            };
                            //date is null if the event is never ending.
                            if (ev.EndReocurring.HasValue)
                                range.EndDateTime = ev.EndReocurring.Value;
                            else
                                range.EndDateTime = endDate.AddMonths(1);

                            //iterates through all the events that were automatically generated from the calendar control
                            //then creates a json view. and adds them to the list of events for the user.
                            foreach (var date in schedule.Occurrences(range))
                            {
                                CalendarViewEventJson calEvent = new CalendarViewEventJson();
                                if (ev.Color != null)
                                {
                                    var c = Color.FromArgb(ev.Color.ColorIdCSharp);
                                    calEvent.backColor = ColorTranslator.ToHtml(c);
                                }
                                calEvent.title = ev.Name;
                                if (ev.Name.Length > 10)
                                    calEvent.title.Remove(10);
                                calEvent.id = ev.CalendarItemId;
                                calEvent.url = baseUrl + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(ev.Name) + "/" + ev.CalendarItemId.ToString().Replace("-", "");

                                if (!ev.IsInUTCTime)
                                {
                                    calEvent.start = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second).ToString("o");
                                    calEvent.end = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second).ToString("o");
                                    calEvent.StartDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                                    calEvent.EndDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                                }
                                else
                                {
                                    calEvent.StartDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                                    calEvent.EndDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);

                                    calEvent.start = (calEvent.StartDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0)).ToString("o");
                                    calEvent.end = (calEvent.EndDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0)).ToString("o");
                                    calEvent.StartDate = (calEvent.StartDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                                    calEvent.EndDate = (calEvent.EndDate + new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return events;
        }
Beispiel #23
0
        public void MonthTest5()
        {
            var holidays = new UnionTE();
            holidays.Add(new FixedHolidayTE(1, 25));
            holidays.Add(new FloatingHolidayTE(3, DayOfWeekEnum.Mon, MonthlyIntervalEnum.First));

            var aEvent = new Event()
            {
                ID = 1,
                Title = "Event 5",
                FrequencyTypeOptions = FrequencyTypeEnum.Monthly,
                MonthlyIntervalOptions = MonthlyIntervalEnum.EveryWeek,
                DaysOfWeekOptions = DayOfWeekEnum.Mon | DayOfWeekEnum.Fri
            };

            var range = new DateRange()
            {
                StartDateTime = new DateTime(2013, 1, 15),
                EndDateTime = new DateTime(2013, 4, 30)
            };

            var occurringDate = new DateTime(2013, 1, 21);

            var schedule = new Schedule(aEvent, holidays);
            Assert.IsTrue(schedule.IsOccurring(occurringDate));
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2013, 3, 4)));

            var previousOccurrence = schedule.PreviousOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 1, 18), previousOccurrence.Value);

            var nextOccurrence = schedule.NextOccurrence(occurringDate, range);
            Assert.AreEqual(new DateTime(2013, 1, 28), nextOccurrence.Value);

            var occurrences = schedule.Occurrences(range);

            Assert.AreEqual(28, occurrences.Count());
            Assert.AreEqual(new DateTime(2013, 1, 18), occurrences.First());
            Assert.AreEqual(new DateTime(2013, 4, 29), occurrences.Last());
        }
Beispiel #24
0
        /// <summary>
        /// Returns true if a date falls within this event's limits, otherwise false.
        /// </summary>
        internal bool DateIsWithinLimits(DateTime aDate)
        {
            DateRange limits = GetEventLimitsAsDateRange();

            return(aDate >= limits.StartDateTime && aDate <= limits.EndDateTime);
        }
Beispiel #25
0
 /// <summary>
 /// Returns the start and end date for this event as a date range instance.
 /// If the event does not have a start date or end date, the date range values will be
 /// DateTime.MinValue and DateTime.MaxValue, respectively.
 /// The dates included in this range will never be null.
 /// </summary>
 public DateRange GetEventLimitsAsDateRange()
 {
     DateRange range = new DateRange();
     range.StartDateTime = (StartDateTime == null) ? DateTime.MinValue : (DateTime)StartDateTime;
     range.EndDateTime = (EndDateTime == null) ? DateTime.MaxValue : (DateTime)EndDateTime;
     return range;
 }
        public static Guid UpdateEventReOcurring(Guid calId, Guid reoccurringEventId, DateTime startDate, DateTime endDate, Guid locationId, string eventName, string link, string notes, bool AllowSelfCheckIn, FrequencyTypeEnum repeatFrequencySelected, bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, EndsWhenReoccuringEnum endsWhen, DateTime endsOnDateReoccuring, long selectedEventTypeId, int monthlyIntervalId, string hexColor, bool isEventPublic, List<long> groupIds, Guid memId)
        {
            bool editColorsOfAllEvents = false;
            bool editGroupsOfAllEvents = false;
            bool editAllEventDates = false;
            ManagementContext dc = new ManagementContext();
            var ev = dc.CalendarEventsReocurring.Where(x => x.CalendarItemId == reoccurringEventId && x.Calendar.CalendarId == calId).FirstOrDefault();
            if (ev != null)
            {
                ev.IsPublic = isEventPublic;
                ev.LastDateEventsWereCreated = startDate.AddDays(-1);
                try
                {
                    int daysOfWeek = 0;
                    if (sunday)
                        daysOfWeek += (int)DayOfWeekEnum.Sun;
                    if (monday)
                        daysOfWeek += (int)DayOfWeekEnum.Mon;
                    if (tuesday)
                        daysOfWeek += (int)DayOfWeekEnum.Tue;
                    if (wednesday)
                        daysOfWeek += (int)DayOfWeekEnum.Wed;
                    if (thursday)
                        daysOfWeek += (int)DayOfWeekEnum.Thu;
                    if (friday)
                        daysOfWeek += (int)DayOfWeekEnum.Fri;
                    if (saturday)
                        daysOfWeek += (int)DayOfWeekEnum.Sat;

                    ScheduleWidget.ScheduledEvents.Event aEvent = null;
                    if (repeatFrequencySelected == FrequencyTypeEnum.Monthly)
                    {
                        aEvent = new ScheduleWidget.ScheduledEvents.Event()
                        {
                            Title = eventName,
                            FrequencyTypeOptions = repeatFrequencySelected,
                            DaysOfWeek = daysOfWeek,
                            MonthlyInterval = monthlyIntervalId
                        };
                    }
                    else
                    {
                        aEvent = new ScheduleWidget.ScheduledEvents.Event()
                        {
                            Title = eventName,
                            FrequencyTypeOptions = repeatFrequencySelected,
                            DaysOfWeek = daysOfWeek
                        };
                    }


                    if (endsWhen == EndsWhenReoccuringEnum.Never)
                    {
                        ev.EndReocurring = DateTime.UtcNow.AddYears(1);
                    }
                    else if (endsWhen == EndsWhenReoccuringEnum.On)
                    {
                        if (endsOnDateReoccuring != new DateTime())
                            ev.EndReocurring = endsOnDateReoccuring;
                        else
                        {
                            //if this breaks, then the if statement above is wrong... Must change to match
                            //1/1/0001 12:00:00 AM
                            ErrorDatabaseManager.AddException(new Exception("NewDateTime" + new DateTime()), new Exception().GetType(), additionalInformation: startDate + " " + endDate + " " + endsOnDateReoccuring + " " + endsWhen.ToString());
                            ev.EndReocurring = null;
                        }
                    }
                    // we delete all the events if the reoccuring event is modified.
                    //so that we have a fresh date.
                    if (ev.DaysOfWeekReocurring != aEvent.DaysOfWeek)
                        editAllEventDates = true;
                    ev.DaysOfWeekReocurring = aEvent.DaysOfWeek;

                    if (ev.FrequencyReocurring != aEvent.Frequency)
                        editAllEventDates = true;
                    ev.FrequencyReocurring = aEvent.Frequency;

                    if (ev.MonthlyIntervalReocurring != aEvent.MonthlyInterval)
                        editAllEventDates = true;
                    ev.MonthlyIntervalReocurring = aEvent.MonthlyInterval;

                    if (ev.StartReocurring != startDate)
                        editAllEventDates = true;
                    ev.StartReocurring = startDate;
                    ev.Calendar = dc.Calendar.Where(x => x.CalendarId == calId).FirstOrDefault();

                    if (ev.EndDate != endDate)
                        editAllEventDates = true;


                    DateTimeOffset dtOffEnd = new DateTimeOffset(endDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                    DateTimeOffset dtOffStart = new DateTimeOffset(startDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));

                    ev.StartDate = dtOffStart.UtcDateTime;
                    ev.EndDate = dtOffEnd.UtcDateTime;
                    ev.IsInUTCTime = true;

                    if (!String.IsNullOrEmpty(hexColor))
                    {
                        Color cc = ColorTranslator.FromHtml(hexColor);
                        int arb = cc.ToArgb();

                        var color = dc.Colors.Where(x => x.ColorIdCSharp == arb).FirstOrDefault();
                        if (ev.Color != color)
                            editColorsOfAllEvents = true;
                        ev.Color = color;
                    }
                    else
                    {
                        if (ev.Color != null)
                            editColorsOfAllEvents = true;
                        ev.Color = null;
                    }
                    if (ev.AllowSelfCheckIn != AllowSelfCheckIn)
                        editAllEventDates = true;
                    ev.AllowSelfCheckIn = AllowSelfCheckIn;
                    ev.Location = dc.Locations.Include("Contact").Include("Contact.Addresses").Include("Contact.Communications").Where(x => x.LocationId == locationId).FirstOrDefault();
                    ev.Name = eventName;
                    ev.Notes = notes;
                    ev.Link = link;

                    //removes any groups not in list.
                    var tempGroups = ev.Groups.ToList();
                    foreach (var group in tempGroups)
                    {
                        if (!groupIds.Contains(group.Group.Id))
                        {
                            ev.Groups.Remove(group);
                            editGroupsOfAllEvents = true;
                        }
                    }

                    //adds any groups not in list.
                    foreach (var id in groupIds)
                    {
                        var group = dc.LeagueGroups.Where(x => x.Id == id).FirstOrDefault();
                        if (group != null)
                        {
                            if (ev.Groups.Where(x => x.Group.Id == id).FirstOrDefault() == null)
                            {
                                RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup newGroup = new RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup();
                                newGroup.Group = group;
                                newGroup.Event = ev;
                                ev.Groups.Add(newGroup);
                                editGroupsOfAllEvents = true;
                            }
                        }
                    }

                    ev.EventType = dc.CalendarEventTypes.Where(x => x.CalendarEventTypeId == selectedEventTypeId).FirstOrDefault();





                    if (editColorsOfAllEvents)
                    {
                        foreach (var eventReoccure in ev.ReoccuringEvents.Where(x => x.IsRemovedFromCalendar == false))
                        {
                            eventReoccure.Color = ev.Color;
                        }
                    }
                    if (editGroupsOfAllEvents)
                    {
                        foreach (var eventReoccure in ev.ReoccuringEvents.Where(x => x.IsRemovedFromCalendar == false))
                        {
                            UpdateGroupsOfEvent(groupIds, dc, eventReoccure);
                        }
                    }

                    int c = dc.SaveChanges();

                    if (editAllEventDates)
                    {
                        var eventsReoccur = ev.ReoccuringEvents.Where(x => x.Attendees.Count == 0 && x.IsRemovedFromCalendar == false).ToList();
                        foreach (var eve in eventsReoccur)
                        {
                            eve.IsRemovedFromCalendar = true;
                        }

                        var schedule = new Schedule(aEvent);
                        var range = new DateRange()
                        {
                            StartDateTime = ev.StartReocurring
                        };
                        //date is null if the event is never ending.
                        if (ev.EndReocurring.HasValue)
                            range.EndDateTime = ev.EndReocurring.Value;
                        else
                            range.EndDateTime = endDate.AddMonths(1);

                        foreach (var date in schedule.Occurrences(range))
                        {

                            DateTime endDateEv = new DateTime();
                            DateTime startDateEv = new DateTime();

                            if (!ev.IsInUTCTime)
                            {
                                startDateEv = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                                endDateEv = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                            }
                            else
                            {
                                //we have to create a temp dates so we can add the timezone information without going back a day
                                //if the time being used is on the border.
                                //without the tempdates 1/4/2013 7pm turned into 1/3/2013 7pm because the timezones didn't account for the 
                                //fact the dates were already in utc.
                                var startTempDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                var endTempDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                startDateEv = new DateTime(date.Year, date.Month, date.Day, startTempDate.Hour, startTempDate.Minute, startTempDate.Second);
                                endDateEv = new DateTime(date.Year, date.Month, date.Day, endTempDate.Hour, endTempDate.Minute, endTempDate.Second);
                            }

                            //only add more dates to dates in the future.  No need to go back in time.
                            if (startDateEv > DateTime.UtcNow)
                                CalendarEventFactory.CreateNewEvent(ev.Calendar.CalendarId, startDateEv, endDateEv, locationId, ev.Name, ev.Link, ev.Notes, ev.AllowSelfCheckIn, ev.IsPublic, true, ev.CalendarItemId, ev.EventType.CalendarEventTypeId, false, ev.TicketUrl, hexColor, new List<long>(), memId);

                        }
                    }
                    c = dc.SaveChanges();

                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: startDate + " " + endDate + " " + endsOnDateReoccuring + " " + endsWhen.ToString());
                }
            }
            return reoccurringEventId;
        }
Beispiel #27
0
        /// <summary>
        /// RoughlyEstimateMinimumEventOccurrences,
        /// This will return a very rough, and conservative, guess of the minimum number of occurrences
        /// that should be generated by a particular event.
        /// </summary>
        static public int RoughlyEstimateMinimumEventOccurrences(Event eventInstance)
        {
            if (eventInstance.HasBrokenZeroOccurrenceConfiguration())
            {
                return(0);
            }
            int       repeatInterval = eventInstance.RepeatInterval;
            DateRange eventLimits    = eventInstance.GetEventLimitsAsDateRange();
            TimeSpan  timeSpan       = eventLimits.EndDateTime - eventLimits.StartDateTime;
            int       spanDays       = timeSpan.Days;
            int       spanWeeks      = timeSpan.Days / 7;
            int       result         = 0;

            switch (eventInstance.FrequencyTypeOptions)
            {
            case FrequencyTypeEnum.None:
                result = 1;
                break;

            case FrequencyTypeEnum.Daily:
                result = (spanDays / repeatInterval) - 1;
                break;

            case FrequencyTypeEnum.Weekly:
                int includedDays = 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Mon) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Tue) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Wed) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Thu) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Fri) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Sat) ? 1 : 0;
                includedDays += eventInstance.DaysOfWeekOptions.HasFlag(DayOfWeekEnum.Sun) ? 1 : 0;
                result        = ((spanWeeks / repeatInterval) * includedDays) - 1;
                break;

            case FrequencyTypeEnum.EveryWeekDay:
                result = ((spanWeeks / repeatInterval) * 5) - 1;
                break;

            case FrequencyTypeEnum.EveryMonWedFri:
                result = ((spanWeeks / repeatInterval) * 3) - 1;
                break;

            case FrequencyTypeEnum.EveryTuTh:
                result = ((spanWeeks / repeatInterval) * 2) - 1;
                break;

            case FrequencyTypeEnum.Monthly:
                int spanMonths = spanDays / 31;
                result = (spanMonths / repeatInterval) - 1;
                break;

            case FrequencyTypeEnum.Quarterly:
                int spanQuarters = spanDays / 92;
                result = (spanQuarters / repeatInterval) - 1;
                break;

            case FrequencyTypeEnum.Yearly:
                int spanYears = spanDays / 365;
                result = (spanYears / repeatInterval) - 1;
                break;
            }
            return((result > 0) ? result : 0);
        }
        private List<EventsOverviewModel> GetRecurringEvents(int id, string culture, DateTime start, DateTime end)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;

            //Handle recurring events
            List<EventsOverviewModel> events = new List<EventsOverviewModel>();

            DateTime startDate = start;
            DateTime endDate = end;

            DateRange range = new DateRange();
            range.StartDateTime = startDate;
            range.EndDateTime = endDate;

            var calendar = db.SingleOrDefault<ECalendar>(id);
            var recurring_events = db.Query<RecurringEvent>("SELECT * FROM ec_recevents WHERE calendarId = @0 ORDER BY id DESC", id).ToList();
            foreach (var e in recurring_events)
            {
                var schedule = new Schedule(
                    new ScheduleWidget.ScheduledEvents.Event()
                    {
                        Title = e.title,
                        ID = e.Id,
                        DaysOfWeekOptions = (DayOfWeekEnum)e.day,
                        FrequencyTypeOptions = (FrequencyTypeEnum)e.frequency,
                        MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                    });
                foreach (var tmp in schedule.Occurrences(range))
                {
                    List<EventDescription> descriptions = db.Query<EventDescription>("SELECT * FROM ec_eventdescriptions WHERE eventid = @0 AND calendarid = @1 AND type = @2", e.Id, e.calendarId, (int)EventType.Recurring).ToList();
                    EventDescription currentDescription = descriptions.SingleOrDefault(x => x.CultureCode.ToLower() == culture);
                    string description = String.Empty;
                    System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");

                    if (null != currentDescription && null != currentDescription.Content)
                    {
                        description = rx.Replace(currentDescription.Content, "");
                        description = description.Substring(0, (description.Length > 150) ? 150 : description.Length) + "...";
                    }

                    events.Add(new EventsOverviewModel()
                    {
                        title = e.title,
                        id = e.Id,
                        allDay = e.allDay,
                        description = description,
                        start = tmp,
                        type = EventType.Recurring,
                        color = !String.IsNullOrEmpty(calendar.Color) ? calendar.Color : "",
                        textColor = !String.IsNullOrEmpty(calendar.TextColor) ? calendar.TextColor : "",
                        categories = e.categories,
                        calendar = e.calendarId
                    });
                }
            }
            return events;
        }
Beispiel #29
0
 /// <summary>
 /// DoDateRangesOverlap,
 /// This returns true if there is some overlap between two ranges, otherwise false.
 /// 
 /// Implementation notes:
 /// To help clarify why this function is implemented in the way that it is, here is a 
 /// listing of all positional possibilities for the start and the end of two date ranges:
 /// No overlap (some of the beginnings are after some of the ends)
 /// f1 f2 s1 s2
 /// s1 s2 f1 f2 
 /// Some overlap (all the beginnings are before all the ends)
 /// f1 s1 f2 s2
 /// f1 s1 s2 f2 
 /// s1 f1 f2 s2
 /// s1 f1 s2 f2 
 /// </summary>
 public static bool DoDateRangesOverlap(DateRange first, DateRange second)
 {
     if (first.EndDateTime < second.StartDateTime) { return false; }
     if (second.EndDateTime < first.StartDateTime) { return false; }
     return true;
 }
        public static Guid CreateNewEventReOcurring(Guid calId, DateTime startDate, DateTime endDate, Guid locationId, string eventName, string link, string notes, bool AllowSelfCheckIn, FrequencyTypeEnum repeatFrequencySelected, bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, EndsWhenReoccuringEnum endsWhen, int endsOnOcurrences, DateTime endsOnDateReoccuring, long selectedEventTypeId, bool broadcastEvent, bool isEventPublic, int monthlyIntervalId, string ticketUrl, string hexColor, List<long> groupIds, Guid memberId)
        {
            DataModels.Calendar.CalendarEventReoccuring ev = new DataModels.Calendar.CalendarEventReoccuring();

            try
            {

                //need to know how many days so we can know when to end the reoccuring event in the calendar
                int howManyDays = 0;
                int daysOfWeek = 0;
                if (sunday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Sun;
                }
                if (monday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Mon;
                }
                if (tuesday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Tue;
                }
                if (wednesday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Wed;
                }
                if (thursday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Thu;
                }
                if (friday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Fri;
                }
                if (saturday)
                {
                    howManyDays += 1;
                    daysOfWeek += (int)DayOfWeekEnum.Sat;
                }
                ScheduleWidget.ScheduledEvents.Event aEvent = null;
                if (repeatFrequencySelected == FrequencyTypeEnum.Monthly)
                {
                    aEvent = new ScheduleWidget.ScheduledEvents.Event()
                   {
                       Title = eventName,
                       FrequencyTypeOptions = repeatFrequencySelected,
                       DaysOfWeek = daysOfWeek,
                       MonthlyInterval = monthlyIntervalId
                   };
                }
                else
                {
                    aEvent = new ScheduleWidget.ScheduledEvents.Event()
                   {
                       Title = eventName,
                       FrequencyTypeOptions = repeatFrequencySelected,
                       DaysOfWeek = daysOfWeek
                   };
                }

                var dc = new ManagementContext();
                if (endsWhen == EndsWhenReoccuringEnum.Never)
                {
                    ev.EndReocurring = DateTime.UtcNow.AddYears(2);
                }
                else if (endsWhen == EndsWhenReoccuringEnum.After)
                {
                    if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Daily)
                        ev.EndReocurring = startDate.AddDays(endsOnOcurrences);
                    else if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Monthly)
                        ev.EndReocurring = startDate.AddMonths(endsOnOcurrences);
                    else if (aEvent.FrequencyTypeOptions == FrequencyTypeEnum.Weekly)
                    {
                        int daysToAdd = (endsOnOcurrences / howManyDays) * 7;
                        ev.EndReocurring = startDate.AddDays(daysToAdd);
                    }
                }
                else if (endsWhen == EndsWhenReoccuringEnum.On)
                {
                    ev.EndReocurring = endsOnDateReoccuring;
                }
                if (!String.IsNullOrEmpty(hexColor))
                {
                    Color c = ColorTranslator.FromHtml(hexColor);
                    int arb = c.ToArgb();
                    ev.Color = dc.Colors.Where(x => x.ColorIdCSharp == arb).FirstOrDefault();
                }
                else
                    ev.Color = null;

                ev.DaysOfWeekReocurring = aEvent.DaysOfWeek;
                ev.FrequencyReocurring = aEvent.Frequency;
                ev.MonthlyIntervalReocurring = aEvent.MonthlyInterval;
                ev.StartReocurring = startDate;
                ev.Calendar = dc.Calendar.Where(x => x.CalendarId == calId).FirstOrDefault();
                if (ev.Calendar.IsCalendarInUTC)
                {
                    DateTimeOffset dtOffEnd = new DateTimeOffset(endDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));
                    DateTimeOffset dtOffStart = new DateTimeOffset(startDate.Ticks, new TimeSpan(ev.Calendar.TimeZone, 0, 0));

                    ev.EndDate = dtOffEnd.UtcDateTime;
                    ev.StartDate = dtOffStart.UtcDateTime;
                    ev.IsInUTCTime = true;
                }
                else
                {
                    ev.EndDate = endDate;
                    ev.StartDate = startDate;
                }
                //keep under isrecocuring question.
                foreach (var id in groupIds)
                {
                    var group = dc.LeagueGroups.Where(x => x.Id == id).FirstOrDefault();
                    if (group != null)
                    {
                        RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup newGroup = new RDN.Library.DataModels.Calendar.CalendarEventReoccuringGroup();
                        newGroup.Group = group;
                        newGroup.Event = ev;
                        if (ev.Groups.Where(x => x.Group.Id == id).FirstOrDefault() == null)
                            ev.Groups.Add(newGroup);
                    }
                }

                ev.AllowSelfCheckIn = AllowSelfCheckIn;
                ev.Location = dc.Locations.Include("Contact").Include("Contact.Addresses").Include("Contact.Communications").Where(x => x.LocationId == locationId).FirstOrDefault();
                ev.Name = eventName;
                ev.Notes = notes;
                ev.TicketUrl = ticketUrl;
                ev.Link = link;
                ev.IsPublic = isEventPublic;
                ev.LastDateEventsWereCreated = DateTime.UtcNow.AddMonths(-3);
                ev.EventType = dc.CalendarEventTypes.Where(x => x.CalendarEventTypeId == selectedEventTypeId).FirstOrDefault();
                dc.CalendarEventsReocurring.Add(ev);
                ev.Calendar.CalendarEventsReocurring.Add(ev);
                int cc = dc.SaveChanges();

                var schedule = new Schedule(aEvent);
                var range = new DateRange()
                {
                    StartDateTime = ev.StartReocurring
                };
                //date is null if the event is never ending.
                if (ev.EndReocurring.HasValue)
                    range.EndDateTime = ev.EndReocurring.Value;
                else
                    range.EndDateTime = endDate.AddMonths(1);

                foreach (var date in schedule.Occurrences(range))
                {


                    DateTime endDateEv = new DateTime();
                    DateTime startDateEv = new DateTime();

                    if (!ev.IsInUTCTime)
                    {
                        startDateEv = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                        endDateEv = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                    }
                    else
                    {
                        //we have to create a temp dates so we can add the timezone information without going back a day
                        //if the time being used is on the border.
                        //without the tempdates 1/4/2013 7pm turned into 1/3/2013 7pm because the timezones didn't account for the 
                        //fact the dates were already in utc.
                        var startTempDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                        var endTempDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                        startDateEv = new DateTime(date.Year, date.Month, date.Day, startTempDate.Hour, startTempDate.Minute, startTempDate.Second);
                        endDateEv = new DateTime(date.Year, date.Month, date.Day, endTempDate.Hour, endTempDate.Minute, endTempDate.Second);
                    }


                    Guid calItemId = CalendarEventFactory.CreateNewEvent(ev.Calendar.CalendarId, startDateEv, endDateEv, locationId, ev.Name, ev.Link, ev.Notes, ev.AllowSelfCheckIn, ev.IsPublic, true, ev.CalendarItemId, ev.EventType.CalendarEventTypeId, false, ev.TicketUrl, hexColor, new List<long>(), memberId);

                }

                if (broadcastEvent)
                {
                    List<Guid> memIds = new List<Guid>();
                    var memberCreated = MemberCache.GetMemberDisplay(memberId);
                    if (ev.Groups.Count == 0)
                    {
                        //sends broadcast to all league members
                        var members = MemberCache.GetCurrentLeagueMembers(memberId);
                        foreach (var mem in members)
                        {
                            SendEmailAboutNewEvent(calId, null, ev, memberCreated.DerbyName, mem.UserId, mem.DerbyName, startDate, endDate);
                            memIds.Add(mem.MemberId);
                        }
                    }
                    else
                    {
                        //gets all the members of the groups selected and sends an email broadcast to those members.
                        List<MemberDisplay> memsToSend = new List<MemberDisplay>();
                        var groups = MemberCache.GetLeagueGroupsOfMember(memberId);
                        foreach (var group in ev.Groups)
                        {
                            var g = groups.Where(x => x.Id == group.Group.Id).FirstOrDefault();
                            if (g != null)
                            {
                                foreach (var temp in g.GroupMembers)
                                {
                                    MemberDisplay mtemp = new MemberDisplay();
                                    mtemp.DerbyName = temp.DerbyName;
                                    mtemp.UserId = temp.UserId;
                                    if (memsToSend.Where(x => x.UserId == mtemp.UserId).FirstOrDefault() == null)
                                        memsToSend.Add(mtemp);
                                }
                            }
                        }
                        var members = MemberCache.GetCurrentLeagueMembers(memberId);
                        foreach (var mem in memsToSend)
                        {
                            SendEmailAboutNewEvent(calId, null, ev, memberCreated.DerbyName, mem.UserId, mem.DerbyName, startDate, endDate);
                            memIds.Add(mem.MemberId);
                        }
                    }
                    var fact = new MobileNotificationFactory()
                       .Initialize("New Event Created:", ev.Name, Mobile.Enums.NotificationTypeEnum.NewCalendarEventBroadcast)
                       .AddCalendarEvent(ev.CalendarItemId, calId, ev.Name)
                       .AddMembers(memIds)
                       .SendNotifications();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return ev.CalendarItemId;
        }
        public void MultifunctionTest1()
        {
            var aEvent = new Event()
            {
                FrequencyTypeOptions = FrequencyTypeEnum.Yearly,
                RepeatInterval = 2,
                StartDateTime = new DateTime(2000, 9, 27), // even years only
                Anniversary = new Anniversary()
                {
                    Month = 9,
                    Day = 27
                }
            };
            // Occurs 2000,2002,2004,2006,2008,2010
            aEvent.SetEndDateWithNumberOfOccurrences(6);

            // Check that the ending date was set correctly.
            Assert.IsTrue(aEvent.EndDateTime == new DateTime(2010, 9, 27));

            // Check that the number of occurrences is retrievable.
            Assert.IsTrue(aEvent.NumberOfOccurrencesThatWasLastSet == 6);

            // Exclude 2000,2006,2010.
            var excludedDates = new List<DateTime>
            {
                new DateTime(2000, 9, 27),
                new DateTime(2005, 9, 27),
                new DateTime(2005, 9, 28),
                new DateTime(2006, 9, 27),
                new DateTime(2010, 9, 27)
            };
            var schedule = new Schedule(aEvent, excludedDates);

            // Make sure it is not occurring on excluded dates.
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2000, 9, 27)));
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2006, 9, 27)));
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2010, 9, 27)));

            // Make sure it is not occurring outside the set range.
            Assert.IsFalse(schedule.IsOccurring(new DateTime(1998, 9, 27)));
            Assert.IsFalse(schedule.IsOccurring(new DateTime(2012, 9, 27)));

            // Make sure it is occurring on desired dates.
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2002, 9, 27)));
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2004, 9, 27)));
            Assert.IsTrue(schedule.IsOccurring(new DateTime(2008, 9, 27)));

            // Check the occurrences function.
            var during = new DateRange(new DateTime(1995, 1, 1),new DateTime(2015, 1, 1));
            var occurrences = schedule.Occurrences(during);
            Assert.IsTrue(occurrences.Count() == 3);

            // Check the last occurrence date function.
            var lastDate = schedule.GetLastOccurrenceDate();
            Assert.IsTrue(lastDate == new DateTime(2008, 9, 27));

            // Check the next occurrence (date only) function.
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(1995, 1, 1)) == new DateTime(2002, 9, 27));
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(2004, 9, 26)) == new DateTime(2004, 9, 27));
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(2004, 9, 27)) == new DateTime(2008, 9, 27));
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(2008, 9, 27)) == null);

            // Check the previous occurrence (date only) function.
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(1995, 1, 1)) == null);
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(2004, 9, 26)) == new DateTime(2002, 9, 27));
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(2004, 9, 28)) == new DateTime(2004, 9, 27));
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(2013, 9, 27)) == new DateTime(2008, 9, 27));

            // Check the next occurrence ranged function.
            var range1 = new DateRange(new DateTime(2004, 9, 1), new DateTime(2004, 10, 1));
            var range2 = new DateRange(new DateTime(2004, 11, 1), new DateTime(2002, 9, 27));
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(1995, 1, 1), range1) == new DateTime(2004, 9, 27));
            Assert.IsTrue(schedule.NextOccurrence(new DateTime(1995, 1, 1), range2) == null);

            // Check the previous occurrence ranged function.
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(2015, 1, 1), range1) == new DateTime(2004, 9, 27));
            Assert.IsTrue(schedule.PreviousOccurrence(new DateTime(2015, 1, 1), range2) == null);
        }
        /// <summary>
        /// any changes made here need to be mirrored in getcalendarscheduleForView
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ownerEntity"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static RDN.Portable.Classes.Controls.Calendar.Calendar GetCalendarSchedule(Guid id, CalendarOwnerEntityEnum ownerEntity, DateTime startDate, DateTime endDate, Guid memberId, bool isAttendanceManagerOrBetter)
        {
            RDN.Portable.Classes.Controls.Calendar.Calendar newCal = new RDN.Portable.Classes.Controls.Calendar.Calendar();
            try
            {
                var dc = new ManagementContext();
                var calDb = (from xx in dc.Calendar.Include("CalendarEventsReocurring").Include("CalendarEvents").Include("CalendarEvents.ReocurringEvent").Include("CalendarEvents.PointsForEvent")
                             where xx.CalendarId == id
                             select new
                             {
                                 xx.IsCalendarInUTC,
                                 xx.TimeZone,
                                 Events = xx.CalendarEvents.Where(x => x.StartDate >= startDate && x.EndDate <= endDate && x.IsRemovedFromCalendar == false),
                                 FedOwners = xx.FederationOwners,
                                 LeagueOwners = xx.LeagueOwners,
                                 AllowSelfCheckIn = xx.AllowSelfCheckIn,
                                 xx.DisableBirthdaysFromShowing,
                                 xx.DisableStartSkatingDays,
                                 EventsReocurring = xx.CalendarEventsReocurring.Where(x => (x.EndReocurring >= startDate || x.EndReocurring == null) && x.StartReocurring <= endDate && x.IsRemovedFromCalendar == false),
                             }).FirstOrDefault();
                newCal.IsCalendarInUTC = calDb.IsCalendarInUTC;
                newCal.TimeZone = calDb.TimeZone;
                newCal.CalendarId = id;
                newCal.OwnerEntity = ownerEntity;
                newCal.AllowSelfCheckIn = calDb.AllowSelfCheckIn;
                newCal.DisableBirthdays = calDb.DisableBirthdaysFromShowing;
                newCal.DisableSkatingStartDates = calDb.DisableStartSkatingDays;
                if (ownerEntity == CalendarOwnerEntityEnum.federation)
                {
                    foreach (var own in calDb.FedOwners)
                    {
                        CalendarOwner owner = new CalendarOwner();
                        owner.OwnerId = own.Federation.FederationId;
                        owner.OwnerName = own.Federation.Name;
                        newCal.EntityName = own.Federation.Name;

                        newCal.Owners.Add(owner);
                    }
                }
                else if (ownerEntity == CalendarOwnerEntityEnum.league)
                {
                    foreach (var own in calDb.LeagueOwners)
                    {
                        CalendarOwner owner = new CalendarOwner();
                        owner.OwnerId = own.League.LeagueId;
                        owner.OwnerName = own.League.Name;
                        newCal.EntityName = own.League.Name;
                        newCal.Owners.Add(owner);
                    }
                }

                foreach (var ev in calDb.Events)
                {
                    newCal.Events.Add(CalendarEventFactory.DisplayEvent(ev, memberId, isAttendanceManagerOrBetter));
                }
                foreach (var ev in calDb.EventsReocurring)
                {
                    //used so we can refresh the last day events were created..

                    // ev.LastDateEventsWereCreated = endDate.AddMonths(-1);
                    if (ev.LastDateEventsWereCreated.GetValueOrDefault() < endDate)
                    {
                        var eventRe = dc.CalendarEventsReocurring.Where(x => x.CalendarItemId == ev.CalendarItemId && x.IsRemovedFromCalendar == false).FirstOrDefault();
                        eventRe.LastDateEventsWereCreated = endDate;
                        eventRe.Calendar = eventRe.Calendar;
                        dc.SaveChanges();

                        var aEvent = new CalendarViewEventJson()
                        {
                            id = ev.CalendarItemId,
                            Title = ev.Name,
                            Frequency = ev.FrequencyReocurring,
                            DaysOfWeek = ev.DaysOfWeekReocurring,
                            MonthlyInterval = ev.MonthlyIntervalReocurring
                        };
                        var schedule = new Schedule(aEvent);

                        var range = new DateRange()
                        {
                            StartDateTime = ev.StartReocurring
                        };
                        //date is null if the event is never ending.
                        if (ev.EndReocurring.HasValue)
                            range.EndDateTime = ev.EndReocurring.Value;
                        else
                            range.EndDateTime = endDate.AddMonths(1);

                        foreach (var date in schedule.Occurrences(range))
                        {
                            CalendarEvent calEvent = new CalendarEvent();
                            Guid locationId = new Guid();
                            if (ev.Location != null)
                            {
                                calEvent.Location.LocationName = ev.Location.LocationName;
                                locationId = ev.Location.LocationId;
                            }
                            calEvent.Name = ev.Name;
                            calEvent.CalendarItemId = ev.CalendarItemId;
                            if (eventRe.Color != null)
                            {
                                var c = Color.FromArgb(eventRe.Color.ColorIdCSharp);
                                calEvent.ColorTempSelected = ColorTranslator.ToHtml(c);
                            }

                            if (!ev.IsInUTCTime)
                            {
                                calEvent.StartDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second);
                                calEvent.EndDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second);
                            }
                            else
                            {
                                //we have to create a temp dates so we can add the timezone information without going back a day
                                //if the time being used is on the border.
                                //without the tempdates 1/4/2013 7pm turned into 1/3/2013 7pm because the timezones didn't account for the 
                                //fact the dates were already in utc.
                                var startTempDate = new DateTime(date.Year, date.Month, date.Day, ev.StartDate.Hour, ev.StartDate.Minute, ev.StartDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                var endTempDate = new DateTime(date.Year, date.Month, date.Day, ev.EndDate.Hour, ev.EndDate.Minute, ev.EndDate.Second) + new TimeSpan(ev.Calendar.TimeZone, 0, 0);
                                calEvent.StartDate = new DateTime(date.Year, date.Month, date.Day, startTempDate.Hour, startTempDate.Minute, startTempDate.Second);
                                calEvent.EndDate = new DateTime(date.Year, date.Month, date.Day, endTempDate.Hour, endTempDate.Minute, endTempDate.Second);
                            }

                            calEvent.Notes = ev.Notes;
                            calEvent.AllowSelfCheckIn = ev.AllowSelfCheckIn;

                            //var evs = (from xx in newCal.Events
                            //           where xx.CalendarReoccurringId == ev.CalendarItemId
                            //           where xx.StartDate == calEvent.StartDate
                            //           where xx.EndDate == calEvent.EndDate
                            //           select xx).FirstOrDefault();
                            ////dirty bit to check if event was already in list.  If it is, we don't add it.
                            ////the date check here is to only create events within the calendar selected dates
                            //if (evs == null && calEvent.StartDate >= startDate && calEvent.EndDate <= endDate)
                            //{
                            //    string colorHex = String.Empty;
                            //    if (ev.Color != null)
                            //    {
                            //        var c = Color.FromArgb(ev.Color.ColorIdCSharp);
                            //        colorHex = ColorTranslator.ToHtml(c);
                            //    }
                            //    Guid calItemId = CalendarEventFactory.CreateNewEvent(ev.Calendar.CalendarId, calEvent.StartDate, calEvent.EndDate, locationId, ev.Name, ev.Link, ev.Notes, ev.AllowSelfCheckIn, ev.IsPublic, true, calEvent.CalendarItemId, ev.EventType.CalendarEventTypeId, false, ev.TicketUrl, colorHex, new List<long>(), memberId);
                            //    calEvent.CalendarItemId = calItemId;
                            //    newCal.Events.Add(calEvent);
                            //}
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return newCal;
        }