Example #1
0
        public void ParseFromStringTest()
        {
            //tets
            var r1 = RecurrenceRule.Parse("FREQ=WEEKLY;INTERVAL=2;UNTIL=19971224T000000Z;WKST=SU");

            Assert.AreEqual(new DateTime(1997, 12, 24, 0, 0, 0), r1.Until);
        }
        public void Weekly_Until_1997_12_24()
        {
            var rrule       = RecurrenceRule.Parse("FREQ=WEEKLY;UNTIL=19971224T000000Z");
            var startDate   = new DateTime(1997, 09, 02, 09, 00, 00);
            var occurrences = rrule.GetNextOccurrences(startDate);

            AssertOccurrences(occurrences,
                              new DateTime(1997, 09, 02, 09, 00, 00),
                              new DateTime(1997, 09, 09, 09, 00, 00),
                              new DateTime(1997, 09, 16, 09, 00, 00),
                              new DateTime(1997, 09, 23, 09, 00, 00),
                              new DateTime(1997, 09, 30, 09, 00, 00),
                              new DateTime(1997, 10, 07, 09, 00, 00),
                              new DateTime(1997, 10, 14, 09, 00, 00),
                              new DateTime(1997, 10, 21, 09, 00, 00),
                              new DateTime(1997, 10, 28, 09, 00, 00),
                              new DateTime(1997, 11, 04, 09, 00, 00),
                              new DateTime(1997, 11, 11, 09, 00, 00),
                              new DateTime(1997, 11, 18, 09, 00, 00),
                              new DateTime(1997, 11, 25, 09, 00, 00),
                              new DateTime(1997, 12, 02, 09, 00, 00),
                              new DateTime(1997, 12, 09, 09, 00, 00),
                              new DateTime(1997, 12, 16, 09, 00, 00),
                              new DateTime(1997, 12, 23, 09, 00, 00));
        }
 protected void DayPilotCalendar1_BeforeEventRecurrence(DayPilot.Web.Ui.Events.Calendar.BeforeEventRecurrenceEventArgs ea)
 {
     if (ea.Value == "5")
     {
         ea.Rule = RecurrenceRule.FromDateTime(ea.Value, ea.Start).Weekly(new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday }).Times(5);
     }
 }
        private static void TestGetHumanText(string rruleText, string cultureInfo, string expectedText)
        {
            var rrule = RecurrenceRule.Parse(rruleText);
            var text  = rrule.GetHumanText(new CultureInfo(cultureInfo));

            Assert.Equal(expectedText, text);
        }
        public void Monthly_EveryTuesdayEveryOtherMonth()
        {
            var rrule       = RecurrenceRule.Parse("FREQ=MONTHLY;INTERVAL=2;BYDAY=TU");
            var startDate   = new DateTime(1997, 09, 02, 09, 00, 00);
            var occurrences = rrule.GetNextOccurrences(startDate);

            AssertOccurrencesStartWith(occurrences,
                                       new DateTime(1997, 09, 02, 09, 00, 00),
                                       new DateTime(1997, 09, 09, 09, 00, 00),
                                       new DateTime(1997, 09, 16, 09, 00, 00),
                                       new DateTime(1997, 09, 23, 09, 00, 00),
                                       new DateTime(1997, 09, 30, 09, 00, 00),
                                       new DateTime(1997, 11, 04, 09, 00, 00),
                                       new DateTime(1997, 11, 11, 09, 00, 00),
                                       new DateTime(1997, 11, 18, 09, 00, 00),
                                       new DateTime(1997, 11, 25, 09, 00, 00),
                                       new DateTime(1998, 01, 06, 09, 00, 00),
                                       new DateTime(1998, 01, 13, 09, 00, 00),
                                       new DateTime(1998, 01, 20, 09, 00, 00),
                                       new DateTime(1998, 01, 27, 09, 00, 00),
                                       new DateTime(1998, 03, 03, 09, 00, 00),
                                       new DateTime(1998, 03, 10, 09, 00, 00),
                                       new DateTime(1998, 03, 17, 09, 00, 00),
                                       new DateTime(1998, 03, 24, 09, 00, 00),
                                       new DateTime(1998, 03, 31, 09, 00, 00));
        }
    protected void DayPilotCalendar1_EventResize(object sender, EventResizeEventArgs e)
    {
        #region Simulation of database update

        DataRow dr = table.Rows.Find(e.Id);

        if (e.Recurrent && !e.RecurrentException)
        {
            DataRow master = table.Rows.Find(e.RecurrentMasterId);

            dr               = table.NewRow();
            dr["id"]         = Guid.NewGuid().ToString();
            dr["recurrence"] = RecurrenceRule.EncodeExceptionModified(e.RecurrentMasterId, e.OldStart);
            dr["start"]      = e.NewStart;
            dr["end"]        = e.NewEnd;
            dr["name"]       = master["name"];
            table.Rows.Add(dr);
            table.AcceptChanges();
        }
        else if (dr != null)
        {
            dr["start"] = e.NewStart;
            dr["end"]   = e.NewEnd;
            table.AcceptChanges();
        }

        #endregion

        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("Event resized");
    }
    protected void DayPilotCalendar1_EventDelete(object sender, EventDeleteEventArgs e)
    {
        #region Simulation of database update

        DataRow dr = table.Rows.Find(e.Id);

        if (e.Recurrent && !e.RecurrentException)
        {
            dr               = table.NewRow();
            dr["id"]         = Guid.NewGuid().ToString();
            dr["start"]      = e.Start;
            dr["end"]        = e.End;
            dr["recurrence"] = RecurrenceRule.EncodeExceptionDeleted(e.RecurrentMasterId, e.Start);
            table.Rows.Add(dr);
            table.AcceptChanges();
        }
        else if (e.Recurrent && e.RecurrentException && dr != null)
        {
            table.Rows.Remove(dr);
            table.AcceptChanges();
        }
        else if (dr != null)
        {
            table.Rows.Remove(dr);
            table.AcceptChanges();
        }

        #endregion

        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("Event deleted.");
    }
