Example #1
0
        static private void PopulateiCalTimeZoneInfo(ITimeZoneInfo tzi, System.TimeZoneInfo.TransitionTime transition, int year)
        {
            Calendar c = CultureInfo.CurrentCulture.Calendar;

            RecurrencePattern recurrence = new RecurrencePattern();            
            recurrence.Frequency = FrequencyType.Yearly;
            recurrence.ByMonth.Add(transition.Month);
            recurrence.ByHour.Add(transition.TimeOfDay.Hour);
            recurrence.ByMinute.Add(transition.TimeOfDay.Minute);

            if (transition.IsFixedDateRule)
            {
                recurrence.ByMonthDay.Add(transition.Day);
            }
            else
            {
                recurrence.ByDay.Add(new WeekDay(transition.DayOfWeek));
                int daysInMonth = c.GetDaysInMonth(year, transition.Month);
                int offset = (transition.Week * 7) - 7;
                if (offset + 7 > daysInMonth)
                    offset = daysInMonth - 7;

                // Add the possible days of the month this could occur.
                for (int i = 1; i <= 7; i++)
                    recurrence.ByMonthDay.Add(i + offset + (int)transition.DayOfWeek);
            }

            tzi.RecurrenceRules.Add(recurrence);
        }
Example #2
0
		public static bool IsOccurrenceInRange(string valueToParse, DateTime start, DateTime end)
		{
			RecurrencePattern pattern = new RecurrencePattern();
			if (RecurrencePatternHelper.TryParseRecurrencePattern(valueToParse, out pattern))
			{
				return pattern.GetOccurrences(start, start, end).Count() > 0;
			}

			return false;
		}
        private IRecurrencePattern ProcessRecurrencePattern(IDateTime referenceDate)
        {
            RecurrencePattern r = new RecurrencePattern();
            r.CopyFrom(Pattern);

            // Convert the UNTIL value to one that matches the same time information as the reference date
            if (r.Until != DateTime.MinValue)
                r.Until = DateUtil.MatchTimeZone(referenceDate, new iCalDateTime(r.Until)).Value;

            if (r.Frequency > FrequencyType.Secondly &&
                r.BySecond.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.BySecond.Add(referenceDate.Second);
            if (r.Frequency > FrequencyType.Minutely &&
                r.ByMinute.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByMinute.Add(referenceDate.Minute);
            if (r.Frequency > FrequencyType.Hourly &&
                r.ByHour.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByHour.Add(referenceDate.Hour);

            // If BYDAY, BYYEARDAY, or BYWEEKNO is specified, then
            // we don't default BYDAY, BYMONTH or BYMONTHDAY
            if (r.ByDay.Count == 0 &&
                r.ByYearDay.Count == 0 &&
                r.ByWeekNo.Count == 0)
            {
                // If the frequency is weekly, and
                // no day of week is specified, use
                // the original date's day of week.
                // NOTE: fixes WeeklyCount1() and WeeklyUntil1() handling
                if (r.Frequency == FrequencyType.Weekly)
                    r.ByDay.Add(new WeekDay(referenceDate.DayOfWeek));

                // If BYMONTHDAY is not specified,
                // default to the current day of month
                // NOTE: fixes YearlyByMonth1() handling, added BYYEARDAY exclusion
                // to fix YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Weekly &&
                    r.ByMonthDay.Count == 0)
                    r.ByMonthDay.Add(referenceDate.Day);

                // If BYMONTH is not specified, default to
                // the current month.
                // NOTE: fixes YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Monthly &&
                    r.ByMonth.Count == 0)
                    r.ByMonth.Add(referenceDate.Month);
            }

            return r;
        }
 public ActionResult Create(GroupInstance groupinstance)
 {
     if (ModelState.IsValid)
     {
         //default recurrence once a week forever
         RecurrencePattern rp = new RecurrencePattern(FrequencyType.Weekly);
         groupinstance.RecurrenceRule = "RRULE:" + rp.ToString();
         db.GroupInstances.Add(groupinstance);
         db.SaveChanges();
         return Content(Boolean.TrueString);
     }
     //TODO: review error handling. This will fail since it is not filtering dropdowns for overlapping events!!!
     ViewBag.GroupId = new SelectList(db.Groups, "GroupId", "Name", groupinstance.GroupId);
     ViewBag.ClassroomId = new SelectList(db.Classrooms, "ClassroomID", "Name", groupinstance.ClassroomId);
     return Content("Please review your form");
 }
Example #5
0
 /// <summary>
 /// Creates a Recurrence object
 /// </summary>
 /// <param name="pattern">The Outlook RecurrencePattern to use</param>
 public Recurrence(RecurrencePattern pattern)
 {
     DayOfMonth        = pattern.DayOfMonth;
     DaysOfTheWeekMask = (DaysOfWeek)pattern.DayOfWeekMask;
     Duration          = pattern.Duration;
     EndTime           = pattern.EndTime.ToString("HH:mm:sszzz");
     StartTime         = pattern.StartTime.ToString("HH:mm:sszzz");
     Instance          = pattern.Instance;
     Interval          = pattern.Interval;
     MonthOfYear       = pattern.MonthOfYear;
     NoEndDate         = pattern.NoEndDate;
     Occurrences       = pattern.Occurrences;
     PatternStartDate  = pattern.PatternStartDate.ToString("yyyy-MM-dd");
     PatternEndDate    = pattern.PatternEndDate.ToString("yyyy-MM-dd");
     Type = (RecurrenceType)pattern.RecurrenceType;
 }
Example #6
0
        static public void AddNewEvent(iCalendar iCal, EventInfo ei)
        {
            Event evt = iCal.Create <Event>();

            evt.DTStart = new iCalDateTime(ei.Pattern.BeginDate.Year, ei.Pattern.BeginDate.Month, ei.Pattern.BeginDate.Day, ei.Begin.Hour, ei.Begin.Minute, ei.Begin.Second);
            evt.DTEnd   = new iCalDateTime(ei.Pattern.BeginDate.Year, ei.Pattern.BeginDate.Month, ei.Pattern.BeginDate.Day, ei.End.Hour, ei.End.Minute, ei.End.Second);

            evt.Description = "#Disc:" + ei.Discipline + "#Type:" + ei.Type + "#Teacher:" + ei.Teacher + "#IsMoved:" + ei.IsMoved.ToString();
            evt.Location    = ei.Room;
            evt.Summary     = ei.Discipline + ", " + ei.Type + ", " + ei.Teacher + ", с " + ei.Begin.ToShortTimeString() + " до " + ei.End.ToShortTimeString() + ".";

            //List<ICalendarProperty> props = new List<ICalendarProperty>(;

            //evt.Properties.

            if (ei.IsMoved)
            {
                evt.Summary = evt.Summary + " Перенесено.";
            }

            FrequencyType ft = FrequencyType.None;

            switch (ei.Pattern.Type)
            {
            case 1: ft = FrequencyType.Daily;
                break;

            case 2: ft = FrequencyType.Weekly;
                break;

            case 3: ft = FrequencyType.Monthly;
                break;
            }

            RecurrencePattern rp = new RecurrencePattern(ft, ei.Pattern.Frequency);

            List <WeekDay> wdList = GetDayFromMask(ei.Pattern.RepeatMask);

            foreach (WeekDay wd in wdList)
            {
                rp.ByDay.Add(wd);
            }

            rp.Until = ei.Pattern.EndDate;

            evt.RecurrenceRules.Add(rp);
        }
Example #7
0
        private void processOutlookExceptions(AppointmentItem ai, Event ev, Boolean forceCompare)
        {
            if (!HasExceptions(ev, checkLocalCacheOnly: true))
            {
                return;
            }

            if (!ai.Saved)
            {
                ai.Save();
            }

            RecurrencePattern oPattern = ai.GetRecurrencePattern();

            foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id))
            {
                log.Fine("Found Google exception for " + (gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date));

                DateTime        oExcpDate = DateTime.Parse(gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date);
                AppointmentItem newAiExcp = getOutlookInstance(oPattern, oExcpDate);
                if (newAiExcp == null)
                {
                    continue;
                }

                if (gExcp.Status != "cancelled")
                {
                    int itemModified = 0;
                    newAiExcp = OutlookCalendar.Instance.UpdateCalendarEntry(newAiExcp, gExcp, ref itemModified, forceCompare);
                    if (itemModified > 0)
                    {
                        newAiExcp.Save();
                    }
                }
                else
                {
                    MainForm.Instance.Logboxout(OutlookCalendar.GetEventSummary(ai) + "\r\nDeleted.");
                    newAiExcp.Delete();
                }
                newAiExcp = (AppointmentItem)OutlookCalendar.ReleaseObject(newAiExcp);
            }
            if (!ai.Saved)
            {
                ai.Save();
            }
            oPattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(oPattern);
        }
Example #8
0
        public static ObservableCollection <Appointment> GenerateAppointments()
        {
            var recurrencePattern   = new RecurrencePattern(new int[] { }, RecurrenceDays.WeekDays, RecurrenceFrequency.Daily, 1, null, null);
            var dailyRecurrenceRule = new RecurrenceRule(recurrencePattern);

            return(new ObservableCollection <Appointment>
            {
                new Appointment
                {
                    StartDate = DateTime.Today.AddHours(8),
                    EndDate = DateTime.Today.AddHours(8.5),
                    Title = "Meeting",
                    Color = AppointmentColors[0],
                    RecurrenceRule = dailyRecurrenceRule
                },
                new Appointment
                {
                    StartDate = DateTime.Today.AddDays(1),
                    EndDate = DateTime.Today.AddDays(3),
                    Title = "UX Conference",
                    Color = AppointmentColors[0],
                    IsAllDay = true
                },
                new Appointment
                {
                    StartDate = DateTime.Today.AddHours(9),
                    EndDate = DateTime.Today.AddHours(10),
                    Title = "Retrospective meeting",
                    Color = AppointmentColors[1]
                },
                new Appointment
                {
                    StartDate = DateTime.Today.AddDays(1).AddHours(10),
                    EndDate = DateTime.Today.AddDays(1).AddHours(12),
                    Title = "Planning",
                    Color = AppointmentColors[2]
                },
                new Appointment
                {
                    StartDate = DateTime.Today.AddDays(3).AddHours(8),
                    EndDate = DateTime.Today.AddDays(3).AddHours(9),
                    Title = "Meeting",
                    Color = AppointmentColors[3]
                }
            });
        }
        /**
         * Returns a list of possible dates generated from the applicable BY* rules, using the specified date as a seed.
         * @param date the seed date
         * @param value the type of date list to return
         * @return a DateList
         */

        private List <DateTime> GetCandidates(DateTime date, RecurrencePattern pattern, bool?[] expandBehaviors)
        {
            var dates = new List <DateTime> {
                date
            };

            dates = GetMonthVariants(dates, pattern, expandBehaviors[0]);
            dates = GetWeekNoVariants(dates, pattern, expandBehaviors[1]);
            dates = GetYearDayVariants(dates, pattern, expandBehaviors[2]);
            dates = GetMonthDayVariants(dates, pattern, expandBehaviors[3]);
            dates = GetDayVariants(dates, pattern, expandBehaviors[4]);
            dates = GetHourVariants(dates, pattern, expandBehaviors[5]);
            dates = GetMinuteVariants(dates, pattern, expandBehaviors[6]);
            dates = GetSecondVariants(dates, pattern, expandBehaviors[7]);
            dates = ApplySetPosRules(dates, pattern);
            return(dates);
        }
Example #10
0
        public async Task <ActionResult> Save(string data)
        {
            return(await RunActionAsync(async() =>
            {
                var model = data?.JsonToEntity <CalendarEventEntity>(throwIfException: false);
                if (model == null)
                {
                    return GetJsonRes("参数错误");
                }
                if (model.ByDay != null && model.ByDay.Value > 0)
                {
                    var rrule = new RecurrencePattern(FrequencyType.Daily, model.ByDay.Value);
                    var serializer = new RecurrencePatternSerializer();
                    var s = serializer.SerializeToString(rrule);
                    model.RRule = s;
                }
                model.HasRule = ValidateHelper.IsPlumpString(model.RRule).ToBoolInt();

                var org_uid = this.GetSelectedOrgUID();
                var loginuser = await this.X.context.GetAuthUserAsync();

                model.OrgUID = org_uid;
                model.UserUID = loginuser?.UserID;


                if (ValidateHelper.IsPlumpString(model.UID))
                {
                    var res = await this._calService.UpdateEvent(model);
                    if (res.error)
                    {
                        return GetJsonRes(res.msg);
                    }
                }
                else
                {
                    var res = await this._calService.AddEvent(model);
                    if (res.error)
                    {
                        return GetJsonRes(res.msg);
                    }
                }


                return GetJsonRes(string.Empty);
            }));
        }
        /**
         * Applies BYDAY rules specified in this Recur instance to the specified date list. If no BYDAY rules are specified
         * the date list is returned unmodified.
         * @param dates
         * @return
         */

        private List <DateTime> GetDayVariants(List <DateTime> dates, RecurrencePattern pattern, bool?expand)
        {
            if (expand == null || pattern.ByDay.Count == 0)
            {
                return(dates);
            }

            if (expand.Value)
            {
                // Expand behavior
                var weekDayDates = new List <DateTime>();
                foreach (var date in dates)
                {
                    foreach (var day in pattern.ByDay)
                    {
                        weekDayDates.AddRange(GetAbsWeekDays(date, day, pattern));
                    }
                }

                return(weekDayDates);
            }

            // Limit behavior
            for (var i = dates.Count - 1; i >= 0; i--)
            {
                var date = dates[i];
                for (var j = 0; j < pattern.ByDay.Count; j++)
                {
                    var weekDay = pattern.ByDay[j];
                    if (weekDay.DayOfWeek.Equals(date.DayOfWeek))
                    {
                        // If no offset is specified, simply test the day of week!
                        // FIXME: test with offset...
                        if (date.DayOfWeek.Equals(weekDay.DayOfWeek))
                        {
                            goto Next;
                        }
                    }
                }
                dates.RemoveAt(i);
Next:
                ;
            }

            return(dates);
        }
Example #12
0
        public static RecurrencePattern CloneRecurrencePattern(RecurrencePattern pattern)
        {
            RecurrencePattern result = null;

            if (pattern == null)
            {
                return(result);
            }
            DailyRecurrencePattern dailyRecurrencePattern = pattern as DailyRecurrencePattern;

            if (dailyRecurrencePattern != null)
            {
                return(new DailyRecurrencePattern(dailyRecurrencePattern.RecurrenceInterval));
            }
            MonthlyRecurrencePattern monthlyRecurrencePattern = pattern as MonthlyRecurrencePattern;

            if (monthlyRecurrencePattern != null)
            {
                return(new MonthlyRecurrencePattern(monthlyRecurrencePattern.DayOfMonth, monthlyRecurrencePattern.RecurrenceInterval, monthlyRecurrencePattern.CalendarType));
            }
            MonthlyThRecurrencePattern monthlyThRecurrencePattern = pattern as MonthlyThRecurrencePattern;

            if (monthlyThRecurrencePattern != null)
            {
                return(new MonthlyThRecurrencePattern(monthlyThRecurrencePattern.DaysOfWeek, monthlyThRecurrencePattern.Order, monthlyThRecurrencePattern.RecurrenceInterval, monthlyThRecurrencePattern.CalendarType));
            }
            WeeklyRecurrencePattern weeklyRecurrencePattern = pattern as WeeklyRecurrencePattern;

            if (weeklyRecurrencePattern != null)
            {
                return(new WeeklyRecurrencePattern(weeklyRecurrencePattern.DaysOfWeek, weeklyRecurrencePattern.RecurrenceInterval, weeklyRecurrencePattern.FirstDayOfWeek));
            }
            YearlyRecurrencePattern yearlyRecurrencePattern = pattern as YearlyRecurrencePattern;

            if (yearlyRecurrencePattern != null)
            {
                return(new YearlyRecurrencePattern(yearlyRecurrencePattern.DayOfMonth, yearlyRecurrencePattern.Month, yearlyRecurrencePattern.IsLeapMonth, yearlyRecurrencePattern.CalendarType));
            }
            YearlyThRecurrencePattern yearlyThRecurrencePattern = pattern as YearlyThRecurrencePattern;

            if (yearlyThRecurrencePattern != null)
            {
                return(new YearlyThRecurrencePattern(yearlyThRecurrencePattern.DaysOfWeek, yearlyThRecurrencePattern.Order, yearlyThRecurrencePattern.Month, yearlyThRecurrencePattern.IsLeapMonth, yearlyThRecurrencePattern.CalendarType));
            }
            throw new ArgumentException("Unhandled RecurrencePattern type.");
        }
Example #13
0
        public override string ReadItemToText(TaskItem item)
        {
            XElement element = new XElement("note",
                                            new XElement("SIFVersion", "1.0"),
                                            DataUtility.CreateElement("ActualWork", item.ActualWork.ToString()),
                                            DataUtility.CreateElement("BillingInformation", item.BillingInformation),
                                            DataUtility.CreateElement("Companies", item.Companies),
                                            DataUtility.CreateElement("Categories", item.Categories),
                                            DataUtility.CreateElement("Complete", item.Complete ? "1" : "0"),
                                            DataUtility.CreateElement("DueDate", item.DueDate.ToUniversalTime().ToString(isoFormat)),
                                            DataUtility.CreateElement("DateCompleted", item.DateCompleted.ToString(isoFormat)),
                                            DataUtility.CreateElement("Body", item.Body),
                                            DataUtility.CreateElement("Importance", ((int)item.Importance).ToString()),
                                            DataUtility.CreateElement("Mileage", item.Mileage),
                                            DataUtility.CreateElement("PercentComplete", item.PercentComplete.ToString()),
                                            DataUtility.CreateElement("ReminderSet", item.ReminderSet ? "1" : "0"),
                                            DataUtility.CreateElement("ReminderTime", item.ReminderTime.ToUniversalTime().ToString(isoFormat)),
                                            DataUtility.CreateElement("ReminderSoundFile", item.ReminderSoundFile),
                                            DataUtility.CreateElement("IsRecurring", item.IsRecurring ? "1" : "0"),
                                            DataUtility.CreateElement("Sensitivity", ((int)item.Sensitivity).ToString()),
                                            DataUtility.CreateElement("StartDate", item.StartDate.ToUniversalTime().ToString(isoFormat)),
                                            DataUtility.CreateElement("Status", ((int)item.Status).ToString()),
                                            DataUtility.CreateElement("Subject", item.Subject),
                                            DataUtility.CreateElement("TeamTask", item.TeamTask ? "1" : "0"),
                                            DataUtility.CreateElement("TotalWork", item.TotalWork.ToString())
                                            );

            if (item.IsRecurring)
            {
                RecurrencePattern pattern = item.GetRecurrencePattern();
                element.Add(
                    DataUtility.CreateElement("DayOfMonth", pattern.DayOfMonth.ToString()),
                    DataUtility.CreateElement("DayOfWeekMask", ((int)pattern.DayOfWeekMask).ToString()),
                    DataUtility.CreateElement("Interval", pattern.Interval.ToString()),
                    DataUtility.CreateElement("Instance", pattern.Instance.ToString()),
                    DataUtility.CreateElement("MonthOfYear", pattern.MonthOfYear.ToString()),
                    DataUtility.CreateElement("NoEndDate", pattern.NoEndDate ? "1" : "0"),
                    DataUtility.CreateElement("Occurrences", pattern.Occurrences.ToString()),
                    DataUtility.CreateElement("PatternStartDate", pattern.PatternStartDate.ToUniversalTime().ToString(isoFormat)),
                    DataUtility.CreateElement("PatternEndDate", pattern.PatternEndDate.ToUniversalTime().ToString(isoFormat)),
                    DataUtility.CreateElement("RecurrenceType", ((int)pattern.RecurrenceType).ToString())
                    );
            }

            return(element.ToString(SaveOptions.DisableFormatting));
        }