Example #8
0
        /// <summary>
        /// Updates the specified appointment.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <param name="appointmentToUpdate">The appointment to update.</param>
        public override void Update(RadScheduler owner, Appointment appointmentToUpdate)
        {
            if (owner.ProviderContext is RemoveRecurrenceExceptionsContext)
            {
                RemoveRecurrenceExceptions(appointmentToUpdate);
                return;
            }

            if (owner.ProviderContext is UpdateAppointmentContext)
            {
                // When removing recurrences through the UI,
                // one Update operation is used to both update the appointment
                // and remove the recurrence exceptions.
                RecurrenceRule updatedRule;
                RecurrenceRule.TryParse(appointmentToUpdate.RecurrenceRule, out updatedRule);

                if (updatedRule != null && updatedRule.Exceptions.Count == 0)
                {
                    RemoveRecurrenceExceptions(appointmentToUpdate);
                }
            }

            CreateRecurrenceExceptionContext createExceptionContext = owner.ProviderContext as CreateRecurrenceExceptionContext;

            if (createExceptionContext == null)
            {
                // We are not creating a recurrence exceptions - synchronize deleted occurrences.
                SynchronizeDeletedOccurrences(appointmentToUpdate);
            }

            ItemChangeType[] changes = new ItemChangeType[] { GetAppointmentChanges(appointmentToUpdate) };
            UpdateCalendarItem(changes);
        }
Example #9
0
        /// <summary>
        /// Gets the recurrence summary for the recurrence pattern of the given <paramref name="recurrenceRule"/>.
        /// </summary>
        /// <param name="recurrenceRule">The recurrence rule to summarize.</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>
        public static string GetRecurrenceSummary(RecurrenceRule recurrenceRule, string resourceFile)
        {
            string recurrenceSummary = string.Empty;

            if (recurrenceRule != null)
            {
                switch (recurrenceRule.Pattern.Frequency)
                {
                case RecurrenceFrequency.Weekly:
                    recurrenceSummary = GetWeeklyRecurrenceSummary(recurrenceRule.Pattern, resourceFile);
                    break;

                case RecurrenceFrequency.Monthly:
                    recurrenceSummary = GetMonthlyRecurrenceSummary(recurrenceRule.Pattern, resourceFile);
                    break;

                case RecurrenceFrequency.Yearly:
                    recurrenceSummary = GetYearlyRecurrenceSummary(recurrenceRule.Pattern, resourceFile);
                    break;

                ////case RecurrenceFrequency.Daily:
                default:
                    recurrenceSummary = GetDailyRecurrenceSummary(recurrenceRule.Pattern, resourceFile);
                    break;
                }
            }

            return(recurrenceSummary);
        }
        public void TestMultiplier()
        {
            RecurrenceRule rule = "42DW";

            Assert.Equal(42, rule.Multiplier);
            Assert.Equal(TimeInterval.DayOfWeek, rule.Frequency);
        }
Example #11
0
            protected override void OnEventMenuClick(EventMenuClickArgs e)
            {
                switch (e.Command)
                {
                case "Delete":
                    if (e.Recurrent == false)
                    {
                        new EventManager().EventDelete(e.Id);
                        UpdateWithMessage("Wydarzenie usunięte.");
                    }
                    else
                    {
                        string prefix = RecurrenceRule.Prefix(e.RecurrentMasterId);

                        new EventManager().EventDeleteWholeRecurrence(prefix);
                        UpdateWithMessage("Seria wydarzeń usunięta.");
                    }
                    Update();
                    break;

                case "Edit":
                    Redirect("/Appointments/Edit/" + e.Text);
                    Update();
                    break;
                }
            }
Example #12
0
        internal void EventCreate(DateTime start, DateTime end, string text, string resource, string recurrenceJson)
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["daypilot"].ConnectionString))
            {
                con.Open();

                SqlCommand cmd = new SqlCommand("INSERT INTO [event] (eventstart, eventend, name, resource) VALUES (@start, @end, @name, @resource); ", con);  // SELECT SCOPE_IDENTITY();
                cmd.Parameters.AddWithValue("start", start);
                cmd.Parameters.AddWithValue("end", end);
                cmd.Parameters.AddWithValue("name", text);
                cmd.Parameters.AddWithValue("resource", resource);
                //cmd.Parameters.AddWithValue("recurrence", recurrence);
                cmd.ExecuteScalar();

                cmd = new SqlCommand("select @@identity;", con);
                int id = Convert.ToInt32(cmd.ExecuteScalar());

                RecurrenceRule rule             = RecurrenceRule.FromJson(id.ToString(), start, recurrenceJson);
                string         recurrenceString = rule.Encode();
                if (!String.IsNullOrEmpty(recurrenceString))
                {
                    cmd = new SqlCommand("update [event] set [recurrence] = @recurrence where [id] = @id", con);
                    cmd.Parameters.AddWithValue("recurrence", rule.Encode());
                    cmd.Parameters.AddWithValue("id", id);
                    cmd.ExecuteNonQuery();
                }
            }
        }