Example #14
0
        protected void IncrementDate(ref DateTime dt, RecurrencePattern pattern, int interval)
        {
            // FIXME: use a more specific exception.
            if (interval == 0)
            {
                throw new Exception("Cannot evaluate with an interval of zero.  Please use an interval other than zero.");
            }

            var old = dt;

            switch (pattern.Frequency)
            {
            case FrequencyType.Secondly:
                dt = old.AddSeconds(interval);
                break;

            case FrequencyType.Minutely:
                dt = old.AddMinutes(interval);
                break;

            case FrequencyType.Hourly:
                dt = old.AddHours(interval);
                break;

            case FrequencyType.Daily:
                dt = old.AddDays(interval);
                break;

            case FrequencyType.Weekly:
                dt = DateUtil.AddWeeks(old, interval, pattern.FirstDayOfWeek);
                break;

            case FrequencyType.Monthly:
                dt = old.AddDays(-old.Day + 1).AddMonths(interval);
                break;

            case FrequencyType.Yearly:
                dt = old.AddDays(-old.DayOfYear + 1).AddYears(interval);
                break;

            // FIXME: use a more specific exception.
            default:
                throw new Exception("FrequencyType.NONE cannot be evaluated. Please specify a FrequencyType before evaluating the recurrence.");
            }
        }
        private static bool IsOutlookPatternDifferent(MeetingRequest mrbs, RecurrencePattern pattern)
        {
            bool different = false;

            switch (mrbs.RepeatTypeId)
            {
            case 1:
                different |= pattern.RecurrenceType != OlRecurrenceType.olRecursDaily;
                break;

            case 2:
                char[] rev = mrbs.RepeatWeeklyCode.ToCharArray();

                different |= pattern.RecurrenceType != OlRecurrenceType.olRecursWeekly;
                different |= pattern.Interval != mrbs.RepeatNumberOfWeeks;
                different |= pattern.DayOfWeekMask != (OlDaysOfWeek)Convert.ToInt32(new string(mrbs.RepeatWeeklyCode.ToCharArray().Reverse().ToArray()), 2);
                break;

            case 3:
                if (mrbs.RepeatMonthlyByWeekday)
                {
                    different |= pattern.RecurrenceType != OlRecurrenceType.olRecursMonthNth;
                    different |= pattern.DayOfWeekMask != (OlDaysOfWeek)((int)Math.Pow(2, mrbs.RepeatWeekdayOfMonth));
                    different |= pattern.Instance != mrbs.RepeatWeekdaysOfMonth;
                }
                else
                {
                    different |= pattern.RecurrenceType != OlRecurrenceType.olRecursMonthly;
                    different |= pattern.DayOfMonth != mrbs.RepeatDayOfMonth;
                }
                break;

            case 4:
                different |= pattern.RecurrenceType != OlRecurrenceType.olRecursYearly;
                break;
            }

            different |= pattern.Duration != (mrbs.End - mrbs.Start).Minutes;
            different |= pattern.EndTime != (mrbs.RepeatEnd.Date + mrbs.End.TimeOfDay);
            different |= pattern.PatternStartDate != mrbs.Start;
            different |= pattern.PatternEndDate != (mrbs.RepeatEnd + mrbs.End.TimeOfDay);
            different |= pattern.StartTime != mrbs.Start;

            return(different);
        }
Example #16
0
        /// <summary>
        /// Gets the recurrence summary for a yearly recurrence pattern.
        /// </summary>
        /// <param name="pattern">The recurrence pattern.</param>
        /// <param name="resourceFile">The resource file to use to find get localized text.</param>
        /// <returns>A human-readable, localized summary of the provided recurrence pattern.</returns>
        private static string GetYearlyRecurrenceSummary(RecurrencePattern pattern, string resourceFile)
        {
            if (pattern.DayOfMonth > 0)
            {
                return(string.Format(
                           CultureInfo.CurrentCulture,
                           Localization.GetString("YearlyRecurrenceOnDate.Text", resourceFile),
                           new DateTime(1, (int)pattern.Month, 1),
                           pattern.DayOfMonth));
            }

            return(string.Format(
                       CultureInfo.CurrentCulture,
                       Localization.GetString("YearlyRecurrenceOnGivenDay.Text", resourceFile),
                       Localization.GetString(OrdinalValuesDictionary[pattern.DayOrdinal], resourceFile),
                       GetLocalizedDayOfWeek(pattern.DaysOfWeekMask, resourceFile),
                       new DateTime(1, (int)pattern.Month, 1)));
        }
Example #17
0
        public static RecurrencePattern ToPattern(this Recurrence recurrence)
        {
            if (recurrence == null)
            {
                return(null);
            }

            var pattern = new RecurrencePattern
            {
                Until      = recurrence.Until,
                Interval   = recurrence.Interval,
                ByDay      = recurrence.ByDay == null ? new List <IWeekDay>() : new List <IWeekDay>(recurrence.ByDay),
                Frequency  = recurrence.Frequency,
                ByMonthDay = recurrence.ByMonthDay
            };

            return(pattern);
        }
        /// <summary>
        /// Creates the view.
        /// </summary>
        /// <param name="scheduler">The scheduler.</param>
        /// <param name="appointment">The appointment.</param>
        /// <returns></returns>
        internal static RecurrenceDialogViewModel CreateView(IScheduler scheduler, IAppointment appointment)
        {
            var         view    = new RecurrenceDialogViewModel(scheduler);
            CultureInfo culture = scheduler.GetCultureInUse();

            DateTime start = appointment.Start;

            RecurrencePattern recurrencePattern = appointment.RecurrenceRule == null
                                                      ? new RecurrencePattern
            {
                Frequency      = RecurrenceFrequency.Weekly,
                Interval       = 1,
                DaysOfWeekMask =
                    appointment.Start.DayOfWeek.GetRecurrenceDay(),
                FirstDayOfWeek = scheduler.GetFirstDayOfWeekInUse(),
            }
                                                      : appointment.RecurrenceRule.Pattern.Copy();

            view.Start          = start;
            view.Duration       = appointment.End - appointment.Start;
            view.MaxOccurrences = recurrencePattern.MaxOccurrences ?? DefaultMaxOccurrences;
            if (recurrencePattern.RecursUntil.HasValue)
            {
                view.RecursUntil = recurrencePattern.RecursUntil.Value;
            }
            view.RecurrenceRangeType = GetRangeType(recurrencePattern);

            view.Interval         = recurrencePattern.Interval;
            view.RecurrenceType   = GetTypeFromRule(recurrencePattern);
            view.DayOfMonth       = recurrencePattern.DayOfMonth ?? culture.Calendar.GetDayOfMonth(start);
            view.NthRecurrenceDay = recurrencePattern.DaysOfWeekMask == RecurrenceDays.None
                                        ? start.DayOfWeek.GetRecurrenceDay()
                                        : recurrencePattern.DaysOfWeekMask;
            view.MonthOfYear = recurrencePattern.MonthOfYear ?? start.Month;
            view.WeekOfMonth = recurrencePattern.DayOrdinal.HasValue
                                   ? FromIntToWeekOfMonth(recurrencePattern.DayOrdinal.Value)
                                   : GetWeekOfMonth(start, view.DayOfMonth);
            view.WeekDays          = CreateWeekDays(scheduler, view.NthRecurrenceDay);
            view.NamesOfMonths     = CalendarHelper.GetNamesOfMonths(culture);
            view.WeekOfMonths      = CreateWeekOfMonths();
            view.nthRecurrenceDays = CreateNthRecurrenceDays(scheduler);

            return(view);
        }
        /**
         * Applies BYYEARDAY rules specified in this Recur instance to the specified date list. If no BYYEARDAY rules are
         * specified the date list is returned unmodified.
         * @param dates
         * @return
         */

        private List <DateTime> GetYearDayVariants(List <DateTime> dates, RecurrencePattern pattern, bool?expand)
        {
            if (expand == null || pattern.ByYearDay.Count == 0)
            {
                return(dates);
            }

            if (expand.Value)
            {
                var yearDayDates = new List <DateTime>(dates.Count);
                foreach (var date in dates)
                {
                    var date1 = date;
                    yearDayDates.AddRange(pattern.ByYearDay.Select(yearDay => yearDay > 0
                        ? date1.AddDays(-date1.DayOfYear + yearDay)
                        : date1.AddDays(-date1.DayOfYear + 1).AddYears(1).AddDays(yearDay)));
                }
                return(yearDayDates);
            }
            // Limit behavior
            for (var i = dates.Count - 1; i >= 0; i--)
            {
                var date = dates[i];
                for (var j = 0; j < pattern.ByYearDay.Count; j++)
                {
                    var yearDay = pattern.ByYearDay[j];

                    var newDate = yearDay > 0
                        ? date.AddDays(-date.DayOfYear + yearDay)
                        : date.AddDays(-date.DayOfYear + 1).AddYears(1).AddDays(yearDay);

                    if (newDate.DayOfYear == date.DayOfYear)
                    {
                        goto Next;
                    }
                }

                dates.RemoveAt(i);
Next:
                ;
            }

            return(dates);
        }
Example #20
0
        private static AppointmentItem getOutlookInstance(RecurrencePattern oPattern, DateTime instanceDate)
        {
            //First check if this is not yet an exception
            AppointmentItem ai = null;

            try {
                ai = oPattern.GetOccurrence(instanceDate);
            } catch { }
            if (ai == null)
            {
                //The Outlook API is rubbish as the date argument is how it exists NOW (not OriginalDate).
                //If this has changed >1 in Google then there's no way of knowing what it might be!

                foreach (Microsoft.Office.Interop.Outlook.Exception oExp in oPattern.Exceptions)
                {
                    if (oExp.OriginalDate.Date == instanceDate.Date)
                    {
                        try {
                            log.Debug("Found Outlook exception for " + instanceDate);
                            if (exceptionIsDeleted(oExp))
                            {
                                log.Debug("This exception is deleted.");
                                return(null);
                            }
                            else
                            {
                                return(oExp.AppointmentItem);
                            }
                        } catch (System.Exception ex) {
                            MainForm.Instance.Logboxout(ex.Message);
                            MainForm.Instance.Logboxout("If this keeps happening, please restart OGCS.");
                            break;
                        } finally {
                            OutlookCalendar.ReleaseObject(oExp);
                        }
                    }
                }
                if (ai == null)
                {
                    log.Warn("Unable to find Outlook exception for " + instanceDate);
                }
            }
            return(ai);
        }
Example #21
0
        public void CompareOutlookPattern(Event ev, AppointmentItem ai, System.Text.StringBuilder sb, ref int itemModified)
        {
            if (ev.Recurrence == null)
            {
                return;
            }

            log.Fine("Building a temporary recurrent Appointment generated from Event");
            AppointmentItem   evAI = OutlookCalendar.Instance.IOutlook.UseOutlookCalendar().Items.Add() as AppointmentItem;
            RecurrencePattern evOpattern;
            RecurrencePattern aiOpattern = ai.GetRecurrencePattern();

            BuildOutlookPattern(ev, evAI, out evOpattern);
            log.Fine("Comparing Google recurrence to Outlook equivalent");

            if (MainForm.CompareAttribute("Recurrence Type", Settings.Instance.SyncDirection,
                                          evOpattern.RecurrenceType.ToString(), aiOpattern.RecurrenceType.ToString(), sb, ref itemModified))
            {
                aiOpattern.RecurrenceType = evOpattern.RecurrenceType;
            }
            if (MainForm.CompareAttribute("Recurrence Interval", Settings.Instance.SyncDirection,
                                          evOpattern.Interval.ToString(), aiOpattern.Interval.ToString(), sb, ref itemModified))
            {
                aiOpattern.Interval = evOpattern.Interval;
            }
            if (MainForm.CompareAttribute("Recurrence Instance", Settings.Instance.SyncDirection,
                                          evOpattern.Instance.ToString(), aiOpattern.Instance.ToString(), sb, ref itemModified))
            {
                aiOpattern.Instance = evOpattern.Instance;
            }
            if (MainForm.CompareAttribute("Recurrence DoW", Settings.Instance.SyncDirection,
                                          evOpattern.DayOfWeekMask.ToString(), aiOpattern.DayOfWeekMask.ToString(), sb, ref itemModified))
            {
                aiOpattern.DayOfWeekMask = evOpattern.DayOfWeekMask;
            }
            if (MainForm.CompareAttribute("Recurrence MoY", Settings.Instance.SyncDirection,
                                          evOpattern.MonthOfYear.ToString(), aiOpattern.MonthOfYear.ToString(), sb, ref itemModified))
            {
                aiOpattern.MonthOfYear = evOpattern.MonthOfYear;
            }
            aiOpattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(aiOpattern);
            evOpattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(evOpattern);
            evAI       = (AppointmentItem)OutlookCalendar.ReleaseObject(evAI);
        }
Example #22
0
        /// <summary>
        /// Sets up the controls in <see cref="RecurrencePatternYearlyView"/>.
        /// </summary>
        /// <param name="pattern">The recurrence pattern.</param>
        private void SetupYearlyRecurrence(RecurrencePattern pattern)
        {
            this.RepeatFrequencyYearly.Checked = true;

            this.RepeatEveryYearOnDate.Checked     = pattern.DayOfMonth > 0;
            this.RepeatEveryYearOnGivenDay.Checked = !this.RepeatEveryYearOnDate.Checked;

            if (this.RepeatEveryYearOnDate.Checked)
            {
                this.YearlyRepeatMonthForDate.SetSelectedEnum(pattern.Month);
                this.YearlyRepeatDateTextBox.Text = pattern.DayOfMonth.ToString(CultureInfo.CurrentCulture);
            }
            else
            {
                this.YearlyDayOrdinalDropDown.SetSelectedInt32(pattern.DayOrdinal);
                this.YearlyDayMaskDropDown.SetSelectedEnum(pattern.DaysOfWeekMask);
                this.YearlyRepeatMonthForGivenDay.SetSelectedEnum(pattern.Month);
            }
        }
        public static RecurrencePattern GetDailyRecurrencePattern(DateTime?recurrenceEndDate = null, int?occurrenceCount = null, int?interval = 1)
        {
            // Repeat daily from the start date until the specified end date or a set number of recurrences, at the specified interval.
            var pattern = $"RRULE:FREQ=DAILY;INTERVAL={interval}";

            if (recurrenceEndDate != null)
            {
                pattern += $";UNTIL={recurrenceEndDate:yyyyMMdd}";
            }

            if (occurrenceCount != null)
            {
                pattern += $";COUNT={occurrenceCount}";
            }

            var recurrencePattern = new RecurrencePattern(pattern);

            return(recurrencePattern);
        }
Example #24
0
        private CalendarEvent AsIcsEvent(Template template, string description, RecurrencePattern rule)
        {
            var e = new CalendarEvent
            {
                Start       = new CalDateTime(_timeManager.ToUtc(template.Start)),
                End         = new CalDateTime(_endTime),
                Summary     = template.Name,
                Description = description,
                Url         = template.Uri
            };

            if (template.IsWeekly)
            {
                e.RecurrenceRules = new List <RecurrencePattern> {
                    rule
                };
            }
            return(e);
        }
        // From: http://sourcefield.blogspot.com/2011/06/dday-ical-example.html
        public void Example()
        {
            // #1: Monthly meetings that occur on the last Wednesday from 6pm - 7pm

            // Create an iCalendar
            var iCal = new iCalendar();

            // Create the event
            var evt = iCal.Create<Event>();
            evt.Summary = "Test Event";
            evt.Start = new iCalDateTime(2008, 1, 1, 18, 0, 0); // Starts January 1, 2008 @ 6:00 P.M.
            evt.Duration = TimeSpan.FromHours(1);

            // Add a recurrence pattern to the event
            var rp = new RecurrencePattern {Frequency = FrequencyType.Monthly};
            rp.ByDay.Add(new WeekDay(DayOfWeek.Wednesday, FrequencyOccurrence.Last));
            evt.RecurrenceRules.Add(rp);

            // #2: Yearly events like holidays that occur on the same day each year.
            // The same as #1, except:
            var rp2 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            evt.RecurrenceRules.Add(rp2);

            // #3: Yearly events like holidays that occur on a specific day like the first monday.
            // The same as #1, except:
            var rp3 = new RecurrencePattern {Frequency = FrequencyType.Yearly};
            rp3.ByMonth.Add(3);
            rp3.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));
            evt.RecurrenceRules.Add(rp3);

            /*
            Note that all events occur on their start time, no matter their
            recurrence pattern. So, for example, you could occur on the first Monday
            of every month, but if your event is scheduled for a Friday (i.e.
            evt.Start = new iCalDateTime(2008, 3, 7, 18, 0, 0)), then it will first
            occur on that Friday, and then the first Monday of every month after
            that.

             this can be worked around by doing this:
             IPeriod nextOccurrence = pattern.GetNextOccurrence(dt);
             evt.Start = nextOccurrence.StartTime;
             */
        }
Example #26
0
        private static CalendarEvent GetEventWithRecurrenceRules(string tzId)
        {
            var dailyForFiveDays = new RecurrencePattern(FrequencyType.Daily, 1)
            {
                Count = 5,
            };

            var calendarEvent = new CalendarEvent
            {
                Start           = new CalDateTime(_now, tzId),
                End             = new CalDateTime(_later, tzId),
                RecurrenceRules = new List <RecurrencePattern> {
                    dailyForFiveDays
                },
                Resources = new List <string>(new[] { "Foo", "Bar", "Baz" }),
            };

            return(calendarEvent);
        }
        private static void AddAppointmentsForTheWeek(ObservableCollection <Appointment> result, DateTime today, string subject, string resourceName, string resourceType, TimeSpan start, TimeSpan end)
        {
            var monday  = today.AddDays(-(int)today.DayOfWeek).AddDays(1);
            var pattern = new RecurrencePattern()
            {
                Frequency      = RecurrenceFrequency.Daily,
                MaxOccurrences = 5
            };
            var appointment = new Appointment()
            {
                Start          = new DateTime(monday.Year, monday.Month, monday.Day, start.Hours, start.Minutes, start.Seconds),
                End            = new DateTime(monday.Year, monday.Month, monday.Day, end.Hours, end.Minutes, end.Seconds),
                Subject        = subject,
                RecurrenceRule = new RecurrenceRule(pattern)
            };

            appointment.Resources.Add(new Resource(resourceName, resourceType));
            result.Add(appointment);
        }
Example #28
0
        /**
         * Applies BYMINUTE rules specified in this Recur instance to the specified date list. If no BYMINUTE rules are
         * specified the date list is returned unmodified.
         * @param dates
         * @return
         */

        private List <DateTime> GetMinuteVariants(List <DateTime> dates, RecurrencePattern pattern, bool?expand)
        {
            if (expand == null || pattern.ByMinute.Count == 0)
            {
                return(dates);
            }

            if (expand.Value)
            {
                // Expand behavior
                var minutelyDates = new List <DateTime>(128);
                for (var i = 0; i < dates.Count; i++)
                {
                    var date = dates[i];
                    for (var j = 0; j < pattern.ByMinute.Count; j++)
                    {
                        var minute = pattern.ByMinute[j];
                        date = date.AddMinutes(-date.Minute + minute);
                        minutelyDates.Add(date);
                    }
                }
                return(minutelyDates);
            }
            // Limit behavior
            for (var i = dates.Count - 1; i >= 0; i--)
            {
                var date = dates[i];
                for (var j = 0; j < pattern.ByMinute.Count; j++)
                {
                    var minute = pattern.ByMinute[j];
                    if (date.Minute == minute)
                    {
                        goto Next;
                    }
                }
                // Remove unmatched dates
                dates.RemoveAt(i);
Next:
                ;
            }
            return(dates);
        }
        /**
         * Applies BYHOUR rules specified in this Recur instance to the specified date list. If no BYHOUR rules are
         * specified the date list is returned unmodified.
         * @param dates
         * @return
         */

        private List <DateTime> GetHourVariants(List <DateTime> dates, RecurrencePattern pattern, bool?expand)
        {
            if (expand == null || pattern.ByHour.Count == 0)
            {
                return(dates);
            }

            if (expand.Value)
            {
                // Expand behavior
                var hourlyDates = new List <DateTime>();
                for (var i = 0; i < dates.Count; i++)
                {
                    var date = dates[i];
                    for (var j = 0; j < pattern.ByHour.Count; j++)
                    {
                        var hour = pattern.ByHour[j];
                        date = date.AddHours(-date.Hour + hour);
                        hourlyDates.Add(date);
                    }
                }
                return(hourlyDates);
            }
            // Limit behavior
            for (var i = dates.Count - 1; i >= 0; i--)
            {
                var date = dates[i];
                for (var j = 0; j < pattern.ByHour.Count; j++)
                {
                    var hour = pattern.ByHour[j];
                    if (date.Hour == hour)
                    {
                        goto Next;
                    }
                }
                // Remove unmatched dates
                dates.RemoveAt(i);
Next:
                ;
            }
            return(dates);
        }
        /**
         * Applies BYSECOND rules specified in this Recur instance to the specified date list. If no BYSECOND rules are
         * specified the date list is returned unmodified.
         * @param dates
         * @return
         */

        private List <DateTime> GetSecondVariants(List <DateTime> dates, RecurrencePattern pattern, bool?expand)
        {
            if (expand == null || pattern.BySecond.Count == 0)
            {
                return(dates);
            }

            if (expand.Value)
            {
                // Expand behavior
                var secondlyDates = new List <DateTime>();
                for (var i = 0; i < dates.Count; i++)
                {
                    var date = dates[i];
                    for (var j = 0; j < pattern.BySecond.Count; j++)
                    {
                        var second = pattern.BySecond[j];
                        date = date.AddSeconds(-date.Second + second);
                        secondlyDates.Add(date);
                    }
                }
                return(secondlyDates);
            }
            // Limit behavior
            for (var i = dates.Count - 1; i >= 0; i--)
            {
                var date = dates[i];
                for (var j = 0; j < pattern.BySecond.Count; j++)
                {
                    var second = pattern.BySecond[j];
                    if (date.Second == second)
                    {
                        goto Next;
                    }
                }
                // Remove unmatched dates
                dates.RemoveAt(i);
Next:
                ;
            }
            return(dates);
        }