Example #13
0
        private static bool CheckRecurrenceRule(RecurrenceRule rule, DateTime time)
        {
            switch (rule)
            {
            case RecurrenceRuleDayOfWeek dayOfWeekRule:
                return(dayOfWeekRule.WeekDays.Contains(time.DayOfWeek));

            case RecurrenceRuleDayOfMonth dayOfMonthRule:
                return(dayOfMonthRule.WeekDays
                       .SelectMany(spec => AddDates(time.Year, time.Month, spec))
                       .Contains(time.Date));

            case RecurrenceRuleTime timesRule:
                if (timesRule.Frequency == TimeInterval.DayOfMonth)
                {
                    return(CheckDayOfMonth(time, timesRule.Times));
                }

                if (timesRule.Frequency == TimeInterval.DayOfYear)
                {
                    return(CheckDayOfYear(time, timesRule.Times));
                }

                if (timesRule.Frequency == TimeInterval.Month)
                {
                    return(CheckMonthMultiplier(time, timesRule.Multiplier) &&
                           timesRule.Times.Contains(time.Month));
                }

                if (timesRule.Frequency == TimeInterval.Year)
                {
                    return(timesRule.Times.Contains(time.Year));
                }

                if (timesRule.Frequency == TimeInterval.Hour)
                {
                    return(timesRule.Times.Contains(time.Hour));
                }

                if (timesRule.Frequency == TimeInterval.Minute)
                {
                    return(timesRule.Times.Contains(time.Minute));
                }

                if (timesRule.Frequency == TimeInterval.Second)
                {
                    return(timesRule.Times.Contains(time.Second));
                }

                if (timesRule.Frequency == TimeInterval.WeekOfYear)
                {
                    return(timesRule.Times.Contains(time.WeekOfYear()));
                }

                return(false);

            default:
                return(true);
            }
        }
Example #14
0
 private void UpdateNextOccurences()
 {
     if (RecurrenceRule.TryParse(TbxRecurrenceRule.Text, out var rule, out var error))
     {
         var occurences = rule.GetNextOccurrences(DateTime.Now).Select(date => date.ToString("F", CultureInfo.CurrentCulture)).Take(50).ToList();
         NextOccurences.ItemsSource = occurences;
     }
Example #15
0
 /// <summary>
 /// Sets the recurrence rule for this control instance.
 /// </summary>
 /// <param name="rule">The recurrence rule with which to populate this control.</param>
 internal void SetRecurrenceRule(RecurrenceRule rule)
 {
     if (rule != null)
     {
         this.SetRecurrencePattern(rule.Pattern);
         this.SetRecurrenceRange(rule.Range);
     }
 }
        public void Yearly_Text01()
        {
            var rrule = RecurrenceRule.Parse("FREQ=YEARLY;UNTIL=20000131T140000Z;BYYEARDAY=1,-1;BYMONTH=1;BYDAY=TU,WE;BYMONTHDAY=2");

            var text = rrule.Text;

            Assert.Equal("FREQ=YEARLY;UNTIL=20000131T140000Z;BYMONTH=1;BYYEARDAY=1,-1;BYMONTHDAY=2;BYDAY=TU,WE", text);
        }
        public void Weekly_Text01()
        {
            var rrule = RecurrenceRule.Parse("FREQ=WEEKLY;UNTIL=20000131T140000Z;BYMONTH=1;BYDAY=TU,WE");

            var text = rrule.Text;

            Assert.Equal("FREQ=WEEKLY;UNTIL=20000131T140000Z;BYMONTH=1;BYDAY=TU,WE", text);
        }
        public void Daily_Text02()
        {
            var rrule = RecurrenceRule.Parse("FREQ=DAILY;UNTIL=20000131T140000Z;INTERVAL=2");

            var text = rrule.Text;

            Assert.Equal("FREQ=DAILY;INTERVAL=2;UNTIL=20000131T140000Z", text);
        }
        public void Daily_Text01()
        {
            var rrule = RecurrenceRule.Parse("FREQ=DAILY;UNTIL=20000131T140000Z;BYMONTH=1");

            var text = rrule.Text;

            Assert.Equal("FREQ=DAILY;UNTIL=20000131T140000Z;BYMONTH=1", text);
        }
Example #20
0
        public void Monthly_Text01()
        {
            var rrule = RecurrenceRule.Parse("FREQ=MONTHLY;UNTIL=20000131T140000Z;BYMONTH=1;BYDAY=TU,WE;BYMONTHDAY=2");

            var text = rrule.Text;

            Assert.AreEqual("FREQ=MONTHLY;UNTIL=20000131T140000Z;BYMONTH=1;BYMONTHDAY=2;BYDAY=TU,WE", text);
        }
Example #21
0
    public ActionResult Edit(string id)
    {
        var mode = Mode(id);

        ViewData["Mode"] = mode;

        var masterId = Request.QueryString["master"];

        var            row    = new EventManager().Get(id) ?? new EventManager.Event();
        var            master = new EventManager().Get(masterId) ?? new EventManager.Event();
        var            e      = new EventManager.Event();
        RecurrenceRule _rule;

        switch (mode)
        {
        case EventMode.Master:
            _rule      = RecurrenceRule.Decode(master.Recurrence);
            e.Start    = master.Start;
            e.End      = master.End;
            e.Text     = master.Text;
            e.Resource = master.Resource;
            break;

        case EventMode.NewException:
            _rule = RecurrenceRule.Exception;
            DateTime start    = Occurrence;
            TimeSpan duration = master.End - master.Start;
            DateTime end      = start + duration;
            e.Start    = start;
            e.End      = end;
            e.Text     = master.Text;
            e.Resource = master.Resource;
            break;

        case EventMode.Exception:
            _rule      = RecurrenceRule.Exception;
            e.Start    = row.Start;
            e.End      = row.End;
            e.Text     = row.Text;
            e.Resource = row.Resource;
            break;

        case EventMode.Regular:
            _rule      = RecurrenceRule.NoRepeat;
            e.Start    = row.Start;
            e.End      = row.End;
            e.Text     = row.Text;
            e.Resource = row.Resource;
            break;

        default:
            throw new ArgumentOutOfRangeException();
        }

        ViewData["RecurrenceJson"] = new HtmlString(_rule.ToJson());

        return(View(e));
    }
Example #22
0
        public List <EventWrapper> UpdateEvent(string calendarId, int eventId, string name, string description, ApiDateTime startDate, ApiDateTime endDate, string repeatType, EventAlertType alertType, bool isAllDayLong, List <SharingParam> sharingOptions)
        {
            var sharingOptionsList = sharingOptions ?? new List <SharingParam>();

            var oldEvent = _dataProvider.GetEventById(eventId);

            //check permissions
            CheckPermissions(oldEvent, CalendarAccessRights.FullAccessAction);

            name = (name ?? "").Trim();
            if (String.IsNullOrEmpty(name))
            {
                throw new Exception(Resources.CalendarApiResource.ErrorEmptyName);
            }

            description = (description ?? "").Trim();

            TimeZoneInfo timeZone = null;
            int          calId    = int.Parse(oldEvent.CalendarId);

            if (!int.TryParse(calendarId, out calId))
            {
                calId    = int.Parse(oldEvent.CalendarId);
                timeZone = _dataProvider.GetTimeZoneForSharedEventsCalendar(SecurityContext.CurrentAccount.ID);
            }
            else
            {
                timeZone = _dataProvider.GetTimeZoneForCalendar(SecurityContext.CurrentAccount.ID, calId);
            }

            var rrule  = RecurrenceRule.Parse(repeatType);
            var usrIds = new List <Guid>();
            var evt    = _dataProvider.UpdateEvent(eventId, calId,
                                                   oldEvent.OwnerId, name, description, startDate.UtcTime, endDate.UtcTime, rrule, alertType, isAllDayLong,
                                                   sharingOptionsList.Select(o => o as SharingOptions.PublicItem).ToList());

            if (evt != null)
            {
                //clear old rights
                CoreContext.AuthorizationManager.RemoveAllAces(evt);

                foreach (var opt in sharingOptionsList)
                {
                    if (String.Equals(opt.actionId, AccessOption.FullAccessOption.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        CoreContext.AuthorizationManager.AddAce(new AzRecord(opt.Id, CalendarAccessRights.FullAccessAction.ID, ASC.Common.Security.Authorizing.AceType.Allow, evt));
                    }
                }

                //notify
                CalendarNotifyClient.NotifyAboutSharingEvent(evt, oldEvent);

                evt.CalendarId = calendarId;
                return(new EventWrapper(evt, SecurityContext.CurrentAccount.ID, timeZone).GetList(startDate.UtcTime, startDate.UtcTime.AddMonths(_monthCount)));
            }
            return(null);
        }
        public void ParseWeeklySeriesFormat()
        {
            var parsedRule = RecurrenceRule.Parse("week_1___1,2,3,4,5#no");

            Assert.AreEqual(RecurrenceType.Weekly, parsedRule.Type);
            Assert.AreEqual(1, parsedRule.Interval);
            Assert.AreEqual(5, parsedRule.DaysOfWeek.Count);
            Assert.AreEqual(-1, parsedRule.NumberOfInstances);
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return(true);
            }

            return(value as string != null && RecurrenceRule.TryParse(value as string, out _));
        }
Example #25
0
        private static RecurrenceType CreateRecurrence(RecurrenceRule schedulerRule, RadScheduler owner)
        {
            RecurrenceType recurrence = new RecurrenceType();

            recurrence.Item  = RecurrencePatternBaseType.CreateFromSchedulerRecurrencePattern(schedulerRule.Pattern);
            recurrence.Item1 = RecurrenceRangeBaseType.CreateFromSchedulerRecurrenceRule(schedulerRule, owner);

            return(recurrence);
        }
Example #26
0
        public static BaseEvent ConvertEvent(Ical.Net.CalendarComponents.CalendarEvent eventObj)
        {
            if (eventObj == null)
            {
                return(null);
            }

            var result = new BusinessObjects.Event();

            result.Name = eventObj.Summary;

            result.Description = eventObj.Description;

            result.AllDayLong = eventObj.IsAllDay;

            result.Uid = eventObj.Uid;

            result.UtcStartDate = ToUtc(eventObj.Start);

            result.UtcEndDate = ToUtc(eventObj.End);

            result.UtcUpdateDate = ToUtc(eventObj.Created);

            var recurrenceRuleStr = string.Empty;

            if (eventObj.RecurrenceRules != null && eventObj.RecurrenceRules.Any())
            {
                var recurrenceRules = eventObj.RecurrenceRules.ToList();

                recurrenceRuleStr = SerializeRecurrencePattern(recurrenceRules.First());
            }

            result.RecurrenceRule = RecurrenceRule.Parse(recurrenceRuleStr);

            if (eventObj.ExceptionDates != null && eventObj.ExceptionDates.Any())
            {
                result.RecurrenceRule.ExDates = new List <RecurrenceRule.ExDate>();

                var exceptionDates = eventObj.ExceptionDates.ToList();

                foreach (var periodList in exceptionDates.First())
                {
                    var start = ToUtc(periodList.StartTime);

                    result.RecurrenceRule.ExDates.Add(new RecurrenceRule.ExDate
                    {
                        Date       = start,
                        isDateTime = start != start.Date
                    });
                }
            }

            result.Status = ConvertEventStatus(eventObj.Status);

            return(result);
        }
        public void Daily_WithInterval_Until2()
        {
            var rrule       = RecurrenceRule.Parse("FREQ=DAILY;INTERVAL=2;UNTIL=19970905T070000Z");
            var startDate   = new DateTime(1997, 09, 02, 09, 00, 00);
            var occurrences = rrule.GetNextOccurrences(startDate);

            AssertOccurrences(occurrences,
                              new DateTime(1997, 09, 02, 09, 00, 00),
                              new DateTime(1997, 09, 04, 09, 00, 00));
        }
Example #28
0
    protected void DayPilotCalendar1_OnBeforeEventRecurrence(BeforeEventRecurrenceEventArgs ea)
    {
        List <DateTime> list = new List <DateTime>();

        for (int i = 1; i < 5; i++)
        {
            list.Add(ea.Start.AddHours(i));
        }
        ea.Rule = RecurrenceRule.FromList(list);
    }
 //added to provide dynamic initialization for DateList in span rules.
 private void InitSpanDateList()
 {
     string[] parts = RecurrenceRule.Split(new char[] { RecurrenceSupport.RuleDelimiter });
     if (parts.GetLength(0) == 3)
     {
         dateList              = new RecurrenceList();
         dateList.BaseDate     = DateTime.Parse(parts[1], System.Globalization.CultureInfo.InstalledUICulture.DateTimeFormat);
         dateList.TerminalDate = DateTime.Parse(parts[2], System.Globalization.CultureInfo.InstalledUICulture.DateTimeFormat);
     }
 }
Example #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetNoStore();

        string data = Request.QueryString["hash"];

        if (Session[data] == null)
        {
            throw new Exception("The session data expired.");
        }
        table = (DataTable)Session[data];

        DataRow row    = table.Rows.Find(Request.QueryString["id"]);
        DataRow master = table.Rows.Find(Request.QueryString["master"]);

        if (!IsPostBack)
        {
            switch (Mode)
            {
            case EventMode.Master:
                _rule             = RecurrenceRule.Decode((string)master["recurrence"]);
                TextBoxStart.Text = ((DateTime)master["start"]).ToString();
                TextBoxEnd.Text   = ((DateTime)master["end"]).ToString();
                TextBoxName.Text  = (string)master["name"];
                break;

            case EventMode.NewException:
                _rule = RecurrenceRule.Exception;
                DateTime start    = Occurrence;
                TimeSpan duration = (DateTime)master["end"] - (DateTime)master["start"];
                DateTime end      = start + duration;
                TextBoxStart.Text = start.ToString();
                TextBoxEnd.Text   = end.ToString();
                TextBoxName.Text  = (string)master["name"];
                break;

            case EventMode.Exception:
                _rule             = RecurrenceRule.Exception;
                TextBoxStart.Text = ((DateTime)row["start"]).ToString();
                TextBoxEnd.Text   = ((DateTime)row["end"]).ToString();
                TextBoxName.Text  = (string)row["name"];
                break;

            case EventMode.Regular:
                _rule             = RecurrenceRule.NoRepeat;
                TextBoxStart.Text = ((DateTime)row["start"]).ToString();
                TextBoxEnd.Text   = ((DateTime)row["end"]).ToString();
                TextBoxName.Text  = (string)row["name"];
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
    }
Example #31
0
 public static void GetRelative(RecurrenceRule obj, MethodReturnEventArgs<DateTime> e, DateTime dt)
 {
     if (obj.Count.HasValue == false)
     {
         e.Result = obj.GetNext(dt, dt);
     }
     else if (obj.Count == 1)
     {
         throw new InvalidOperationException("count cannot be 1, would return dt");
     }
     else
     {
         var result = dt;
         for (int i = 0; i < obj.Count; i++)
         {
             result = obj.GetNext(result, result);
         }
         e.Result = result;
     }
 }
		public static RecurrenceRangeBaseType CreateFromSchedulerRecurrenceRule(RecurrenceRule schedulerRule, RadScheduler owner)
		{
			RecurrenceRange schedulerRange = schedulerRule.Range;

			DateTime start = schedulerRange.Start;

			//DateTime start = owner.UtcDayStart(schedulerRange.Start);
			if (schedulerRule.Pattern.Frequency == RecurrenceFrequency.Monthly ||
				schedulerRule.Pattern.Frequency == RecurrenceFrequency.Yearly)
			{
				DateTime monthStart = new DateTime(schedulerRange.Start.Year, schedulerRange.Start.Month, 1, 0, 0, 0, DateTimeKind.Utc);
				start = monthStart;
			}

			if (schedulerRange.RecursUntil < DateTime.MaxValue)
			{
				EndDateRecurrenceRangeType range = new EndDateRecurrenceRangeType();
				range.StartDate = start;
				range.EndDate = schedulerRange.RecursUntil.AddDays(-1);
				return range;
			}

			if (schedulerRange.MaxOccurrences < int.MaxValue)
			{
				NumberedRecurrenceRangeType range = new NumberedRecurrenceRangeType();
				range.StartDate = start;
				range.NumberOfOccurrences = schedulerRange.MaxOccurrences;
				return range;
			}

			NoEndRecurrenceRangeType noEndRange = new NoEndRecurrenceRangeType();
			noEndRange.StartDate = start;

			return noEndRange;
		}
Example #33
0
        public static void GetWithinInterval(RecurrenceRule obj, MethodReturnEventArgs<IEnumerable<DateTime>> e, DateTime start, DateTime from, DateTime until)
        {
            if (obj.Frequency == null)
            {
                e.Result = Enumerable.Empty<DateTime>();
                return;
            }
            var interval = obj.Interval ?? 1;
            if (interval <= 0)
            {
                Logging.Log.WarnFormat("{0} has an invalid interval of {1}", obj, interval);
                interval = 1;
            }

            if (obj.Until.HasValue && obj.Until < until)
            {
                until = obj.Until.Value;
            }

            var result = new List<DateTime>();
            var current = start;
            AddToResult(result, current, from, until);
            int count = 1;

            while (current <= until && (obj.Count.HasValue == false || obj.Count > count))
            {
                switch (obj.Frequency.Value)
                {
                    case Frequency.Yearly:
                        current = current.AddYears(interval);
                        count += AddToResult(result, current, from, until);
                        break;
                    case Frequency.Monthly:
                        if (obj.ByMonthDay != null)
                        {
                            for (int i = 0; i < 2; i++)
                            {
                                foreach (var day in ToInt(obj.ByMonthDay))
                                {
                                    if (day >= 0)
                                    {
                                        var first = current.FirstMonthDay().Add(current.TimeOfDay);
                                        count += AddToResult(result, first.AddDays(day - 1), from, until);
                                    }
                                    else
                                    {
                                        var last = current.LastMonthDay().Add(current.TimeOfDay);
                                        count += AddToResult(result, last.AddDays(day + 1), from, until);
                                    }
                                }
                                current = current.AddMonths(interval);
                            }
                        }
                        else
                        {
                            current = current.AddMonths(interval);
                            count += AddToResult(result, current, from, until);
                        }
                        break;
                    case Frequency.Weekly:
                        current = current.AddDays(interval * 7);
                        if (obj.ByDay != null)
                        {
                            var first = current.FirstWeekDay().Add(current.TimeOfDay);
                            foreach (var wd in ToWeekdays(obj.ByDay))
                            {
                                count += AddToResult(result, first.AddDays((((int)wd - 1) % 7)), from, until);
                            }
                        }
                        else
                        {
                            count += AddToResult(result, current, from, until);
                        }
                        break;
                    case Frequency.Daily:
                        current = current.AddDays(interval);
                        count += AddToResult(result, current, from, until);
                        break;
                    case Frequency.Hourly:
                        current = current.AddHours(interval);
                        count += AddToResult(result, current, from, until);
                        break;
                    case Frequency.Minutely:
                        current = current.AddMinutes(interval);
                        count += AddToResult(result, current, from, until);
                        break;
                    case Frequency.Secondly:
                        current = current.AddSeconds(interval);
                        count += AddToResult(result, current, from, until);
                        break;
                    default:
                        break;
                }
            }

            e.Result = result;
        }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Event"/> class.
 /// </summary>
 /// <param name="portalId">The portal id.</param>
 /// <param name="moduleId">The module id.</param>
 /// <param name="organizerEmail">The organizer email.</param>
 /// <param name="title">The title of the event.</param>
 /// <param name="overview">The overview (short description) of the event.</param>
 /// <param name="description">The event description.</param>
 /// <param name="eventStart">When the event starts.</param>
 /// <param name="eventEnd">When the event ends.</param>
 /// <param name="timeZoneId">The time zone's ID.</param>
 /// <param name="location">The location of the event.</param>
 /// <param name="isFeatured">if set to <c>true</c> this event is featured.</param>
 /// <param name="allowRegistrations">if set to <c>true</c> this event allows users to register for it.</param>
 /// <param name="recurrenceRule">The recurrence rule.</param>
 /// <param name="canceled">if set to <c>true</c> this event is canceled.</param>
 /// <param name="capacity">The maximum number of registrants for this event, or <c>null</c> if there is no maximum.</param>
 /// <param name="capacityMetMessage">The the message to display to a user who wants to register for this
 /// event when the <see cref="Capacity"/> for this event has been met,  or
 /// <c>null</c> or <see cref="string.Empty"/> to display a generic message.</param>
 /// <param name="categoryId">The ID of the event's <see cref="Category"/>.</param>
 private Event(
     int portalId,
     int moduleId,
     string organizerEmail,
     string title,
     string overview,
     string description,
     DateTime eventStart,
     DateTime eventEnd,
     string timeZoneId,
     string location,
     bool isFeatured,
     bool allowRegistrations,
     RecurrenceRule recurrenceRule,
     bool canceled,
     int? capacity,
     string capacityMetMessage,
     int categoryId)
 {
     this.Id = -1;
     this.CreatedBy = -1;
     this.LocationUrl = string.Empty;
     this.InvitationUrl = string.Empty;
     this.RecapUrl = string.Empty;
     this.Organizer = string.Empty;
     this.PortalId = portalId;
     this.ModuleId = moduleId;
     this.OrganizerEmail = organizerEmail ?? string.Empty;
     this.Title = title;
     this.Overview = overview;
     this.Description = description;
     this.EventStart = eventStart;
     this.EventEnd = eventEnd;
     this.TimeZoneId = timeZoneId;
     this.Location = location;
     this.IsFeatured = isFeatured;
     this.AllowRegistrations = allowRegistrations;
     this.RecurrenceRule = recurrenceRule;
     this.Canceled = canceled;
     this.Capacity = capacity;
     this.CapacityMetMessage = capacityMetMessage;
     this.CategoryId = categoryId;
 }
        /// <summary>
        /// Transfers information from a Task object into a data row.
        /// </summary>
        public EditTaskFormData.TaskRow LoadTask(Task task)
        {
            PatternParser parser = new PatternParser();
            if (!parser.Parse(task.Pattern))
                throw new Exception("This is not a simple pattern.");

            mTaskData = NewTask();
            mTask = task;
            mRule = mTask.Pattern.RRules[0];

            //Load task name
            mTaskData.Name = task.Name;

            //Load the recurrence rule
            switch (parser.PatternType)
            {
                case PatternType.Daily:
                    LoadDaily();
                    break;
                case PatternType.Weekly:
                    LoadWeekly();
                    break;
                case PatternType.MonthlyDay:
                    LoadMonthlyDay();
                    break;
                case PatternType.MonthlyDayOfWeek:
                    LoadMonthlyDayOfWeek();
                    break;
                case PatternType.MonthlyWeekDay:
                    LoadMonthlyWeekDay();
                    break;
                case PatternType.YearlyDay:
                    LoadYearlyDay();
                    break;
                case PatternType.YearlyDayOfWeek:
                    LoadYearlyDayOfWeek();
                    break;
                case PatternType.YearlyWeekDay:
                    LoadYearlyWeekDay();
                    break;
                default:
                    throw new Exception("Unknown pattern type.");
            }

            //Load the range of the pattenr
            mTaskData.StartDate = DemoUtil.FormatDate(task.Pattern.StartDate);
            mTaskData.StartTime = DemoUtil.FormatTime(task.Pattern.StartDate);
            mTaskData.EndChoice = (int)mRule.EndType;
            switch (mRule.EndType)
            {
                case EndType.None:
                    //Do nothing
                    break;
                case EndType.Count:
                    mTaskData.Count = mRule.Count.ToString();
                    break;
                case EndType.Until:
                    mTaskData.EndDate = DemoUtil.FormatDate(mRule.Until);
                    break;
                default:
                    throw new Exception("Unknown end type.");
            }

            return mTaskData;
        }
Example #36
0
 /// <summary>
 /// Creates the specified event.
 /// </summary>
 /// <param name="portalId">The portal id.</param>
 /// <param name="moduleId">The module id.</param>
 /// <param name="organizerEmail">The organizer email.</param>
 /// <param name="title">The title of the event.</param>
 /// <param name="overview">The overview or description of the event.</param>
 /// <param name="description">The description.</param>
 /// <param name="eventStart">The event's start date and time.</param>
 /// <param name="eventEnd">The event end.</param>
 /// <param name="timeZoneId">The time zone's ID.</param>
 /// <param name="location">The location of the event.</param>
 /// <param name="isFeatured">if set to <c>true</c> the event should be listed in featured displays.</param>
 /// <param name="allowRegistrations">if set to <c>true</c> this event allows users to register for it.</param>
 /// <param name="recurrenceRule">The recurrence rule.</param>
 /// <param name="capacity">The maximum number of registrants for this event, or <c>null</c> if there is no maximum.</param>
 /// <param name="capacityMetMessage">
 /// The the message to display to a user who wants to register for this
 /// event when the <see cref="Capacity"/> for this event has been met,  or 
 /// <c>null</c> or <see cref="string.Empty"/> to display a generic message.
 /// </param>
 /// <param name="categoryId">The ID of the event's <see cref="Category"/>.</param>
 /// <returns>A new event object.</returns>
 public static Event Create(
     int portalId,
     int moduleId,
     string organizerEmail,
     string title,
     string overview,
     string description,
     DateTime eventStart,
     DateTime eventEnd,
     string timeZoneId,
     string location,
     bool isFeatured,
     bool allowRegistrations,
     RecurrenceRule recurrenceRule,
     int? capacity,
     string capacityMetMessage,
     int categoryId)
 {
     return new Event(
         portalId,
         moduleId,
         organizerEmail,
         title,
         overview,
         description,
         eventStart,
         eventEnd,
         timeZoneId,
         location,
         isFeatured,
         allowRegistrations,
         recurrenceRule,
         capacity,
         capacityMetMessage,
         categoryId);
 }
        /// <summary>
        /// Saves data from the data set into a Task object.
        /// </summary>
        public void Save(EditTaskFormData.TaskRow taskData, Task task)
        {
            mTaskData = taskData;
            mTask = task;

            Validate();

            //Save task name
            mTask.Name = mTaskData.Name;

            //Create a new recurrence pattern that we will save the data into.
            mTask.Pattern = new RecurrencePattern();
            mRule = mTask.Pattern.RRules.Add();

            //Save the recurrence rule
            switch ((RecurrenceChoice)mTaskData.RecurrenceChoice)
            {
                case RecurrenceChoice.Daily:
                    SaveDaily();
                    break;
                case RecurrenceChoice.Weekly:
                    SaveWeekly();
                    break;
                case RecurrenceChoice.Monthly:
                    SaveMonthly();
                    break;
                case RecurrenceChoice.Yearly:
                    SaveYearly();
                    break;
                default:
                    throw new Exception("Unknown recurrence choice.");
            }

            //Save the range of the pattern
            mTask.Pattern.StartDate = DateTime.Parse(mTaskData.StartDate) + TimeSpan.Parse(mTaskData.StartTime);
            switch ((EndType)mTaskData.EndChoice)
            {
                case EndType.None:
                    mRule.EndType = EndType.None;
                    break;
                case EndType.Count:
                    mRule.Count = int.Parse(mTaskData.Count);
                    break;
                case EndType.Until:
                    mRule.Until = DateTime.Parse(mTaskData.EndDate);
                    break;
                default:
                    throw new Exception("Unknown end type.");
            }
        }
 /// <summary>
 /// Crazy hack because i had issue with save and the rules applied on setter of RecurrenceRule
 /// Use this method only for saving.
 /// </summary>
 /// <param name="recRule"></param>
 public void SetPrivateRecurrenceRuleForSave(RecurrenceRule recRule)
 {
     recurrenceRule = recRule;
 }
Example #39
0
 public override void SetUp()
 {
     base.SetUp();
     ctx = GetContext();
     rule = ctx.CreateCompoundObject<RecurrenceRule>();
     now = new DateTime(2012, 9, 26);
     start = new DateTime(2012, 1, 1);
 }
		private static RecurrenceType CreateRecurrence(RecurrenceRule schedulerRule, RadScheduler owner)
		{
			RecurrenceType recurrence = new RecurrenceType();
			recurrence.Item = RecurrencePatternBaseType.CreateFromSchedulerRecurrencePattern(schedulerRule.Pattern);
			recurrence.Item1 = RecurrenceRangeBaseType.CreateFromSchedulerRecurrenceRule(schedulerRule, owner);

			return recurrence;
		}
 /// <summary>
 /// Adds all exceptions defined in the EXDATE property of the specified Recurring Component in
 /// the list of Exceptions of the Scheduler Recurrence Rule.
 /// </summary>
 /// <param name="schedulerRRule"><seealso cref="RecurrenceRule"/> as the Scheduler Recurrence Rule.</param>
 /// <param name="recurringComponent">The <seealso cref="RecurringComponent"/> object.</param>
 private static void AddRecurrenceExceptions(RecurrenceRule schedulerRRule, RecurringComponent recurringComponent)
 {
     if (recurringComponent.ExceptionDates != null)
     {
         foreach (IPeriodList exceptionDates in recurringComponent.ExceptionDates)
         {
             foreach (Period period in exceptionDates)
             {
                 if (period.StartTime != null)
                 {
                     schedulerRRule.Exceptions.Add(period.StartTime.Local);
                 }
             }
         }
     }
 }
Example #42
0
 public static void GetNext(RecurrenceRule obj, MethodReturnEventArgs<DateTime> e, DateTime start)
 {
     e.Result = obj.GetNext(start, DateTime.Now);
 }
Example #43
0
 public static void GetNext(RecurrenceRule obj, MethodReturnEventArgs<DateTime> e, DateTime start, DateTime dt)
 {
     var occurrences = obj.GetWithinInterval(start, dt, dt.Add(GetIntervalTimeSpan(obj.Frequency, obj.Interval)));
     e.Result = occurrences.Where(i => i != dt).FirstOrDefault();
     if (e.Result == default(DateTime)) e.Result = dt;
 }
 /// <summary>
 /// Sets the recurrence rule for this control instance.
 /// </summary>
 /// <param name="rule">The recurrence rule with which to populate this control.</param>
 internal void SetRecurrenceRule(RecurrenceRule rule)
 {
     if (rule != null)
     {
         this.SetRecurrencePattern(rule.Pattern);
         this.SetRecurrenceRange(rule.Range);
     }
 }
Example #45
0
        public static void ToString(RecurrenceRule obj, MethodReturnEventArgs<string> e)
        {
            var interval = obj.Interval ?? 1;
            if (interval <= 0)
            {
                interval = 1;
            }

            var sb = new StringBuilder();
            if (obj.Frequency.HasValue) sb.AppendFormat("every {0} {1}", interval, ToString(obj.Frequency.Value));
            if (!string.IsNullOrWhiteSpace(obj.ByMonth)) sb.AppendFormat(" by months {0}", obj.ByMonth);
            if (!string.IsNullOrWhiteSpace(obj.ByWeekNumber)) sb.AppendFormat(" by week numbers {0}", obj.ByWeekNumber);
            if (!string.IsNullOrWhiteSpace(obj.ByYearDay)) sb.AppendFormat(" by year days {0}", obj.ByYearDay);
            if (!string.IsNullOrWhiteSpace(obj.ByMonthDay)) sb.AppendFormat(" by month days {0}", obj.ByMonthDay);
            if (!string.IsNullOrWhiteSpace(obj.ByDay)) sb.AppendFormat(" by days {0}", obj.ByDay);
            if (!string.IsNullOrWhiteSpace(obj.ByHour)) sb.AppendFormat(" by hours {0}", obj.ByHour);
            if (!string.IsNullOrWhiteSpace(obj.ByMinute)) sb.AppendFormat(" by minutes {0}", obj.ByMinute);
            if (!string.IsNullOrWhiteSpace(obj.BySecond)) sb.AppendFormat(" by seconds {0}", obj.BySecond);

            if (obj.Until.HasValue)
            {
                sb.AppendFormat(" until {0}", obj.Until);
            }
            else if (obj.Count.HasValue)
            {
                sb.AppendFormat(" {0} times", obj.Count);
            }

            if (sb.Length == 0)
            {
                sb.Append("not defined");
            }
            e.Result = sb.ToString();
        }