Example #31
0
        public void SkippedOccurrenceOnWeeklyPattern()
        {
            const int evaluationsCount = 1000;
            var       eventStart       = new CalDateTime(new DateTime(2016, 1, 1, 10, 0, 0, DateTimeKind.Utc));
            var       eventEnd         = new CalDateTime(new DateTime(2016, 1, 1, 11, 0, 0, DateTimeKind.Utc));
            var       vEvent           = new CalendarEvent
            {
                DtStart = eventStart,
                DtEnd   = eventEnd,
            };

            var pattern = new RecurrencePattern
            {
                Frequency = FrequencyType.Weekly,
                ByDay     = new List <WeekDay> {
                    new WeekDay(DayOfWeek.Friday)
                }
            };

            vEvent.RecurrenceRules.Add(pattern);
            var calendar = new Calendar();

            calendar.Events.Add(vEvent);

            var intervalStart = eventStart;
            var intervalEnd   = intervalStart.AddDays(7 * evaluationsCount);

            var occurrences = RecurrenceUtil.GetOccurrences(
                recurrable: vEvent,
                periodStart: intervalStart,
                periodEnd: intervalEnd,
                includeReferenceDateInResults: false);
            var occurrenceSet = new HashSet <IDateTime>(occurrences.Select(o => o.Period.StartTime));

            Assert.AreEqual(evaluationsCount, occurrenceSet.Count);

            for (var currentOccurrence = intervalStart; currentOccurrence.CompareTo(intervalEnd) < 0; currentOccurrence = (CalDateTime)currentOccurrence.AddDays(7))
            {
                var contains = occurrenceSet.Contains(currentOccurrence);
                Assert.IsTrue(contains, $"Collection does not contain {currentOccurrence}, but it is a {currentOccurrence.DayOfWeek}");
            }
        }
        public void Calendar_Tests()
        {
            var rruleA = new RecurrencePattern(FrequencyType.Daily, 1)
            {
                Count = 5
            };

            var e = new Event
            {
                DtStart         = new CalDateTime(_nowTime),
                DtEnd           = new CalDateTime(_later),
                Duration        = TimeSpan.FromHours(1),
                RecurrenceRules = new List <IRecurrencePattern> {
                    rruleA
                },
            };

            var actualCalendar = new Calendar();

            actualCalendar.Events.Add(e);

            //Work around referential equality...
            var rruleB = new RecurrencePattern(FrequencyType.Daily, 1)
            {
                Count = 5
            };

            var expectedCalendar = new Calendar();

            expectedCalendar.Events.Add(new Event
            {
                DtStart         = new CalDateTime(_nowTime),
                DtEnd           = new CalDateTime(_later),
                Duration        = TimeSpan.FromHours(1),
                RecurrenceRules = new List <IRecurrencePattern> {
                    rruleB
                },
            });

            Assert.AreEqual(actualCalendar.GetHashCode(), expectedCalendar.GetHashCode());
            Assert.IsTrue(actualCalendar.Equals(expectedCalendar));
        }
Example #33
0
        /// <summary>
        /// Update an exception item in the collection
        /// </summary>
        /// <param name="source">The source of the event</param>
        /// <param name="e">The event arguments</param>
        protected void dgExceptions_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            RecurringObject ro = GetCurrentObject();

            RecurrencePattern rpException = (RecurrencePattern)e.Item.FindControl("rpException");

            Recurrence r = ro.ExceptionRules[e.Item.ItemIndex].Recurrence;

            r.Reset();
            rpException.GetRecurrence(r);

            dgExceptions.EditItemIndex = -1;
            dgExceptions.DataSource    = ro.ExceptionRules;
            dgExceptions.DataBind();
        }
Example #34
0
        public static Recurrence ToRecurrence(this RecurrencePattern pattern)
        {
            if (pattern == null)
            {
                return(new Recurrence());
            }

            var reucrrence = new Recurrence
            {
                Until    = pattern.Until,
                Interval = pattern.Interval,
                ByDay    = pattern.ByDay.Select(x => new WeekDay {
                    DayOfWeek = x.DayOfWeek, Offset = x.Offset
                }).ToList(),
                Frequency  = pattern.Frequency,
                ByMonthDay = pattern.ByMonthDay
            };

            return(reucrrence);
        }
Example #35
0
        public List <String> BuildGooglePattern(AppointmentItem ai, Event ev)
        {
            if (!ai.IsRecurring || ai.RecurrenceState != OlRecurrenceState.olApptMaster)
            {
                return(null);
            }

            log.Debug("Creating Google iCalendar definition for recurring event.");
            List <String>     gPattern = new List <String>();
            RecurrencePattern rp       = null;

            try {
                rp = ai.GetRecurrencePattern();
                gPattern.Add("RRULE:" + buildRrule(rp));
            } finally {
                rp = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(rp);
            }
            log.Debug(string.Join("\r\n", gPattern.ToArray()));
            return(gPattern);
        }
        public RecurrenceForm(RecurrencePattern pattern, RecurrenceRange range)
        {
            InitializeComponent();
            StringBuilder dow = new StringBuilder();
            int n = dgRecurrencePattern.Rows.Add();
            dgRecurrencePattern.Rows[n].Cells[0].Value = pattern.Type;
            dgRecurrencePattern.Rows[n].Cells[1].Value = pattern.Interval;
            dgRecurrencePattern.Rows[n].Cells[2].Value = pattern.DayOfMonth;
            dgRecurrencePattern.Rows[n].Cells[3].Value = pattern.Month;
            foreach (var item in pattern.DaysOfWeek)
            {
                dow.Append(item + "-");
            }
            dgRecurrencePattern.Rows[n].Cells[4].Value = dow;
            dgRecurrencePattern.Rows[n].Cells[5].Value = pattern.FirstDayOfWeek;
            dgRecurrencePattern.Rows[n].Cells[6].Value = pattern.Index;

            int x = dgRecurrenceRange.Rows.Add();
            dgRecurrenceRange.Rows[n].Cells[0].Value = range.Type;
            dgRecurrenceRange.Rows[n].Cells[1].Value = range.StartDate;
            dgRecurrenceRange.Rows[n].Cells[2].Value = range.EndDate;
            dgRecurrenceRange.Rows[n].Cells[3].Value = range.NumberOfOccurrences;
            dgRecurrenceRange.Rows[n].Cells[4].Value = range.RecurrenceTimeZone;
        }
Example #37
0
        static private void PopulateiCalTimeZoneInfo(ITimeZoneInfo tzi, System.TimeZoneInfo.TransitionTime transition, int year)
        {
            Calendar c = CultureInfo.CurrentCulture.Calendar;

            RecurrencePattern recurrence = new RecurrencePattern();            
            recurrence.Frequency = FrequencyType.Yearly;
            recurrence.ByMonth.Add(transition.Month);
            recurrence.ByHour.Add(transition.TimeOfDay.Hour);
            recurrence.ByMinute.Add(transition.TimeOfDay.Minute);

            if (transition.IsFixedDateRule)
            {
                recurrence.ByMonthDay.Add(transition.Day);
            }
            else
            {
                if( transition.Week != 5 )
                    recurrence.ByDay.Add(new WeekDay(transition.DayOfWeek, transition.Week ));
                else
                    recurrence.ByDay.Add( new WeekDay( transition.DayOfWeek, -1 ) );
            }

            tzi.RecurrenceRules.Add(recurrence);
        }
Example #38
0
 public TickRRule(string iCalString)
 {
     if (iCalString.Contains(TT_COMPLETED_COUNT_KEY))
     {
         //CompletedRepeatCount = RepeatUtils.GetIntFromRRule(TT_COMPLETED_COUNT_KEY, iCalString);
         //iCalString = RepeatUtils.RemoveKeyValueFromRRule(TT_COMPLETED_COUNT_KEY, iCalString);
     }
     String iCal;
     if (iCalString.Contains(LUNAR_RRULE_NAME))
     {
         iCal = iCalString.Replace(LUNAR_RRULE_NAME, RRULE_NAME);
         IsLunar = true;
     }
     else
     {
         iCal = iCalString;
         IsLunar = false;
     }
     //rRule = new RRule(iCal);
     //RecurringComponent = new DDay.iCal.RecurringComponent();
     RRule = new RecurrencePattern();
     //RRule = new RecurrencePattern(iCal);
     //RecurringComponent.RecurrenceRules.Add(RRule);
 }
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Daily;
			pattern.Interval = Interval;
			pattern.DaysOfWeekMask = RecurrenceDay.EveryDay;
			return pattern;
		}
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Weekly;
			pattern.Interval = Interval;
			pattern.DaysOfWeekMask = DaysOfWeekStringConverter.ConvertToRecurrenceDay(DaysOfWeek);
			return pattern;
		}
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Monthly;
			pattern.DayOfMonth = DayOfMonth;
			pattern.Interval = Interval;
			return pattern;
		}
        private IRecurrencePattern ProcessRecurrencePattern(IDateTime referenceDate)
        {
            RecurrencePattern r = new RecurrencePattern();
            r.CopyFrom(Pattern);

            // Convert the UNTIL value to a local date/time based on the time zone information that
            // is in the reference date
            if (r.Until != DateTime.MinValue)
            {
                // Build an iCalDateTime with the correct time zone & calendar
                var until = new iCalDateTime(r.Until, referenceDate.TZID);
                until.AssociatedObject = referenceDate.AssociatedObject;

                // Convert back to local time so time zone comparisons match
                r.Until = until.Local;
            }

            if (r.Frequency > FrequencyType.Secondly &&
                r.BySecond.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.BySecond.Add(referenceDate.Second);
            if (r.Frequency > FrequencyType.Minutely &&
                r.ByMinute.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByMinute.Add(referenceDate.Minute);
            if (r.Frequency > FrequencyType.Hourly &&
                r.ByHour.Count == 0 &&
                referenceDate.HasTime /* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
                r.ByHour.Add(referenceDate.Hour);

            // If BYDAY, BYYEARDAY, or BYWEEKNO is specified, then
            // we don't default BYDAY, BYMONTH or BYMONTHDAY
            if (r.ByDay.Count == 0)
            {
                // If the frequency is weekly, use the original date's day of week.
                // NOTE: fixes WeeklyCount1() and WeeklyUntil1() handling
                // If BYWEEKNO is specified and BYMONTHDAY/BYYEARDAY is not specified,
                // then let's add BYDAY to BYWEEKNO.
                // NOTE: fixes YearlyByWeekNoX() handling
                if (r.Frequency == FrequencyType.Weekly ||
                    (
                        r.ByWeekNo.Count > 0 &&
                        r.ByMonthDay.Count == 0 &&
                        r.ByYearDay.Count == 0
                    ))
                    r.ByDay.Add(new WeekDay(referenceDate.DayOfWeek));

                // If BYMONTHDAY is not specified,
                // default to the current day of month.
                // NOTE: fixes YearlyByMonth1() handling, added BYYEARDAY exclusion
                // to fix YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Weekly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonthDay.Count == 0)
                    r.ByMonthDay.Add(referenceDate.Day);

                // If BYMONTH is not specified, default to
                // the current month.
                // NOTE: fixes YearlyCountByYearDay1() handling
                if (r.Frequency > FrequencyType.Monthly &&
                    r.ByWeekNo.Count == 0 &&
                    r.ByYearDay.Count == 0 &&
                    r.ByMonth.Count == 0)
                    r.ByMonth.Add(referenceDate.Month);
            }

            return r;
        }
		public static RecurrencePatternBaseType CreateFromSchedulerRecurrencePattern(RecurrencePattern schedulerPattern)
		{
			if (schedulerPattern.Frequency == RecurrenceFrequency.Daily)
			{
				if (schedulerPattern.DaysOfWeekMask == RecurrenceDay.EveryDay)
				{
					DailyRecurrencePatternType pattern = new DailyRecurrencePatternType();
					pattern.Interval = schedulerPattern.Interval;
					return pattern;
				}
				else
				{
					WeeklyRecurrencePatternType pattern = new WeeklyRecurrencePatternType();
					pattern.Interval = 1; // Interval is ignored in this case.
					pattern.DaysOfWeek = DaysOfWeekStringConverter.ConvertFromRecurrenceDay(schedulerPattern.DaysOfWeekMask, false);
					return pattern;
				}
			}

			if (schedulerPattern.Frequency == RecurrenceFrequency.Weekly)
			{
				WeeklyRecurrencePatternType pattern = new WeeklyRecurrencePatternType();
				pattern.Interval = schedulerPattern.Interval;
				pattern.DaysOfWeek = DaysOfWeekStringConverter.ConvertFromRecurrenceDay(schedulerPattern.DaysOfWeekMask, false);
				return pattern;
			}

			if (schedulerPattern.Frequency == RecurrenceFrequency.Monthly)
			{
				if (schedulerPattern.DayOfMonth > 0)
				{
					AbsoluteMonthlyRecurrencePatternType pattern = new AbsoluteMonthlyRecurrencePatternType();
					pattern.Interval = schedulerPattern.Interval;
					pattern.DayOfMonth = schedulerPattern.DayOfMonth;
					return pattern;
				}
				else
				{
					RelativeMonthlyRecurrencePatternType pattern = new RelativeMonthlyRecurrencePatternType();
					pattern.Interval = schedulerPattern.Interval;
					pattern.DayOfWeekIndex = DayOfWeekIndexConverter.ConvertFromDayOrdinal(schedulerPattern.DayOrdinal);
					pattern.DaysOfWeek = DayOfWeekConverter.ConvertFromRecurrenceDay(schedulerPattern.DaysOfWeekMask);
					return pattern;
				}
			}

			if (schedulerPattern.Frequency == RecurrenceFrequency.Yearly)
			{
				if (schedulerPattern.DayOfMonth > 0)
				{
					AbsoluteYearlyRecurrencePatternType pattern = new AbsoluteYearlyRecurrencePatternType();
					pattern.Month = (MonthNamesType) Enum.Parse(typeof(MonthNamesType), schedulerPattern.Month.ToString());
					pattern.DayOfMonth = schedulerPattern.DayOfMonth;
					return pattern;
				}
				else
				{
					RelativeYearlyRecurrencePatternType pattern = new RelativeYearlyRecurrencePatternType();
					pattern.Month = (MonthNamesType) Enum.Parse(typeof(MonthNamesType), schedulerPattern.Month.ToString());
					pattern.DayOfWeekIndex = DayOfWeekIndexConverter.ConvertFromDayOrdinal(schedulerPattern.DayOrdinal);
					pattern.DaysOfWeek = DaysOfWeekStringConverter.ConvertFromRecurrenceDay(schedulerPattern.DaysOfWeekMask, true);
					return pattern;
				}
			}

			return null;
		}
        /// <summary>
        /// Sets up the controls in <see cref="RecurrencePatternYearlyView"/>.
        /// </summary>
        /// <param name="pattern">The recurrence pattern.</param>
        private void SetupYearlyRecurrence(RecurrencePattern pattern)
        {
            this.RepeatFrequencyYearly.Checked = true;

            this.RepeatEveryYearOnDate.Checked = pattern.DayOfMonth > 0;
            this.RepeatEveryYearOnGivenDay.Checked = !this.RepeatEveryYearOnDate.Checked;

            if (this.RepeatEveryYearOnDate.Checked)
            {
                this.YearlyRepeatMonthForDate.SelectedValue = pattern.Month.ToString();
                this.YearlyRepeatDateTextBox.Text = pattern.DayOfMonth.ToString(CultureInfo.CurrentCulture);
            }
            else
            {
                this.YearlyDayOrdinalDropDown.SelectedValue = pattern.DayOrdinal.ToString(CultureInfo.CurrentCulture);
                this.YearlyDayMaskDropDown.SelectedValue = pattern.DaysOfWeekMask.ToString();
                this.YearlyRepeatMonthForGivenDay.SelectedValue = pattern.Month.ToString();
            }
        }
Example #45
0
        public void RecurrencePattern1()
        {
            // NOTE: evaluators are not generally meant to be used directly like this.
            // However, this does make a good test to ensure they behave as they should.
            IRecurrencePattern pattern = new RecurrencePattern("FREQ=SECONDLY;INTERVAL=10");
            pattern.RestrictionType = RecurrenceRestrictionType.NoRestriction;

            CultureInfo us = CultureInfo.CreateSpecificCulture("en-US");

            iCalDateTime startDate = new iCalDateTime(DateTime.Parse("3/30/08 11:59:40 PM", us));
            iCalDateTime fromDate = new iCalDateTime(DateTime.Parse("3/30/08 11:59:40 PM", us));
            iCalDateTime toDate = new iCalDateTime(DateTime.Parse("3/31/08 12:00:11 AM", us));

            IEvaluator evaluator = pattern.GetService(typeof(IEvaluator)) as IEvaluator;
            Assert.IsNotNull(evaluator);

            IList<IPeriod> occurrences = evaluator.Evaluate(
                startDate, 
                DateUtil.SimpleDateTimeToMatch(fromDate, startDate), 
                DateUtil.SimpleDateTimeToMatch(toDate, startDate),
                false);
            Assert.AreEqual(4, occurrences.Count);
            Assert.AreEqual(new iCalDateTime(DateTime.Parse("03/30/08 11:59:40 PM", us)), occurrences[0].StartTime);
            Assert.AreEqual(new iCalDateTime(DateTime.Parse("03/30/08 11:59:50 PM", us)), occurrences[1].StartTime);
            Assert.AreEqual(new iCalDateTime(DateTime.Parse("03/31/08 12:00:00 AM", us)), occurrences[2].StartTime);
            Assert.AreEqual(new iCalDateTime(DateTime.Parse("03/31/08 12:00:10 AM", us)), occurrences[3].StartTime);
        }
Example #46
0
        public void Test4()
        {
            IRecurrencePattern rpattern = new RecurrencePattern();
            rpattern.ByDay.Add(new WeekDay(DayOfWeek.Saturday));
            rpattern.ByDay.Add(new WeekDay(DayOfWeek.Sunday));

            rpattern.Frequency = FrequencyType.Weekly;

            IDateTime evtStart = new iCalDateTime(2006, 12, 1);
            IDateTime evtEnd = new iCalDateTime(2007, 1, 1);

            IEvaluator evaluator = rpattern.GetService(typeof(IEvaluator)) as IEvaluator;
            Assert.IsNotNull(evaluator);

            // Add the exception dates
            IList<IPeriod> periods = evaluator.Evaluate(
                evtStart,
                DateUtil.GetSimpleDateTimeData(evtStart), 
                DateUtil.SimpleDateTimeToMatch(evtEnd, evtStart),
                false);
            Assert.AreEqual(10, periods.Count);
            Assert.AreEqual(2, periods[0].StartTime.Day);
            Assert.AreEqual(3, periods[1].StartTime.Day);
            Assert.AreEqual(9, periods[2].StartTime.Day);
            Assert.AreEqual(10, periods[3].StartTime.Day);
            Assert.AreEqual(16, periods[4].StartTime.Day);
            Assert.AreEqual(17, periods[5].StartTime.Day);
            Assert.AreEqual(23, periods[6].StartTime.Day);
            Assert.AreEqual(24, periods[7].StartTime.Day);
            Assert.AreEqual(30, periods[8].StartTime.Day);
            Assert.AreEqual(31, periods[9].StartTime.Day);
        }
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Yearly;
			pattern.DayOrdinal = DayOfWeekIndexConverter.ConvertToDayOrdinal(DayOfWeekIndex);
			pattern.DaysOfWeekMask = DaysOfWeekStringConverter.ConvertToRecurrenceDay(DaysOfWeek);
			pattern.Month = (RecurrenceMonth) Enum.Parse(typeof(RecurrenceMonth), Month.ToString());
			return pattern;
		}
Example #48
0
        public void Test2()
        {
            IICalendar iCal = new iCalendar();
            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Event summary";
            evt.Start = new iCalDateTime(DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc));

            IRecurrencePattern recur = new RecurrencePattern();
            recur.Frequency = FrequencyType.Daily;
            recur.Count = 3;
            recur.ByDay.Add(new WeekDay(DayOfWeek.Monday));
            recur.ByDay.Add(new WeekDay(DayOfWeek.Wednesday));
            recur.ByDay.Add(new WeekDay(DayOfWeek.Friday));
            evt.RecurrenceRules.Add(recur);

            RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
            Assert.IsTrue(string.Compare(serializer.SerializeToString(recur), "FREQ=DAILY;COUNT=3;BYDAY=MO,WE,FR") == 0,
                "Serialized recurrence string is incorrect");
        }
Example #49
0
        public void Test1()
        {
            IICalendar iCal = new iCalendar();
            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Event summary";
            evt.Start = new iCalDateTime(DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc));

            IRecurrencePattern recur = new RecurrencePattern();
            evt.RecurrenceRules.Add(recur);

            try
            {
                IList<Occurrence> occurrences = evt.GetOccurrences(DateTime.Today.AddDays(1), DateTime.Today.AddDays(2));
                Assert.Fail("An exception should be thrown when evaluating a recurrence with no specified FREQUENCY");
            }
            catch { }
        }
Example #50
0
        public void RecurrencePattern2()
        {
            // NOTE: evaluators are generally not meant to be used directly like this.
            // However, this does make a good test to ensure they behave as they should.
            RecurrencePattern pattern = new RecurrencePattern("FREQ=MINUTELY;INTERVAL=1");

            CultureInfo us = CultureInfo.CreateSpecificCulture("en-US");

            iCalDateTime startDate = new iCalDateTime(DateTime.Parse("3/31/2008 12:00:10 AM", us));
            iCalDateTime fromDate = new iCalDateTime(DateTime.Parse("4/1/2008 10:08:10 AM", us));
            iCalDateTime toDate = new iCalDateTime(DateTime.Parse("4/1/2008 10:43:23 AM", us));

            IEvaluator evaluator = pattern.GetService(typeof(IEvaluator)) as IEvaluator;
            Assert.IsNotNull(evaluator);

            IList<IPeriod> occurrences = evaluator.Evaluate(
                startDate, 
                DateUtil.SimpleDateTimeToMatch(fromDate, startDate), 
                DateUtil.SimpleDateTimeToMatch(toDate, startDate),
                false);
            Assert.AreNotEqual(0, occurrences.Count);
        }
        public void CopyFrom(IRecurrenceRule other)
        {
            if (this.GetType().FullName != other.GetType().FullName)
            {
                throw new ArgumentException("Invalid type");
            }

            if (other is SqlRecurrenceRule)
            {
                this.MasterAppointment = (other as SqlRecurrenceRule).MasterAppointment;
            }

            this.Pattern = other.Pattern.Copy();
            this.Exceptions.Clear();
            foreach (var exception in other.Exceptions)
            {
                this.Exceptions.Add(exception.Copy() as SqlExceptionOccurrence);
            }
        }
 /// <summary>
 /// Sets up the controls in <see cref="RecurrencePatternDailyView"/>.
 /// </summary>
 /// <param name="pattern">The recurrence pattern.</param>
 private void SetupDailyRecurrence(RecurrencePattern pattern)
 {
     this.RepeatFrequencyDaily.Checked = true;
     this.RepeatEveryWeekday.Checked = pattern.DaysOfWeekMask == RecurrenceDay.WeekDays;
     this.RepeatEveryNthDay.Checked = !this.RepeatEveryWeekday.Checked;
     if (this.RepeatEveryNthDay.Checked)
     {
         this.DailyRepeatIntervalTextBox.Text = pattern.Interval.ToString(CultureInfo.CurrentCulture);
     }
 }
Example #53
0
 /// <summary>
 /// Counts to until replace. For  recurrence pattern
 /// </summary>
 /// <param name="dtStart">The dt start.</param>
 /// <param name="until">The until.</param>
 /// <param name="rpattern">The rpattern.</param>
 private static void CountToUntilReplace(iCalDateTime dtStart, iCalDateTime until, RecurrencePattern pattern)
 {
     //COUNT is specified
     if (pattern.Count > 0)
     {
         List<iCalDateTime> occurs = pattern.Evaluate(dtStart, dtStart, until);
         if (occurs.Count != 0 && occurs[occurs.Count - 1] >= until)
         {
             //Remove COUNT
             pattern.Count = int.MinValue;
             pattern.Until = until;
         }
     }
     else
     {
         pattern.Until = until;
     }
 }
Example #54
0
        public void Bug1821721()
        {
            iCalendar iCal = new iCalendar();

            iCalTimeZone tz = iCal.Create<iCalTimeZone>();

            tz.TZID = "US-Eastern";
            tz.LastModified = new iCalDateTime(new DateTime(1987, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            ITimeZoneInfo standard = new iCalTimeZoneInfo(Components.STANDARD);
            standard.Start = new iCalDateTime(new DateTime(1967, 10, 29, 2, 0, 0, DateTimeKind.Utc));
            standard.RecurrenceRules.Add(new RecurrencePattern("FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10"));
            standard.OffsetFrom = new UTCOffset("-0400");
            standard.OffsetTo = new UTCOffset("-0500");
            standard.TimeZoneName = "EST";
            tz.AddChild(standard);

            ITimeZoneInfo daylight = new iCalTimeZoneInfo(Components.DAYLIGHT);
            daylight.Start = new iCalDateTime(new DateTime(1987, 4, 5, 2, 0, 0, DateTimeKind.Utc));
            daylight.RecurrenceRules.Add(new RecurrencePattern("FREQ=YEARLY;BYDAY=1SU;BYMONTH=4"));
            daylight.OffsetFrom = new UTCOffset("-0500");
            daylight.OffsetTo = new UTCOffset("-0400");
            daylight.TimeZoneName = "EDT";            
            tz.AddChild(daylight);

            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Test event";
            evt.Start = new iCalDateTime(2007, 1, 24, 8, 0, 0, tzid);
            evt.Duration = TimeSpan.FromHours(1);
            evt.End = new iCalDateTime(2007, 1, 24, 9, 0, 0, tzid);
            IRecurrencePattern recur = new RecurrencePattern("FREQ=MONTHLY;INTERVAL=2;BYDAY=4WE");
            evt.RecurrenceRules.Add(recur);

            EventOccurrenceTest(
                iCal,
                new iCalDateTime(2007, 1, 24),
                new iCalDateTime(2007, 12, 31),
                new iCalDateTime[]
                {                
                    new iCalDateTime(2007, 1, 24, 8, 0, 0, tzid),
                    new iCalDateTime(2007, 3, 28, 8, 0, 0, tzid),
                    new iCalDateTime(2007, 5, 23, 8, 0, 0, tzid),
                    new iCalDateTime(2007, 7, 25, 8, 0, 0, tzid),
                    new iCalDateTime(2007, 9, 26, 8, 0, 0, tzid),
                    new iCalDateTime(2007, 11, 28, 8, 0, 0, tzid)
                },
                null
            );
        }
        /// <summary>
        /// Sets the pattern.
        /// </summary>
        /// <param name="pattern">The pattern.</param>
        private void SetRecurrencePattern(RecurrencePattern pattern)
        {
            this.InitializeRecurrenceFrequency();

            switch (pattern.Frequency)
            {
                case RecurrenceFrequency.Weekly:
                    this.SetupWeeklyRecurrence(pattern);
                    break;
                case RecurrenceFrequency.Monthly:
                    this.SetupMonthlyRecurrence(pattern);
                    break;
                case RecurrenceFrequency.Yearly:
                    this.SetupYearlyRecurrence(pattern);
                    break;
                    ////case RecurrenceFrequency.Daily:
                default:
                    this.SetupDailyRecurrence(pattern);
                    break;
            }
        }
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Yearly;
			pattern.DayOfMonth = DayOfMonth;
			pattern.Month = (RecurrenceMonth) Enum.Parse(typeof(RecurrenceMonth), Month.ToString());
			return pattern;
		}
        /// <summary>
        /// Sets up the controls in <see cref="RecurrencePatternWeeklyView"/>.
        /// </summary>
        /// <param name="pattern">The recurrence pattern.</param>
        private void SetupWeeklyRecurrence(RecurrencePattern pattern)
        {
            this.RepeatFrequencyWeekly.Checked = true;

            this.WeeklyRepeatIntervalTextBox.Text = pattern.Interval.ToString(CultureInfo.CurrentCulture);
            this.WeeklyWeekdayMonday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Monday) != 0;
            this.WeeklyWeekdayTuesday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Tuesday) != 0;
            this.WeeklyWeekdayWednesday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Wednesday) != 0;
            this.WeeklyWeekdayThursday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Thursday) != 0;
            this.WeeklyWeekdayFriday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Friday) != 0;
            this.WeeklyWeekdaySaturday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Saturday) != 0;
            this.WeeklyWeekdaySunday.Checked = (pattern.DaysOfWeekMask & RecurrenceDay.Sunday) != 0;
        }
Example #58
0
        /// <summary>
        /// Gets the calendar content from controls.
        /// </summary>
        /// <returns></returns>
        internal string GetCalendarContentFromControls()
        {
            EnsureChildControls();

            if ( _dpStartDateTime.SelectedDateTimeIsBlank )
            {
                return iCalendarContentEmptyEvent;
            }

            DDay.iCal.Event calendarEvent = new DDay.iCal.Event();
            calendarEvent.DTStart = new DDay.iCal.iCalDateTime( _dpStartDateTime.SelectedDateTime.Value );
            calendarEvent.DTStart.HasTime = true;

            int durationHours = TextBoxToPositiveInteger( _tbDurationHours, 0 );
            int durationMins = TextBoxToPositiveInteger( _tbDurationMinutes, 0 );

            if ( (durationHours == 0 && durationMins == 0) || this.ShowDuration == false )
            {
                // make a one second duration since a zero duration won't be included in occurrences
                calendarEvent.Duration = new TimeSpan( 0, 0, 1);
            }
            else
            {
                calendarEvent.Duration = new TimeSpan( durationHours, durationMins, 0 );
            }

            if ( _radRecurring.Checked )
            {
                if ( _radSpecificDates.Checked )
                {
                    #region specific dates
                    PeriodList recurrenceDates = new PeriodList();
                    List<string> dateStringList = _hfSpecificDateListValues.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                    foreach ( var dateString in dateStringList )
                    {
                        DateTime newDate;
                        if ( DateTime.TryParse( dateString, out newDate ) )
                        {
                            recurrenceDates.Add( new iCalDateTime( newDate.Date ) );
                        }
                    }

                    calendarEvent.RecurrenceDates.Add( recurrenceDates );
                    #endregion
                }
                else
                {
                    if ( _radDaily.Checked )
                    {
                        #region daily
                        if ( _radDailyEveryXDays.Checked )
                        {
                            RecurrencePattern rruleDaily = new RecurrencePattern( FrequencyType.Daily );

                            rruleDaily.Interval = TextBoxToPositiveInteger( _tbDailyEveryXDays );
                            calendarEvent.RecurrenceRules.Add( rruleDaily );
                        }
                        else
                        {
                            // NOTE:  Daily Every Weekday/Weekend Day is actually Weekly on Day(s)OfWeek in iCal
                            RecurrencePattern rruleWeekly = new RecurrencePattern( FrequencyType.Weekly );
                            if ( _radDailyEveryWeekday.Checked )
                            {
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Monday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Tuesday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Wednesday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Thursday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Friday ) );
                            }
                            else if ( _radDailyEveryWeekendDay.Checked )
                            {
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Saturday ) );
                                rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Sunday ) );
                            }

                            calendarEvent.RecurrenceRules.Add( rruleWeekly );
                        }
                        #endregion
                    }
                    else if ( _radWeekly.Checked )
                    {
                        #region weekly
                        RecurrencePattern rruleWeekly = new RecurrencePattern( FrequencyType.Weekly );
                        rruleWeekly.Interval = TextBoxToPositiveInteger( _tbWeeklyEveryX );

                        if ( _cbWeeklySunday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Sunday ) );
                        }

                        if ( _cbWeeklyMonday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Monday ) );
                        }

                        if ( _cbWeeklyTuesday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Tuesday ) );
                        }

                        if ( _cbWeeklyWednesday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Wednesday ) );
                        }

                        if ( _cbWeeklyThursday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Thursday ) );
                        }

                        if ( _cbWeeklyFriday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Friday ) );
                        }

                        if ( _cbWeeklySaturday.Checked )
                        {
                            rruleWeekly.ByDay.Add( new WeekDay( DayOfWeek.Saturday ) );
                        }

                        calendarEvent.RecurrenceRules.Add( rruleWeekly );
                        #endregion
                    }
                    else if ( _radMonthly.Checked )
                    {
                        #region monthly
                        RecurrencePattern rruleMonthly = new RecurrencePattern( FrequencyType.Monthly );
                        if ( _radMonthlyDayX.Checked )
                        {
                            rruleMonthly.ByMonthDay.Add( TextBoxToPositiveInteger( _tbMonthlyDayX ) );
                            rruleMonthly.Interval = TextBoxToPositiveInteger( _tbMonthlyXMonths );
                        }
                        else if ( _radMonthlyNth.Checked )
                        {
                            WeekDay monthWeekDay = new WeekDay();
                            monthWeekDay.Offset = _ddlMonthlyNth.SelectedValue.AsIntegerOrNull() ?? 1;
                            monthWeekDay.DayOfWeek = (DayOfWeek)( _ddlMonthlyDayName.SelectedValue.AsIntegerOrNull() ?? 1 );
                            rruleMonthly.ByDay.Add( monthWeekDay );
                        }

                        calendarEvent.RecurrenceRules.Add( rruleMonthly );
                        #endregion
                    }
                }
            }

            if ( calendarEvent.RecurrenceRules.Count > 0 )
            {
                IRecurrencePattern rrule = calendarEvent.RecurrenceRules[0];

                // Continue Until
                if ( _radEndByNone.Checked )
                {
                    // intentionally blank
                }
                else if ( _radEndByDate.Checked )
                {
                    rrule.Until = _dpEndBy.SelectedDate.HasValue ? _dpEndBy.SelectedDate.Value : DateTime.MaxValue;
                }
                else if ( _radEndByOccurrenceCount.Checked )
                {
                    rrule.Count = TextBoxToPositiveInteger( _tbEndByOccurrenceCount, 0 );
                }
            }

            // Exclusions
            List<string> dateRangeStringList = _hfExclusionDateRangeListValues.Value.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();

            PeriodList exceptionDates = new PeriodList();
            foreach ( string dateRangeString in dateRangeStringList )
            {
                var dateRangeParts = dateRangeString.Split( new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries );
                if ( dateRangeParts.Count() == 2 )
                {
                    DateTime beginDate;
                    DateTime endDate;

                    if ( DateTime.TryParse( dateRangeParts[0], out beginDate ) )
                    {
                        if ( DateTime.TryParse( dateRangeParts[1], out endDate ) )
                        {
                            DateTime dateToAdd = beginDate.Date;
                            while ( dateToAdd <= endDate )
                            {
                                Period periodToAdd = new Period( new iCalDateTime( dateToAdd ) );
                                if ( !exceptionDates.Contains( periodToAdd ) )
                                {
                                    exceptionDates.Add( periodToAdd );
                                }

                                dateToAdd = dateToAdd.AddDays( 1 );
                            }
                        }
                    }
                }
            }

            if ( exceptionDates.Count > 0 )
            {
                calendarEvent.ExceptionDates.Add( exceptionDates );
            }

            DDay.iCal.iCalendar calendar = new iCalendar();
            calendar.Events.Add( calendarEvent );

            iCalendarSerializer s = new iCalendarSerializer( calendar );

            return s.SerializeToString( calendar );
        }
		public override RecurrencePattern ConvertToRecurrencePattern()
		{
			RecurrencePattern pattern = new RecurrencePattern();
			pattern.Frequency = RecurrenceFrequency.Monthly;
			pattern.DayOrdinal = DayOfWeekIndexConverter.ConvertToDayOrdinal(DayOfWeekIndex);
			pattern.DaysOfWeekMask = DayOfWeekConverter.ConvertToRecurrenceDay(DaysOfWeek);
			pattern.Interval = Interval;
			return pattern;
		}
        /// <summary>
        /// Serializes the specified get recurrence pattern.
        /// </summary>
        /// <param name="recurrencePattern">The recurrence pattern.</param>
        /// <param name="appointmentStart">The appointment start.</param>
        /// <param name="allday">if set to <c>true</c> [allday].</param>
        /// <returns>The serialized Recurrence.</returns>
        public static string Serialize(RecurrencePattern recurrencePattern, DateTime appointmentStart, bool allday)
        {
            var startTime = appointmentStart.Date.Add(recurrencePattern.StartTime - recurrencePattern.StartTime.Date);
            var endTime = appointmentStart.Date.Add(recurrencePattern.EndTime - recurrencePattern.EndTime.Date);
            var values = allday
            ? new List<string>
            {
                string.Format("DTSTART;VALUE=DATE:{0}", startTime.ToString("yyyyMMdd", CultureInfo.InvariantCulture)),
                string.Format("DTEND;VALUE=DATE:{0}", endTime.ToString("yyyyMMdd", CultureInfo.InvariantCulture))
            }
            : new List<string>
            {
                string.Format("DTSTART:{0}", startTime.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture)),
                string.Format("DTEND:{0}", endTime.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture))
            };

            var ruleValues = new List<string>
            {
                string.Format("FREQ={0}", recurrencePattern.RecurrenceType.GetRecurrenceString())
            };

            if (!recurrencePattern.NoEndDate)
            {
                ruleValues.Add(string.Format("UNTIL={0}", recurrencePattern.PatternEndDate.ToUniversalTime().ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture)));
            }

            if ((recurrencePattern.RecurrenceType == OlRecurrenceType.olRecursYearly && recurrencePattern.Interval / 12 > 1) ||
                (recurrencePattern.RecurrenceType != OlRecurrenceType.olRecursYearly && recurrencePattern.Interval > 1))
            {
                ruleValues.Add(string.Format("INTERVAL={0}", recurrencePattern.Interval));
            }

            if (recurrencePattern.NoEndDate && recurrencePattern.Occurrences > 0)
            {
                ruleValues.Add(string.Format("COUNT={0}", recurrencePattern.Occurrences));
            }

            switch (recurrencePattern.RecurrenceType)
            {
                case OlRecurrenceType.olRecursWeekly:
                    ruleValues.Add(string.Format("BYDAY={0}", recurrencePattern.DayOfWeekMask.GetDayOfWeek()));
                    break;
                case OlRecurrenceType.olRecursDaily:
                case OlRecurrenceType.olRecursMonthly:
                case OlRecurrenceType.olRecursYearly:
                    if (recurrencePattern.MonthOfYear > 0)
                        ruleValues.Add(string.Format("BYMONTH={0}", recurrencePattern.MonthOfYear));
                    if (recurrencePattern.DayOfMonth > 0)
                        ruleValues.Add(string.Format("BYMONTHDAY={0}", recurrencePattern.DayOfMonth));
                    break;
            }

            values.Add(string.Format("RRULE:{0}", string.Join(";", ruleValues)));
            return string.Join("\r\n", values);
        }