Пример #1
0
 /// <summary>
 /// This is called to set the values for the controls based on the current recurrence settings
 /// </summary>
 /// <param name="rRecur">The recurrence object from which to get the settings</param>
 public void SetValues(Recurrence rRecur)
 {
     if(rRecur.Frequency == RecurFrequency.Minutely)
         udcMinutes.Value = (rRecur.Interval < 1000) ? rRecur.Interval : 999;
     else
         udcMinutes.Value = 1;
 }
Пример #2
0
		public Schedule(List<DateTimeRange> timeRanges, Recurrence recurrence, int activationLimit)
		{
			TimeRanges = timeRanges;
			
			RequiredRecurrence = recurrence;
			ActivationLimit = activationLimit;
		}
Пример #3
0
 /// <summary>
 /// This is called to set the values for the controls based on the current recurrence settings
 /// </summary>
 /// <param name="recurrence">The recurrence object from which to get the settings</param>
 public void SetValues(Recurrence recurrence)
 {
     if(recurrence.Frequency == RecurFrequency.Hourly)
         udcHours.Value = (recurrence.Interval < 1000) ? recurrence.Interval : 999;
     else
         udcHours.Value = 1;
 }
Пример #4
0
        //=====================================================================

        /// <summary>
        /// This is called to get the values from the controls and set them in the specified recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence object to which the settings are applied</param>
        /// <remarks>It is assumed that the recurrence object has been reset to a default state</remarks>
        public void GetValues(Recurrence recurrence)
        {
            if(recurrence.Frequency == RecurFrequency.Weekly)
            {
                recurrence.Interval = (int)udcWeeks.Value;

                if(chkSunday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Sunday);

                if(chkMonday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Monday);

                if(chkTuesday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Tuesday);

                if(chkWednesday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Wednesday);

                if(chkThursday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Thursday);

                if(chkFriday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Friday);

                if(chkSaturday.Checked)
                    recurrence.ByDay.Add(DayOfWeek.Saturday);
            }
        }
Пример #5
0
        //=====================================================================

        /// <summary>
        /// This is called to get the values from the controls and set them in the specified recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence object to which the settings are applied</param>
        /// <remarks>It is assumed that the recurrence object has been reset to a default state</remarks>
        public void GetValues(Recurrence recurrence)
        {
            if(recurrence.Frequency == RecurFrequency.Daily)
                if(rbEveryXDays.Checked)
                    recurrence.Interval = (int)udcDays.Value;
                else
                {
                    recurrence.Interval = 1;
                    recurrence.ByDay.AddRange(new[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday,
                        DayOfWeek.Thursday, DayOfWeek.Friday });
                }
        }
Пример #6
0
        //=====================================================================

        /// <summary>
        /// This is called to get the values from the controls and set them in the specified recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence object to which the settings are applied</param>
        /// <remarks>It is assumed that the recurrence object has been reset to a default state</remarks>
        public void GetValues(Recurrence recurrence)
        {
            int instance;
            DaysOfWeek rd;

            if(recurrence.Frequency != RecurFrequency.Yearly)
                return;

            if(rbDayXEveryYYears.Checked)
            {
                recurrence.Interval = (int)udcYears.Value;
                recurrence.ByMonth.Add((int)cboMonth.SelectedValue);
                recurrence.ByMonthDay.Add((int)udcDay.Value);
            }
            else
            {
                recurrence.Interval = (int)udcDOWYears.Value;
                recurrence.ByMonth.Add((int)cboDOWMonth.SelectedValue);

                // If it's a single day, use ByDay.  If it's a combination, use ByDay with BySetPos.
                rd = (DaysOfWeek)cboDOW.SelectedValue;
                instance = ((DayOccurrence)cboOccurrence.SelectedValue == DayOccurrence.Last) ? -1 :
                    (int)cboOccurrence.SelectedValue;

                switch(rd)
                {
                    case DaysOfWeek.EveryDay:
                        recurrence.BySetPos.Add(instance);
                        recurrence.ByDay.AddRange(new DayOfWeek[] { DayOfWeek.Sunday, DayOfWeek.Monday,
                            DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday,
                            DayOfWeek.Saturday });
                        break;

                    case DaysOfWeek.Weekdays:
                        recurrence.BySetPos.Add(instance);
                        recurrence.ByDay.AddRange(new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday,
                            DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday });
                        break;

                    case DaysOfWeek.Weekends:
                        recurrence.BySetPos.Add(instance);
                        recurrence.ByDay.AddRange(new DayOfWeek[] { DayOfWeek.Sunday, DayOfWeek.Saturday });
                        break;

                    default:
                        recurrence.ByDay.Add(new DayInstance(instance, DateUtils.ToDayOfWeek(rd)));
                        break;
                }
            }
        }
Пример #7
0
		public Schedule(JSONObject jsonSched)
		{
			if(jsonSched[JSONConsts.SOOM_SCHE_REC]) {
				RequiredRecurrence = (Recurrence) jsonSched[JSONConsts.SOOM_SCHE_REC].n;
			} else {
				RequiredRecurrence = Recurrence.NONE;
			}

			ActivationLimit = (int)Math.Ceiling(jsonSched[JSONConsts.SOOM_SCHE_APPROVALS].n);

			TimeRanges = new List<DateTimeRange>();
			if (jsonSched[JSONConsts.SOOM_SCHE_RANGES]) {
				List<JSONObject> RangesObjs = jsonSched[JSONConsts.SOOM_SCHE_RANGES].list;
				foreach(JSONObject RangeObj in RangesObjs) {
					TimeSpan tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_START].n);
					DateTime start = new DateTime(tmpTime.Ticks);
					tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_END].n);
					DateTime end = new DateTime(tmpTime.Ticks);

					TimeRanges.Add(new DateTimeRange(start, end));
				}
			}
		}
Пример #8
0
        /// <summary>
        /// This is called to set the values for the controls based on the current recurrence settings
        /// </summary>
        /// <param name="recurrence">The recurrence object from which to get the settings</param>
        public void SetValues(Recurrence recurrence)
        {
            int idx;

            rbEveryXDays.Checked = true;

            if(recurrence.Frequency != RecurFrequency.Daily)
                udcDays.Value = 1;
            else
            {
                udcDays.Value = (recurrence.Interval < 1000) ? recurrence.Interval : 999;

                // "Daily, every weekday" is a special case that is handled as a simple pattern in this control
                if(recurrence.ByDay.Count == 5 && recurrence.Interval == 1)
                {
                    for(idx = 0; idx < 5; idx++)
                        if(recurrence.ByDay[idx].Instance != 0 || recurrence.ByDay[idx].DayOfWeek == DayOfWeek.Saturday ||
                          recurrence.ByDay[idx].DayOfWeek == DayOfWeek.Sunday)
                            break;

                    rbEveryWeekday.Checked = (idx == 5);
                }
            }
        }
Пример #9
0
        /// <summary>
        /// This is called to set the values for the controls based on the current recurrence settings
        /// </summary>
        /// <param name="recurrence">The recurrence object from which to get the settings</param>
        public void SetValues(Recurrence recurrence)
        {
            DaysOfWeek rd = DaysOfWeek.None;

            rbDayXEveryYYears.Checked = true;

            // Use default values if not a yearly frequency
            if(recurrence.Frequency != RecurFrequency.Yearly)
            {
                udcDay.Value = udcYears.Value = udcDOWYears.Value = 1;
                cboMonth.SelectedIndex = cboOccurrence.SelectedIndex = cboDOW.SelectedIndex =
                    cboDOWMonth.SelectedIndex = 0;
            }
            else
            {
                if(recurrence.ByDay.Count == 0)
                {
                    if(recurrence.ByMonth.Count != 0)
                        cboMonth.SelectedValue = recurrence.ByMonth[0];
                    else
                        cboMonth.SelectedValue = recurrence.StartDateTime.Month;

                    if(recurrence.ByMonthDay.Count != 0)
                        udcDay.Value = recurrence.ByMonthDay[0];
                    else
                        udcDay.Value = recurrence.StartDateTime.Day;

                    udcYears.Value = (recurrence.Interval < 1000) ? recurrence.Interval : 999;

                    cboOccurrence.SelectedIndex = cboDOW.SelectedIndex = cboDOWMonth.SelectedIndex = 0;
                    udcDOWYears.Value = 1;
                }
                else
                {
                    rbDayOfWeek.Checked = true;

                    udcDay.Value = udcYears.Value = 1;
                    udcDOWYears.Value = (recurrence.Interval < 1000) ? recurrence.Interval : 999;
                    cboMonth.SelectedIndex = 0;

                    if(recurrence.ByMonth.Count != 0)
                        cboDOWMonth.SelectedValue = recurrence.ByMonth[0];
                    else
                        cboDOWMonth.SelectedValue = recurrence.StartDateTime.Month;

                    // If it's a single day, use ByDay.  If it's a combination, use ByDay with BySetPos.
                    if(recurrence.ByDay.Count == 1)
                    {
                        cboOccurrence.SelectedValue = (recurrence.ByDay[0].Instance < 1 ||
                          recurrence.ByDay[0].Instance > 4) ? DayOccurrence.Last :
                            (DayOccurrence)recurrence.ByDay[0].Instance;

                        cboDOW.SelectedValue = DateUtils.ToDaysOfWeek(recurrence.ByDay[0].DayOfWeek);
                    }
                    else
                    {
                        if(recurrence.BySetPos.Count == 0)
                            cboOccurrence.SelectedIndex = 0;
                        else
                            cboOccurrence.SelectedValue = (recurrence.BySetPos[0] < 1 ||
                              recurrence.BySetPos[0] > 4) ? DayOccurrence.Last :
                                (DayOccurrence)recurrence.BySetPos[0];

                        // Figure out days
                        foreach(DayInstance di in recurrence.ByDay)
                            switch(di.DayOfWeek)
                            {
                                case DayOfWeek.Sunday:
                                    rd |= DaysOfWeek.Sunday;
                                    break;

                                case DayOfWeek.Monday:
                                    rd |= DaysOfWeek.Monday;
                                    break;

                                case DayOfWeek.Tuesday:
                                    rd |= DaysOfWeek.Tuesday;
                                    break;

                                case DayOfWeek.Wednesday:
                                    rd |= DaysOfWeek.Wednesday;
                                    break;

                                case DayOfWeek.Thursday:
                                    rd |= DaysOfWeek.Thursday;
                                    break;

                                case DayOfWeek.Friday:
                                    rd |= DaysOfWeek.Friday;
                                    break;

                                case DayOfWeek.Saturday:
                                    rd |= DaysOfWeek.Saturday;
                                    break;
                            }

                        // If not EveryDay, Weekdays, or Weekends, force it to a single day of the week
                        if(rd == DaysOfWeek.None || (rd != DaysOfWeek.EveryDay && rd != DaysOfWeek.Weekdays &&
                          rd != DaysOfWeek.Weekends))
                            rd = DateUtils.ToDaysOfWeek(DateUtils.ToDayOfWeek(rd));

                        cboDOW.SelectedValue = rd;
                    }
                }
            }
        }
Пример #10
0
 //recurrence
 public void AddRecurrence(Recurrence recurrence)
 {
     _repository.Recurrence.Add(recurrence);
 }
Пример #11
0
 public void DeleteRecurrence(Recurrence recurrence)
 {
     _repository.Recurrence.Delete(recurrence);
 }
Пример #12
0
        //=====================================================================

        /// <summary>
        /// Test the recurrence class with the entered pattern
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            DateTimeCollection dc;
            int    start, count;
            double elapsed;

            try
            {
                lblCount.Text = String.Empty;

                // Define the recurrence rule by parsing the text
                Recurrence r = new Recurrence(txtRRULE.Text);
                r.StartDateTime = dtpStartDate.Value;

                // Get the currently defined set of holidays if necessary
                if (!r.CanOccurOnHoliday)
                {
                    Recurrence.Holidays.Clear();
                    Recurrence.Holidays.AddRange(hmHolidays.Holidays);
                }

                // For hourly, minutely, and secondly, warn the user if there is no end date or max occurrences
                if (r.Frequency >= RecurFrequency.Hourly && r.MaximumOccurrences == 0 &&
                    r.RecurUntil > r.StartDateTime.AddDays(100))
                {
                    if (MessageBox.Show("This recurrence may run for a very long time.  Continue?", "Confirm",
                                        MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }
                }

                lbDates.DataSource = null;
                this.Cursor        = Cursors.WaitCursor;

                start   = System.Environment.TickCount;
                dc      = r.InstancesBetween(r.StartDateTime, DateTime.MaxValue);
                elapsed = (System.Environment.TickCount - start) / 1000.0;
                count   = dc.Count;

                if (count > 5000)
                {
                    dc.RemoveRange(5000, count - 5000);
                    lblCount.Text += "A large number of dates were returned.  Only the first 5000 have been " +
                                     "loaded into the list box.\r\n";
                }

                // DateTimeCollection is bindable so we can assign it as the list box's data source
                lbDates.DataSource = dc;

                lblCount.Text += String.Format("Found {0:N0} instances in {1:N2} seconds ({2:N2} instances/second)",
                                               count, elapsed, count / elapsed);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
 /// <summary>
 /// Checks if two recurrence objects are identical. 
 /// </summary>
 /// <param name="otherRecurrence">The recurrence to compare this one to.</param>
 /// <returns>true if the two recurrences are identical, false otherwise.</returns>
 public override bool IsSame(Recurrence otherRecurrence)
 {
     return base.IsSame(otherRecurrence) && this.dayOfMonth == ((MonthlyPattern)otherRecurrence).dayOfMonth;
 }
Пример #14
0
        /// <summary>
        /// Show or hide the advanced pattern rule options
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void chkAdvanced_CheckedChanged(object sender, System.EventArgs e)
        {
            Recurrence r = new Recurrence();

            // Don't copy settings if the current context doesn't warrant it.  Just change the state of the
            // panels.
            if (noCopy)
            {
                pnlPatterns.Visible = !chkAdvanced.Checked;
                ucAdvanced.Visible  = chkAdvanced.Checked;
                return;
            }

            r.Frequency = rbYearly.Checked ? RecurFrequency.Yearly :
                          rbMonthly.Checked ? RecurFrequency.Monthly :
                          rbWeekly.Checked ? RecurFrequency.Weekly :
                          rbDaily.Checked ? RecurFrequency.Daily :
                          rbHourly.Checked ? RecurFrequency.Hourly :
                          rbMinutely.Checked ? RecurFrequency.Minutely : RecurFrequency.Secondly;

            // Copy settings between the advanced and simple panels based on the prior setting
            if (!chkAdvanced.Checked)
            {
                ucAdvanced.GetValues(r);

                // Set the state in all simple patterns so that the ones other than the current frequency reset
                // to their default state.
                ucYearly.SetValues(r);
                ucMonthly.SetValues(r);
                ucWeekly.SetValues(r);
                ucDaily.SetValues(r);
                ucHourly.SetValues(r);
                ucMinutely.SetValues(r);
                ucSecondly.SetValues(r);

                pnlPatterns.Visible = true;
                ucAdvanced.Visible  = false;
            }
            else
            {
                if (rbYearly.Checked)
                {
                    ucYearly.GetValues(r);
                }
                else
                if (rbMonthly.Checked)
                {
                    ucMonthly.GetValues(r);
                }
                else
                if (rbWeekly.Checked)
                {
                    ucWeekly.GetValues(r);
                }
                else
                if (rbDaily.Checked)
                {
                    ucDaily.GetValues(r);
                }
                else
                if (rbHourly.Checked)
                {
                    ucHourly.GetValues(r);
                }
                else
                if (rbMinutely.Checked)
                {
                    ucMinutely.GetValues(r);
                }
                else
                {
                    ucSecondly.GetValues(r);
                }

                ucAdvanced.SetValues(r);

                pnlPatterns.Visible = false;
                ucAdvanced.Visible  = true;
            }
        }
 internal override LocalizedString When()
 {
     if (Recurrence.IsGregorianCompatible(this.CalendarType))
     {
         if (base.RecurrenceInterval == 1)
         {
             if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
             {
                 return(ClientStrings.CalendarWhenMonthlyThEveryMonth(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
             }
             return(ClientStrings.TaskWhenMonthlyThEveryMonth(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
         }
         else if (base.RecurrenceInterval == 2)
         {
             if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
             {
                 return(ClientStrings.CalendarWhenMonthlyThEveryOtherMonth(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
             }
             return(ClientStrings.TaskWhenMonthlyThEveryOtherMonth(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
         }
         else
         {
             if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
             {
                 return(ClientStrings.CalendarWhenMonthlyThEveryNMonths(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek), base.RecurrenceInterval));
             }
             return(ClientStrings.TaskWhenMonthlyThEveryNMonths(MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek), base.RecurrenceInterval));
         }
     }
     else if (base.RecurrenceInterval == 1)
     {
         if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
         {
             return(ClientStrings.AlternateCalendarWhenMonthlyThEveryMonth(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
         }
         return(ClientStrings.AlternateCalendarTaskWhenMonthlyThEveryMonth(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
     }
     else if (base.RecurrenceInterval == 2)
     {
         if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
         {
             return(ClientStrings.AlternateCalendarWhenMonthlyThEveryOtherMonth(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
         }
         return(ClientStrings.AlternateCalendarTaskWhenMonthlyThEveryOtherMonth(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek)));
     }
     else
     {
         if (base.RecurrenceObjectType == RecurrenceObjectType.CalendarRecurrence)
         {
             return(ClientStrings.AlternateCalendarWhenMonthlyThEveryNMonths(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek), base.RecurrenceInterval));
         }
         return(ClientStrings.AlternateCalendarTaskWhenMonthlyThEveryNMonths(Recurrence.GetCalendarName(this.CalendarType), MonthlyThRecurrencePattern.OrderAsString(this.Order), new LocalizedDaysOfWeek(this.DaysOfWeek), base.RecurrenceInterval));
     }
 }
Пример #16
0
        public void Save()
        {
            ExTraceGlobals.TasksCallTracer.TraceDebug((long)this.GetHashCode(), "EditTaskEventHandler.Save");
            bool       flag       = base.IsParameterSet("Id");
            bool       flag2      = false;
            bool       flag3      = false;
            ExDateTime?exDateTime = null;
            Task       task       = this.GetTask(new PropertyDefinition[0]);

            try
            {
                if (!base.IsParameterSet("Id"))
                {
                    OwaStoreObjectId owaStoreObjectId = (OwaStoreObjectId)base.GetParameter("fId");
                    if (owaStoreObjectId != null && owaStoreObjectId.IsOtherMailbox)
                    {
                        ADSessionSettings adSettings        = Utilities.CreateScopedADSessionSettings(base.UserContext.LogonIdentity.DomainName);
                        ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromLegacyDN(adSettings, owaStoreObjectId.MailboxOwnerLegacyDN);
                        task[TaskSchema.TaskOwner] = exchangePrincipal.MailboxInfo.DisplayName;
                    }
                    else
                    {
                        task[TaskSchema.TaskOwner] = base.UserContext.ExchangePrincipal.MailboxInfo.DisplayName;
                    }
                }
                if (base.IsParameterSet("subj"))
                {
                    task.Subject = (string)base.GetParameter("subj");
                }
                if (base.IsParameterSet("sd"))
                {
                    task.StartDate = this.GetDateValue("sd");
                }
                if (base.IsParameterSet("dd"))
                {
                    task.DueDate = this.GetDateValue("dd");
                }
                if (base.IsParameterSet("dc"))
                {
                    exDateTime = this.GetDateValue("dc");
                    if (exDateTime != null)
                    {
                        flag2 = true;
                    }
                }
                if (base.IsParameterSet("st"))
                {
                    TaskStatus taskStatus = (TaskStatus)base.GetParameter("st");
                    if (taskStatus == TaskStatus.Completed)
                    {
                        flag2 = true;
                    }
                    else
                    {
                        TaskUtilities.SetIncomplete(task, taskStatus);
                    }
                }
                if (base.IsParameterSet("pri"))
                {
                    task[ItemSchema.Importance] = (Importance)base.GetParameter("pri");
                }
                if (base.IsParameterSet("pc"))
                {
                    double num = (double)((int)base.GetParameter("pc")) / 100.0;
                    if (!flag2 || num != 1.0)
                    {
                        if (num >= 0.0 && num < 1.0)
                        {
                            task.PercentComplete = num;
                        }
                        else if (num == 1.0)
                        {
                            flag2 = true;
                        }
                    }
                }
                if (base.IsParameterSet("rs"))
                {
                    bool flag4 = (bool)base.GetParameter("rs");
                    task[ItemSchema.ReminderIsSet] = flag4;
                    if (flag4 && base.IsParameterSet("rd"))
                    {
                        ExDateTime?dateValue = this.GetDateValue("rd");
                        if (dateValue != null)
                        {
                            task[ItemSchema.ReminderDueBy] = dateValue.Value;
                        }
                    }
                }
                if (base.IsParameterSet("ps"))
                {
                    task[ItemSchema.Sensitivity] = (((bool)base.GetParameter("ps")) ? Sensitivity.Private : Sensitivity.Normal);
                }
                if (base.IsParameterSet("tw"))
                {
                    int num2 = (int)base.GetParameter("tw");
                    if (num2 < 0 || num2 > 1525252319)
                    {
                        throw new OwaInvalidRequestException(LocalizedStrings.GetNonEncoded(-1310086288));
                    }
                    task[TaskSchema.TotalWork] = num2;
                }
                if (base.IsParameterSet("aw"))
                {
                    int num3 = (int)base.GetParameter("aw");
                    if (num3 < 0 || num3 > 1525252319)
                    {
                        throw new OwaInvalidRequestException(LocalizedStrings.GetNonEncoded(210380742));
                    }
                    task[TaskSchema.ActualWork] = num3;
                }
                if (base.IsParameterSet("mi"))
                {
                    task[TaskSchema.Mileage] = (string)base.GetParameter("mi");
                }
                if (base.IsParameterSet("bl"))
                {
                    task[TaskSchema.BillingInformation] = (string)base.GetParameter("bl");
                }
                if (base.IsParameterSet("co"))
                {
                    string   text = (string)base.GetParameter("co");
                    string[] value;
                    if (string.IsNullOrEmpty(text))
                    {
                        value = new string[0];
                    }
                    else
                    {
                        value = new string[]
                        {
                            text
                        };
                    }
                    task[TaskSchema.Companies] = value;
                }
                if (base.IsParameterSet("nt"))
                {
                    string text2 = (string)base.GetParameter("nt");
                    if (text2 != null)
                    {
                        BodyConversionUtilities.SetBody(task, text2, Markup.PlainText, base.UserContext);
                    }
                }
                if (base.IsParameterSet("RcrT"))
                {
                    Recurrence recurrence = base.CreateRecurrenceFromRequest();
                    if ((recurrence != null || task.Recurrence != null) && (recurrence == null || task.Recurrence == null || !recurrence.Equals(task.Recurrence)))
                    {
                        task.Recurrence = recurrence;
                        flag3           = true;
                    }
                }
                if (flag2 && exDateTime == null)
                {
                    if (task.CompleteDate == null)
                    {
                        exDateTime = new ExDateTime?(DateTimeUtilities.GetLocalTime());
                    }
                    else
                    {
                        exDateTime = new ExDateTime?(task.CompleteDate.Value);
                    }
                }
                if (!flag3 && flag2)
                {
                    task.SetStatusCompleted(exDateTime.Value);
                }
                Utilities.SaveItem(task, flag);
                task.Load();
                if (flag3 && flag2)
                {
                    OwaStoreObjectId owaStoreObjectId2 = OwaStoreObjectId.CreateFromStoreObject(task);
                    string           changeKey         = task.Id.ChangeKeyAsBase64String();
                    task.Dispose();
                    task = Utilities.GetItem <Task>(base.UserContext, owaStoreObjectId2, changeKey, TaskUtilities.TaskPrefetchProperties);
                    task.SetStatusCompleted(exDateTime.Value);
                    Utilities.SaveItem(task);
                    task.Load();
                }
                if (!flag)
                {
                    OwaStoreObjectId owaStoreObjectId3 = OwaStoreObjectId.CreateFromStoreObject(task);
                    if (ExTraceGlobals.TasksDataTracer.IsTraceEnabled(TraceType.DebugTrace))
                    {
                        ExTraceGlobals.TasksDataTracer.TraceDebug <string>((long)this.GetHashCode(), "New task item ID is '{0}'", owaStoreObjectId3.ToBase64String());
                    }
                    this.Writer.Write("<div id=itemId>");
                    this.Writer.Write(owaStoreObjectId3.ToBase64String());
                    this.Writer.Write("</div>");
                }
                this.Writer.Write("<div id=ck>");
                this.Writer.Write(task.Id.ChangeKeyAsBase64String());
                this.Writer.Write("</div>");
                base.MoveItemToDestinationFolderIfInScratchPad(task);
            }
            finally
            {
                task.Dispose();
            }
        }
Пример #17
0
        private static AutoscaleSettingResource CreateAutoscaleSetting(string location, string resourceUri, string metricName)
        {
            var capacity = new ScaleCapacity()
            {
                DefaultProperty = "1",
                Maximum         = "10",
                Minimum         = "1"
            };

            var fixedDate = new TimeWindow()
            {
                End      = DateTime.Parse("2014-04-16T21:06:11.7882792Z"),
                Start    = DateTime.Parse("2014-04-15T21:06:11.7882792Z"),
                TimeZone = TimeZoneInfo.Utc.Id.ToString()
            };

            var recurrence = new Recurrence()
            {
                Frequency = RecurrenceFrequency.Week,
                Schedule  = new RecurrentSchedule()
                {
                    Days = new List <string> {
                        "Monday"
                    },
                    Hours = new List <int?> {
                        0
                    },
                    Minutes = new List <int?> {
                        10
                    },
                    TimeZone = "UTC-11"
                }
            };

            var rules = new ScaleRule[]
            {
                new ScaleRule()
                {
                    MetricTrigger = new MetricTrigger
                    {
                        MetricName        = metricName,
                        MetricResourceUri = resourceUri,
                        Statistic         = MetricStatisticType.Average,
                        Threshold         = 80.0,
                        TimeAggregation   = TimeAggregationType.Maximum,
                        TimeGrain         = TimeSpan.FromMinutes(1),
                        TimeWindow        = TimeSpan.FromHours(1)
                    },
                    ScaleAction = new ScaleAction
                    {
                        Cooldown  = TimeSpan.FromMinutes(20),
                        Direction = ScaleDirection.Increase,
                        Value     = "1",
                        Type      = ScaleType.ChangeCount
                    }
                }
            };

            var profiles = new AutoscaleProfile[]
            {
                new AutoscaleProfile()
                {
                    Name       = "Profile1",
                    Capacity   = capacity,
                    FixedDate  = fixedDate,
                    Recurrence = null,
                    Rules      = rules
                },
                new AutoscaleProfile()
                {
                    Name       = "Profile2",
                    Capacity   = capacity,
                    FixedDate  = null,
                    Recurrence = recurrence,
                    Rules      = rules
                }
            };

            AutoscaleSettingResource setting = new AutoscaleSettingResource(location: Location, profiles: profiles, name: SettingName)
            {
                AutoscaleSettingResourceName = SettingName,
                TargetResourceUri            = resourceUri,
                Enabled       = true,
                Tags          = null,
                Notifications = null
            };

            return(setting);
        }
        private AutoscaleSettingResource CreateAutoscale(
            string location,
            string resourceUri,
            string metricName,
            string vmssASMin,
            string vmssASMax)
        {
            var capacity = new ScaleCapacity()
            {
                DefaultProperty = "1",
                Maximum         = vmssASMax,
                Minimum         = vmssASMin
            };

            var recurrence = new Recurrence()
            {
                Frequency = RecurrenceFrequency.Week,
                Schedule  = new RecurrentSchedule()
                {
                    Days = new List <string> {
                        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
                    },
                    Hours = new List <int?> {
                        0
                    },
                    Minutes = new List <int?> {
                        10
                    },
                    TimeZone = "UTC-11"
                }
            };

            var rules = new ScaleRule[]
            {
                new ScaleRule()
                {
                    MetricTrigger = new MetricTrigger
                    {
                        MetricName        = metricName,
                        MetricResourceUri = resourceUri,
                        Statistic         = MetricStatisticType.Average,
                        Threshold         = 80.0,
                        OperatorProperty  = ComparisonOperationType.GreaterThan,
                        TimeAggregation   = TimeAggregationType.Maximum,
                        TimeGrain         = TimeSpan.FromMinutes(1),
                        TimeWindow        = TimeSpan.FromHours(1)
                    },
                    ScaleAction = new ScaleAction
                    {
                        Cooldown  = TimeSpan.FromMinutes(20),
                        Direction = ScaleDirection.Increase,
                        Value     = "10"
                    }
                },

                new ScaleRule()
                {
                    MetricTrigger = new MetricTrigger
                    {
                        MetricName        = metricName,
                        MetricResourceUri = resourceUri,
                        Statistic         = MetricStatisticType.Average,
                        Threshold         = 30.0,
                        OperatorProperty  = ComparisonOperationType.LessThan,
                        TimeAggregation   = TimeAggregationType.Maximum,
                        TimeGrain         = TimeSpan.FromMinutes(1),
                        TimeWindow        = TimeSpan.FromHours(1)
                    },
                    ScaleAction = new ScaleAction
                    {
                        Cooldown  = TimeSpan.FromMinutes(20),
                        Direction = ScaleDirection.Decrease,
                        Value     = "2"
                    }
                }
            };

            AutoscaleSettingResource setting = new AutoscaleSettingResource
            {
                Name = TestUtilities.GenerateName("autoscale"),
                AutoscaleSettingResourceName = "setting1",
                TargetResourceUri            = resourceUri,
                Enabled  = true,
                Profiles = new AutoscaleProfile[]
                {
                    new AutoscaleProfile()
                    {
                        Name       = TestUtilities.GenerateName("profile"),
                        Capacity   = capacity,
                        FixedDate  = null,
                        Recurrence = recurrence,
                        Rules      = rules
                    }
                },
                Location      = location,
                Tags          = null,
                Notifications = null
            };

            return(setting);
        }
Пример #19
0
        /// <summary>
        /// Computes Y{v}(x), where v is an integer
        /// </summary>
        /// <param name="v">Integer order</param>
        /// <param name="x">Argument. Requires x &gt; 0</param>
        /// <returns></returns>
        public static DoubleX YN(double v, double x)
        {
            if ((x == 0) && (v == 0))
            {
                return(double.NegativeInfinity);
            }
            if (x <= 0)
            {
                Policies.ReportDomainError("BesselY(v: {0}, x: {1}): Complex number result not supported. Requires x >= 0", v, x);
                return(double.NaN);
            }


            //
            // Reflection comes first:
            //

            double sign = 1;

            if (v < 0)
            {
                // Y_{-n}(z) = (-1)^n Y_n(z)
                if (Math2.IsOdd(v))
                {
                    sign = -1;
                }
                v = -v;
            }

            Debug.Assert(v >= 0 && x >= 0);

            if (v > int.MaxValue)
            {
                Policies.ReportNotImplementedError("BesselY(v: {0}, x: {1}): Large integer values not yet implemented", v, x);
                return(double.NaN);
            }

            int n = (int)v;

            if (n == 0)
            {
                return(Y0(x));
            }

            if (n == 1)
            {
                return(sign * Y1(x));
            }

            if (x < DoubleLimits.RootMachineEpsilon._2)
            {
                DoubleX smallArgValue = YN_SmallArg(n, x);
                return(smallArgValue * sign);
            }

            // if v > MinAsymptoticV, use the asymptotics
            const int MinAsymptoticV = 7; // arbitrary constant to reduce iterations

            if (v > MinAsymptoticV)
            {
                double  Jv;
                DoubleX Yv;
                if (JY_TryAsymptotics(v, x, out Jv, out Yv, false, true))
                {
                    return(sign * Yv);
                }
            }


            // forward recurrence always OK (though unstable)
            double prev    = Y0(x);
            double current = Y1(x);

            var(Yvpn, Yvpnm1, YScale) = Recurrence.ForwardJY_B(1.0, x, n - 1, current, prev);

            return(DoubleX.Ldexp(sign * Yvpn, YScale));
        }
        // Token: 0x060001CB RID: 459 RVA: 0x00011324 File Offset: 0x0000F524
        private static Recurrence CreateRecurrenceFromRequest(HttpRequest request, ExDateTime startDate, UserContext userContext)
        {
            OwaRecurrenceType newRecurrenceTypeFromPost = EditRecurrencePreFormAction.GetNewRecurrenceTypeFromPost(request);
            RecurrencePattern pattern           = null;
            Recurrence        result            = null;
            DaysOfWeek        defaultDaysOfWeek = CalendarUtilities.ConvertDateTimeToDaysOfWeek(startDate);
            int defaultValue = CalendarUtilities.ComputeDayOfMonthOrder(startDate);
            OwaRecurrenceType owaRecurrenceType = newRecurrenceTypeFromPost;

            if (owaRecurrenceType <= OwaRecurrenceType.Yearly)
            {
                switch (owaRecurrenceType)
                {
                case OwaRecurrenceType.Daily:
                {
                    int num = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtinterval", 1);
                    num     = Math.Max(1, num);
                    pattern = new DailyRecurrencePattern(num);
                    break;
                }

                case OwaRecurrenceType.None | OwaRecurrenceType.Daily:
                    break;

                case OwaRecurrenceType.Weekly:
                {
                    int num = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtinterval", 1);
                    num     = Math.Max(1, num);
                    pattern = new WeeklyRecurrencePattern(EditRecurrencePreFormAction.ParseDayCheckboxes(request, defaultDaysOfWeek), num);
                    break;
                }

                default:
                    if (owaRecurrenceType != OwaRecurrenceType.Monthly)
                    {
                        if (owaRecurrenceType == OwaRecurrenceType.Yearly)
                        {
                            int num2             = EditRecurrencePreFormAction.GetIntFormParameter(request, "selRcrYD", startDate.Day);
                            int intFormParameter = EditRecurrencePreFormAction.GetIntFormParameter(request, "selRcrYM", startDate.Month);
                            num2    = Math.Min(ExDateTime.DaysInMonth(startDate.Year, intFormParameter), num2);
                            pattern = new YearlyRecurrencePattern(num2, intFormParameter);
                        }
                    }
                    else
                    {
                        int num2 = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtRcrMD", startDate.Day);
                        int num  = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtRcrMM", 1);
                        num     = Math.Max(1, num);
                        pattern = new MonthlyRecurrencePattern(num2, num);
                    }
                    break;
                }
            }
            else if (owaRecurrenceType != (OwaRecurrenceType.Daily | OwaRecurrenceType.DailyEveryWeekday))
            {
                if (owaRecurrenceType != (OwaRecurrenceType.Monthly | OwaRecurrenceType.MonthlyTh))
                {
                    if (owaRecurrenceType == (OwaRecurrenceType.Yearly | OwaRecurrenceType.YearlyTh))
                    {
                        int        intFormParameter2 = EditRecurrencePreFormAction.GetIntFormParameter(request, "selRcrYTI", defaultValue);
                        int        intFormParameter  = EditRecurrencePreFormAction.GetIntFormParameter(request, "selRcrYTM", startDate.Month);
                        DaysOfWeek daysOfWeek        = EditRecurrencePreFormAction.ParseDaysOfWeek(request, "selRcrThD", defaultDaysOfWeek);
                        pattern = new YearlyThRecurrencePattern(daysOfWeek, (RecurrenceOrderType)intFormParameter2, intFormParameter);
                    }
                }
                else
                {
                    int intFormParameter2 = EditRecurrencePreFormAction.GetIntFormParameter(request, "selRcrYTI", defaultValue);
                    int num = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtRcrMThM", 1);
                    num = Math.Max(1, num);
                    DaysOfWeek daysOfWeek = EditRecurrencePreFormAction.ParseDaysOfWeek(request, "selRcrThD", defaultDaysOfWeek);
                    pattern = new MonthlyThRecurrencePattern(daysOfWeek, (RecurrenceOrderType)intFormParameter2, num);
                }
            }
            else
            {
                pattern = new WeeklyRecurrencePattern(DaysOfWeek.Weekdays);
            }
            if (newRecurrenceTypeFromPost != OwaRecurrenceType.None)
            {
                if (startDate == ExDateTime.MinValue)
                {
                    startDate = CalendarUtilities.ParseDateTimeFromForm(request, "selSY", "selSM", "selSD", null, userContext);
                }
                RecurrenceRange range;
                switch (EditRecurrencePreFormAction.GetRecurrenceRangeTypeFromPost(request))
                {
                case RecurrenceRangeType.Numbered:
                {
                    int num3 = EditRecurrencePreFormAction.GetIntFormParameter(request, "txtno", 10);
                    num3  = Math.Max(1, num3);
                    range = new NumberedRecurrenceRange(startDate, num3);
                    goto IL_284;
                }

                case RecurrenceRangeType.EndDate:
                {
                    ExDateTime exDateTime = CalendarUtilities.ParseDateTimeFromForm(request, "selEY", "selEM", "selED", null, userContext);
                    if (exDateTime < startDate)
                    {
                        exDateTime = startDate.IncrementDays(10);
                    }
                    range = new EndDateRecurrenceRange(startDate, exDateTime);
                    goto IL_284;
                }
                }
                range = new NoEndRecurrenceRange(startDate);
IL_284:
                result = new Recurrence(pattern, range);
            }
            return(result);
        }
Пример #21
0
        /// <summary>
        /// Creates or updates recurrence on the object.
        /// <para>Podio API Reference: https://developers.podio.com/doc/recurrence/create-or-update-recurrence-3349957 </para>
        /// </summary>
        /// <param name="refType">Type of the reference.</param>
        /// <param name="refId">The reference identifier.</param>
        /// <param name="recurrence">The recurrence.</param>
        /// <returns>Task.</returns>
        public Task UpdateRecurrence(string refType, int refId, Recurrence recurrence)
        {
            string url = string.Format("/recurrence/{0}/{1}", refType, refId);

            return(_podio.PutAsync <dynamic>(url, recurrence));
        }
Пример #22
0
        //=====================================================================

        /// <summary>
        /// This is called to get the values from the controls and set them in the specified recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence object to which the settings are applied</param>
        /// <remarks>It is assumed that the recurrence object has been reset to a default state</remarks>
        public void GetValues(Recurrence recurrence)
        {
            if(recurrence.Frequency == RecurFrequency.Hourly)
                recurrence.Interval = (int)udcHours.Value;
        }
Пример #23
0
        /// <summary>
        /// Setups the recurrence.
        /// </summary>
        /// <param name="recurrence">The recurrence.</param>
        internal override void SetupRecurrence(Recurrence recurrence)
        {
            base.SetupRecurrence(recurrence);

            recurrence.NeverEnds();
        }
Пример #24
0
        public void saveEvent()
        {
            Task       task       = null;
            Recurrence recurrence = null;
            Reminder   reminder   = null;
            string     success    = "Event saved successfully.";
            string     error      = "Event was not saved.";

            int taskID = Convert.ToInt32(hf_taskID.Value);

            int clientID = SessionHelper.getClientId();

            if (taskID > 0)
            {
                // edit
                task = TasksManager.Get(taskID);
            }
            else
            {
                // new
                task            = new Task();
                task.creator_id = clientID;
                task.TaskType   = 2;                    // save task as an event
                task.status_id  = 1;
            }

            if (task != null)
            {
                try {
                    task.text             = txtSubject.Text.Trim();
                    task.details          = txtDescription.Text.Trim();
                    task.start_date       = txtEventDateTimeStart.Date;
                    task.end_date         = txtEventDateTimeEnd.Date;
                    task.owner_id         = Convert.ToInt32(ddlOwner.SelectedValue);
                    task.ReminderInterval = Convert.ToInt32(ddlReminderWhen.SelectedValue);

                    using (TransactionScope scope = new TransactionScope()) {
                        taskID = TasksManager.Save(task);

                        hf_taskID.Value = taskID.ToString();

                        // reminder
                        if (ddlReminderWhen.SelectedIndex > 0 && task.Reminder != null && task.Reminder.Count == 0)
                        {
                            // new reminder
                            reminder        = new Reminder();
                            reminder.TaskID = taskID;

                            saveReminder(reminder);
                        }
                        else if (ddlReminderWhen.SelectedIndex > 0 && task.Reminder != null && task.Reminder.Count == 1)
                        {
                            // edit existing reminder
                            reminder = task.Reminder.FirstOrDefault();

                            saveReminder(reminder);
                        }
                        else if (ddlReminderWhen.SelectedIndex == 0 && task.Reminder != null && task.Reminder.Count == 1 && ViewState["ReminderID"] != null)
                        {
                            // delete reminder
                            ReminderManager.Delete(Convert.ToInt32(ViewState["ReminderID"]));
                        }

                        // recurring
                        if (!string.IsNullOrEmpty(txtRecurrenceStartDate.Text) && task.Recurrence == null)
                        {
                            // new recurrence
                            recurrence        = new Recurrence();
                            recurrence.TaskID = taskID;

                            saveRecurrence(recurrence);
                        }
                        else if (!string.IsNullOrEmpty(txtRecurrenceStartDate.Text) && task.Recurrence != null)
                        {
                            // edit recurrence
                            recurrence = (Recurrence)task.Recurrence;

                            saveRecurrence(recurrence);
                        }
                        else if (string.IsNullOrEmpty(txtRecurrenceStartDate.Text) && task.Recurrence != null && ViewState["RecurringID"] != null)
                        {
                            // delete recurrence
                            RecurrenceManager.Delete(Convert.ToInt32(ViewState["RecurringID"]));
                        }

                        // commit changes to DB
                        scope.Complete();
                    }

                    // allow user to add invitees
                    pnlInvitees.Visible = true;

                    if (this.Page is CRM.Web.Protected.EventEdit)
                    {
                        ((CRM.Web.Protected.EventEdit) this.Page).setErrorMessage(success, "ok");
                    }
                    else if (this.Page is CRM.Web.Protected.EventEditPopUp)
                    {
                        ((CRM.Web.Protected.EventEditPopUp) this.Page).setErrorMessage(success, "ok");
                    }

                    //lblMessage.Text = "Event saved successfully.";
                    //lblMessage.CssClass = "ok";
                }
                catch (Exception ex) {
                    Core.EmailHelper.emailError(ex);
                    if (this.Page is CRM.Web.Protected.EventEdit)
                    {
                        ((CRM.Web.Protected.EventEdit) this.Page).setErrorMessage(error, "error");
                    }
                    else if (this.Page is CRM.Web.Protected.EventEditPopUp)
                    {
                        ((CRM.Web.Protected.EventEditPopUp) this.Page).setErrorMessage(error, "error");
                    }

                    //lblMessage.Text = "Event was not saved.";
                    //lblMessage.CssClass = "error";
                }
            }
        }
Пример #25
0
        //=====================================================================

        /// <summary>
        /// This is used to retrieve the recurrence information into the passed recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence in which to store the settings</param>
        /// <exception cref="ArgumentNullException">This is thrown if the passed recurrence object is null</exception>
        public void GetRecurrence(Recurrence recurrence)
        {
            Recurrence r = new Recurrence();

            if (recurrence == null)
            {
                throw new ArgumentNullException("recurrence", LR.GetString("ExRPRecurrenceIsNull"));
            }

            // Get the basic stuff
            r.Reset();
            r.WeekStart         = (DayOfWeek)cboWeekStartDay.SelectedValue;
            r.CanOccurOnHoliday = chkHolidays.Checked;

            r.Frequency = rbYearly.Checked ? RecurFrequency.Yearly :
                          rbMonthly.Checked ? RecurFrequency.Monthly :
                          rbWeekly.Checked ? RecurFrequency.Weekly :
                          rbDaily.Checked ? RecurFrequency.Daily :
                          rbHourly.Checked ? RecurFrequency.Hourly :
                          rbMinutely.Checked ? RecurFrequency.Minutely : RecurFrequency.Secondly;

            if (rbEndAfter.Checked)
            {
                r.MaximumOccurrences = (int)udcOccurrences.Value;
            }
            else
            if (rbEndByDate.Checked)
            {
                if (this.ShowEndTime)
                {
                    r.RecurUntil = dtpEndDate.Value;
                }
                else
                {
                    r.RecurUntil = dtpEndDate.Value.Date;
                }
            }

            // Get the frequency-specific stuff
            if (chkAdvanced.Checked)
            {
                ucAdvanced.GetValues(r);
            }
            else
            if (rbYearly.Checked)
            {
                ucYearly.GetValues(r);
            }
            else
            if (rbMonthly.Checked)
            {
                ucMonthly.GetValues(r);
            }
            else
            if (rbWeekly.Checked)
            {
                ucWeekly.GetValues(r);
            }
            else
            if (rbDaily.Checked)
            {
                ucDaily.GetValues(r);
            }
            else
            if (rbHourly.Checked)
            {
                ucHourly.GetValues(r);
            }
            else
            if (rbMinutely.Checked)
            {
                ucMinutely.GetValues(r);
            }
            else
            {
                ucSecondly.GetValues(r);
            }

            recurrence.Parse(r.ToString());
        }
Пример #26
0
        /// <summary>
        /// This is called to set the values for the controls based on the current recurrence settings
        /// </summary>
        /// <param name="recurrence">The recurrence object from which to get the settings</param>
        public void SetValues(Recurrence recurrence)
        {
            DaysOfWeek rd = DaysOfWeek.None;

            rbDayXEveryYYears.Checked = true;

            // Use default values if not a yearly frequency
            if (recurrence.Frequency != RecurFrequency.Yearly)
            {
                udcDay.Value                  = udcYears.Value = udcDOWYears.Value = 1;
                cboMonth.SelectedIndex        = cboOccurrence.SelectedIndex = cboDOW.SelectedIndex =
                    cboDOWMonth.SelectedIndex = 0;
            }
            else
            {
                if (recurrence.ByDay.Count == 0)
                {
                    if (recurrence.ByMonth.Count != 0)
                    {
                        cboMonth.SelectedValue = recurrence.ByMonth[0];
                    }
                    else
                    {
                        cboMonth.SelectedValue = recurrence.StartDateTime.Month;
                    }

                    if (recurrence.ByMonthDay.Count != 0)
                    {
                        udcDay.Value = recurrence.ByMonthDay[0];
                    }
                    else
                    {
                        udcDay.Value = recurrence.StartDateTime.Day;
                    }

                    udcYears.Value = (recurrence.Interval < 1000) ? recurrence.Interval : 999;

                    cboOccurrence.SelectedIndex = cboDOW.SelectedIndex = cboDOWMonth.SelectedIndex = 0;
                    udcDOWYears.Value           = 1;
                }
                else
                {
                    rbDayOfWeek.Checked = true;

                    udcDay.Value           = udcYears.Value = 1;
                    udcDOWYears.Value      = (recurrence.Interval < 1000) ? recurrence.Interval : 999;
                    cboMonth.SelectedIndex = 0;

                    if (recurrence.ByMonth.Count != 0)
                    {
                        cboDOWMonth.SelectedValue = recurrence.ByMonth[0];
                    }
                    else
                    {
                        cboDOWMonth.SelectedValue = recurrence.StartDateTime.Month;
                    }

                    // If it's a single day, use ByDay.  If it's a combination, use ByDay with BySetPos.
                    if (recurrence.ByDay.Count == 1)
                    {
                        cboOccurrence.SelectedValue = (recurrence.ByDay[0].Instance < 1 ||
                                                       recurrence.ByDay[0].Instance > 4) ? DayOccurrence.Last :
                                                      (DayOccurrence)recurrence.ByDay[0].Instance;

                        cboDOW.SelectedValue = DateUtils.ToDaysOfWeek(recurrence.ByDay[0].DayOfWeek);
                    }
                    else
                    {
                        if (recurrence.BySetPos.Count == 0)
                        {
                            cboOccurrence.SelectedIndex = 0;
                        }
                        else
                        {
                            cboOccurrence.SelectedValue = (recurrence.BySetPos[0] < 1 ||
                                                           recurrence.BySetPos[0] > 4) ? DayOccurrence.Last :
                                                          (DayOccurrence)recurrence.BySetPos[0];
                        }

                        // Figure out days
                        foreach (DayInstance di in recurrence.ByDay)
                        {
                            switch (di.DayOfWeek)
                            {
                            case DayOfWeek.Sunday:
                                rd |= DaysOfWeek.Sunday;
                                break;

                            case DayOfWeek.Monday:
                                rd |= DaysOfWeek.Monday;
                                break;

                            case DayOfWeek.Tuesday:
                                rd |= DaysOfWeek.Tuesday;
                                break;

                            case DayOfWeek.Wednesday:
                                rd |= DaysOfWeek.Wednesday;
                                break;

                            case DayOfWeek.Thursday:
                                rd |= DaysOfWeek.Thursday;
                                break;

                            case DayOfWeek.Friday:
                                rd |= DaysOfWeek.Friday;
                                break;

                            case DayOfWeek.Saturday:
                                rd |= DaysOfWeek.Saturday;
                                break;
                            }
                        }

                        // If not EveryDay, Weekdays, or Weekends, force it to a single day of the week
                        if (rd == DaysOfWeek.None || (rd != DaysOfWeek.EveryDay && rd != DaysOfWeek.Weekdays &&
                                                      rd != DaysOfWeek.Weekends))
                        {
                            rd = DateUtils.ToDaysOfWeek(DateUtils.ToDayOfWeek(rd));
                        }

                        cboDOW.SelectedValue = rd;
                    }
                }
            }
        }
Пример #27
0
 /// <summary>
 /// This is used to expand the hourly frequency by second
 /// </summary>
 /// <param name="r">A reference to the recurrence</param>
 /// <param name="dates">A reference to the collection of current instances that have been generated</param>
 /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
 /// checked as there's nothing else to do.</returns>
 public int BySecond(Recurrence r, RecurDateTimeCollection dates)
 {
     return(Expand.BySecond(r, dates));
 }
Пример #28
0
        /// <summary>
        /// Generate instances for the specified recurrence pattern
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event parameters</param>
        protected void btnTest_Click(object sender, EventArgs e)
        {
            DateTimeCollection dc;
            DateTime           dt;
            int    start;
            double elapsed;

            try
            {
                lblCount.Text = lblDescription.Text = String.Empty;

                if (!DateTime.TryParse(txtStartDate.Text, CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    lblCount.Text = "Invalid date/time or RRULE format";
                    return;
                }

                // Define the recurrence rule by parsing the text
                Recurrence r = new Recurrence(txtRRULE.Text);
                r.StartDateTime = dt;

                // Synch the pattern control to the RRULE if not called by the pattern's test button
                if (sender != btnTestPattern)
                {
                    rpRecurrence.SetRecurrence(r);
                }

                // Use some limitations to prevent overloading the server or timing out the page if possible
                if (r.Frequency > RecurFrequency.Hourly && (r.MaximumOccurrences == 0 || r.MaximumOccurrences > 5000))
                {
                    r.MaximumOccurrences = 5000;
                    txtRRULE.Text        = r.ToString();
                }

                if (r.MaximumOccurrences != 0)
                {
                    if (r.MaximumOccurrences > 5000)
                    {
                        r.MaximumOccurrences = 5000;
                        txtRRULE.Text        = r.ToString();
                    }
                }
                else
                if (r.Frequency == RecurFrequency.Hourly)
                {
                    if (r.RecurUntil > r.StartDateTime.AddYears(5))
                    {
                        r.RecurUntil  = r.StartDateTime.AddYears(5);
                        txtRRULE.Text = r.ToString();
                    }
                }
                else
                if (r.RecurUntil > r.StartDateTime.AddYears(50))
                {
                    r.RecurUntil  = r.StartDateTime.AddYears(50);
                    txtRRULE.Text = r.ToString();
                }

                // Time the calculation
                start   = System.Environment.TickCount;
                dc      = r.InstancesBetween(r.StartDateTime, DateTime.MaxValue);
                elapsed = (System.Environment.TickCount - start) / 1000.0;

                // Bind the results to the list box
                lbResults.DataSource = dc;
                lbResults.DataBind();

                lblCount.Text = String.Format("Found {0:N0} instances in {1:N2} " +
                                              "seconds ({2:N2} instances/second)", dc.Count, elapsed, dc.Count / elapsed);

                // Show a description of the pattern
                lblDescription.Text = r.ToDescription();
            }
            catch (Exception ex)
            {
                lblCount.Text = ex.Message;
            }
        }
Пример #29
0
        public static void AddRecurrence(
			int EventId,
			int StartTime, int EndTime,
			byte Pattern, byte SubPattern,
			byte Frequency, byte Weekdays,
			byte DayOfMonth, byte weekNumber,
			byte MonthNumber, int EndAfter,
			DateTime StartDate, DateTime FinishDate,
			int TimeZoneId)
        {
            if (!CanUpdate(EventId))
                throw new AccessDeniedException();

            if (Pattern < 4 && Frequency <= 0)
                throw new WrongDataException();

            DateTime eventStartDate = DateTime.UtcNow;
            using (IDataReader reader = GetEvent(EventId, false, true))
            {
                if (reader.Read())
                    eventStartDate = (DateTime)reader["StartDate"];
            }

            DateTime RecStartDate = StartDate;
            DateTime RecFinishDate = FinishDate;
            StartDate = DBCommon.GetUTCDate(TimeZoneId, StartDate);		// to UTC
            FinishDate = DBCommon.GetUTCDate(TimeZoneId, FinishDate);	// to UTC

            if (EndAfter > 0)		// end after N occurrences
            {
                // Recalculating FinishDate
                Recurrence recurrence = new Recurrence(Pattern, SubPattern, Frequency, Weekdays, DayOfMonth, weekNumber, MonthNumber, EndAfter, RecStartDate, RecFinishDate, TimeZoneId);
                ArrayList dates = GetRecurDates(StartDate, StartDate.AddYears(100), StartTime, eventStartDate, recurrence, 1, Disposition.Last);
                if (dates.Count > 0)
                    FinishDate = (DateTime)dates[0];		// Finish is in UTC format
            }

            StartDate = StartDate.AddMinutes(StartTime);
            FinishDate = FinishDate.AddMinutes(EndTime);

            int UserId = Security.CurrentUser.UserID;

            int ReminderInterval;

            using (DbTransaction tran = DbTransaction.Begin())
            {
                DBCommon.AddRecurrence((int)CALENDAR_ENTRY_TYPE, EventId, StartTime, EndTime, Pattern, SubPattern, Frequency, Weekdays, DayOfMonth, weekNumber, MonthNumber, EndAfter, TimeZoneId);
                DbCalendarEntry2.UpdateTimeline(EventId, StartDate, FinishDate, EndTime - StartTime);

                Schedule.DeleteDateTypeValue(DateTypes.CalendarEntry_StartDate, EventId);
                Schedule.DeleteDateTypeValue(DateTypes.CalendarEntry_FinishDate, EventId);

                Hashtable ret = GetEventInstances(EventId, out ReminderInterval);
                foreach (DateTime dtStart in ret.Keys)
                {
                    DateTime dtEnd = (DateTime)ret[dtStart];
                    if (dtStart > DateTime.UtcNow && dtEnd > DateTime.UtcNow)
                    {
                        DbSchedule2.AddNewDateTypeValue((int)DateTypes.CalendarEntry_StartDate, EventId, dtStart);
                        DbSchedule2.AddNewDateTypeValue((int)DateTypes.CalendarEntry_FinishDate, EventId, dtEnd);
                    }
                }

                // O.R. [2009-12-18] Timeline = duration * count
                DbCalendarEntry2.UpdateTimeline(EventId, StartDate, FinishDate, (EndTime - StartTime) * ret.Count);

                RecalculateState(EventId);

                tran.Commit();
            }
        }
Пример #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string[] uris;
            string   povtoruvanje = "";
            mwGoogleEvent.ActiveViewIndex = 0;



            if ((Request.QueryString["token"] != null) && Session["sessionToken"] == null)
            {
                Session["sessionToken"] = AuthSubUtil.exchangeForSessionToken(Request.QueryString["token"], null);
            }
            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "FEITPortal");
            authFactory.Token = (string)Session["sessionToken"];
            myCalendarService.RequestFactory = authFactory;
            CalendarQuery query = new CalendarQuery();
            query.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
            try
            {
                CalendarFeed resultFeed = myCalendarService.Query(query);
                foreach (CalendarEntry entry in resultFeed.Entries)
                {
                    uris = entry.Id.Uri.ToString().Split('/');
                    ListItem li = new ListItem();
                    li.Text  = entry.Title.Text;
                    li.Value = uris[8];
                    ddlKalendari.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                hlGcal1.Visible  = true;
                hlNazad1.Visible = true;
                lblGreska.Text   = "Немате креирано Google Calendar";
                mwGoogleEvent.ActiveViewIndex = 3;
            }


            Calendar.COURSE_EVENTS_INSTANCEDataTable nastan = (Calendar.COURSE_EVENTS_INSTANCEDataTable)Session["gNastan"];



            foreach (Calendar.COURSE_EVENTS_INSTANCERow r in nastan)
            {
                CoursesTier CourseTier = new CoursesTier(Convert.ToInt32(Session["COURSE_ID"]));
                novNastan.Content.Language = r.COURSE_EVENT_ID.ToString();
                novNastan.Title.Text       = r.TITLE;
                novNastan.Content.Content  = "Предмет: " + CourseTier.Name + " Опис: " + r.DESCRIPTION + " Тип: " + r.TYPEDESCRIPTION + " ID:" + r.COURSE_EVENT_ID.ToString();
                Where mesto = new Where();
                mesto.ValueString = r.ROOM;
                novNastan.Locations.Add(mesto);
                int recType = Convert.ToInt32(r.RECURRENCE_TYPE);


                DateTime startDate = Convert.ToDateTime(r.STARTDATE);
                DateTime endDate   = Convert.ToDateTime(r.ENDDATE);
                DateTime startTime = Convert.ToDateTime(r.STARTIME);
                DateTime endTime   = Convert.ToDateTime(r.ENDTIME);
                TimeSpan span      = endTime - startTime;

                if (recType != 0)
                {
                    Recurrence rec = new Recurrence();
                    string     recData;
                    string     dStart = "DTSTART;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1).ToString("HHmm") + "00\r\n";
                    string     dEnd   = "DTEND;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1 + span.Hours).ToString("HHmm") + "00\r\n";
                    string     rRule  = "";
                    povtoruvanje = "<b>Повторување:</b> ";

                    switch (recType)
                    {
                    case 1:
                        rRule         = "RRULE:FREQ=DAILY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Дневно, секој " + r.RECURRENCE_NUMBER.ToString() + " ден <br> </br> <br> </br>";
                        break;

                    case 2:
                        string daysInWeek = "";
                        string denovi     = "";

                        if (r.DAYSINWEEK[0] == '1')
                        {
                            daysInWeek += "MO,";
                            denovi     += " Понеделник,";
                        }
                        if (r.DAYSINWEEK[1] == '1')
                        {
                            daysInWeek += "TU,";
                            denovi     += " Вторник,";
                        }
                        if (r.DAYSINWEEK[2] == '1')
                        {
                            daysInWeek += "WE,";
                            denovi     += " Среда,";
                        }
                        if (r.DAYSINWEEK[3] == '1')
                        {
                            daysInWeek += "TH,";
                            denovi     += " Четврток,";
                        }
                        if (r.DAYSINWEEK[4] == '1')
                        {
                            daysInWeek += "FR,";
                            denovi     += " Петок,";
                        }
                        if (r.DAYSINWEEK[5] == '1')
                        {
                            daysInWeek += "SA,";
                            denovi     += " Сабота,";
                        }
                        if (r.DAYSINWEEK[6] == '1')
                        {
                            daysInWeek += "SU,";
                            denovi     += " Недела,";
                        }
                        daysInWeek    = daysInWeek.Substring(0, daysInWeek.Length - 1);
                        denovi        = denovi.Substring(0, denovi.Length - 1);
                        rRule         = "RRULE:FREQ=WEEKLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";BYDAY=" + daysInWeek + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Неделно, секоја " + r.RECURRENCE_NUMBER + " недела и тоа во: " + denovi + " <br> </br> <br> </br>";
                        break;

                    case 3:
                        rRule         = "RRULE:FREQ=MONTHLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Месечно, секој " + r.RECURRENCE_NUMBER + " месец <br> </br> <br> </br>";
                        break;
                    }
                    recData              = dStart + dEnd + rRule;
                    rec.Value            = recData;
                    novNastan.Recurrence = rec;
                }
                else
                {
                    When vreme = new When();
                    vreme.StartTime = r.STARTIME;
                    vreme.EndTime   = r.ENDTIME;
                    novNastan.Times.Add(vreme);
                }


                lblPrikaz.Text += "<b>Наслов: </b>" + r.TITLE + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Опис: </b>" + r.DESCRIPTION + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Просторија: </b>" + r.ROOM + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Тип: </b>" + r.TYPEDESCRIPTION + "<br> </br> <br> </br>";
                lblPrikaz.Text += povtoruvanje;
                lblPrikaz.Text += "<b>Почетен датум: </b>" + startDate.ToShortDateString() + "  <b>Краен датум: </b>" + endDate.ToShortDateString() + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Време: Од </b>" + startTime.ToShortTimeString() + " <b>До</b> " + endTime.ToShortTimeString();
            }
            Session["novNastan"] = novNastan;
        }
    }
Пример #31
0
        public static string GenerateWhen(UserContext userContext, ExDateTime startTime, ExDateTime endTime, Recurrence recurrence)
        {
            string result;

            using (CalendarItem calendarItem = CalendarItem.Create(userContext.MailboxSession, userContext.CalendarFolderId))
            {
                calendarItem.StartTime  = startTime;
                calendarItem.EndTime    = endTime;
                calendarItem.Recurrence = recurrence;
                result = calendarItem.GenerateWhen();
            }
            return(result);
        }
Пример #32
0
        protected Recurrence CreateRecurrenceFromRequest()
        {
            Recurrence result = null;

            if (base.IsParameterSet("RcrT"))
            {
                OwaRecurrenceType owaRecurrenceType  = (OwaRecurrenceType)base.GetParameter("RcrT");
                RecurrencePattern recurrencePattern  = null;
                OwaRecurrenceType owaRecurrenceType2 = owaRecurrenceType;
                if (owaRecurrenceType2 <= (OwaRecurrenceType.Monthly | OwaRecurrenceType.MonthlyTh))
                {
                    if (owaRecurrenceType2 <= OwaRecurrenceType.Monthly)
                    {
                        switch (owaRecurrenceType2)
                        {
                        case OwaRecurrenceType.Daily:
                            recurrencePattern = new DailyRecurrencePattern((int)base.GetParameter("RcrI"));
                            break;

                        case OwaRecurrenceType.None | OwaRecurrenceType.Daily:
                            break;

                        case OwaRecurrenceType.Weekly:
                            recurrencePattern = new WeeklyRecurrencePattern((DaysOfWeek)base.GetParameter("RcrDys"), (int)base.GetParameter("RcrI"));
                            break;

                        default:
                            if (owaRecurrenceType2 == OwaRecurrenceType.Monthly)
                            {
                                recurrencePattern = new MonthlyRecurrencePattern((int)base.GetParameter("RcrDy"), (int)base.GetParameter("RcrI"));
                            }
                            break;
                        }
                    }
                    else if (owaRecurrenceType2 != OwaRecurrenceType.Yearly)
                    {
                        if (owaRecurrenceType2 != (OwaRecurrenceType.Daily | OwaRecurrenceType.DailyEveryWeekday))
                        {
                            if (owaRecurrenceType2 == (OwaRecurrenceType.Monthly | OwaRecurrenceType.MonthlyTh))
                            {
                                recurrencePattern = new MonthlyThRecurrencePattern((DaysOfWeek)base.GetParameter("RcrDys"), (RecurrenceOrderType)base.GetParameter("RcrO"), (int)base.GetParameter("RcrI"));
                            }
                        }
                        else
                        {
                            recurrencePattern = new WeeklyRecurrencePattern(DaysOfWeek.Weekdays);
                        }
                    }
                    else
                    {
                        recurrencePattern = new YearlyRecurrencePattern((int)base.GetParameter("RcrDy"), (int)base.GetParameter("RcrM"));
                    }
                }
                else if (owaRecurrenceType2 <= (OwaRecurrenceType.Daily | OwaRecurrenceType.DailyRegenerating))
                {
                    if (owaRecurrenceType2 != (OwaRecurrenceType.Yearly | OwaRecurrenceType.YearlyTh))
                    {
                        if (owaRecurrenceType2 == (OwaRecurrenceType.Daily | OwaRecurrenceType.DailyRegenerating))
                        {
                            recurrencePattern = new DailyRegeneratingPattern((int)base.GetParameter("RgrI"));
                        }
                    }
                    else
                    {
                        recurrencePattern = new YearlyThRecurrencePattern((DaysOfWeek)base.GetParameter("RcrDys"), (RecurrenceOrderType)base.GetParameter("RcrO"), (int)base.GetParameter("RcrM"));
                    }
                }
                else if (owaRecurrenceType2 != (OwaRecurrenceType.Weekly | OwaRecurrenceType.WeeklyRegenerating))
                {
                    if (owaRecurrenceType2 != (OwaRecurrenceType.Monthly | OwaRecurrenceType.MonthlyRegenerating))
                    {
                        if (owaRecurrenceType2 == (OwaRecurrenceType.Yearly | OwaRecurrenceType.YearlyRegenerating))
                        {
                            recurrencePattern = new YearlyRegeneratingPattern((int)base.GetParameter("RgrI"));
                        }
                    }
                    else
                    {
                        recurrencePattern = new MonthlyRegeneratingPattern((int)base.GetParameter("RgrI"));
                    }
                }
                else
                {
                    recurrencePattern = new WeeklyRegeneratingPattern((int)base.GetParameter("RgrI"));
                }
                if (owaRecurrenceType != OwaRecurrenceType.None)
                {
                    RecurrenceRangeType recurrenceRangeType = (RecurrenceRangeType)base.GetParameter("RcrRngT");
                    ExDateTime          startDate           = (ExDateTime)base.GetParameter("RcrRngS");
                    RecurrenceRange     recurrenceRange;
                    switch (recurrenceRangeType)
                    {
                    case RecurrenceRangeType.Numbered:
                        recurrenceRange = new NumberedRecurrenceRange(startDate, (int)base.GetParameter("RcrRngO"));
                        goto IL_2C8;

                    case RecurrenceRangeType.EndDate:
                        recurrenceRange = new EndDateRecurrenceRange(startDate, (ExDateTime)base.GetParameter("RcrRngE"));
                        goto IL_2C8;
                    }
                    recurrenceRange = new NoEndRecurrenceRange(startDate);
IL_2C8:
                    if (recurrencePattern != null && recurrenceRange != null)
                    {
                        result = new Recurrence(recurrencePattern, recurrenceRange);
                    }
                }
            }
            return(result);
        }
Пример #33
0
 public void UpdateRecurrence(Recurrence recurrence)
 {
     _repository.Recurrence.Update(recurrence);
 }
Пример #34
0
        /// <summary>
        /// This is used to retrieve the recurrence information into the passed recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence in which to store the settings.</param>
        /// <exception cref="ArgumentNullException">This is thrown if the passed recurrence object is null</exception>
        public void GetRecurrence(Recurrence recurrence)
        {
            if(recurrence == null)
                throw new ArgumentNullException("recurrence", LR.GetString("ExRPRecurrenceIsNull"));

            recurrence.Parse(rRecur.ToString());
        }
Пример #35
0
        /// <summary>
        /// This is used to expand one or more months by day of the week.  It is used by the monthly and yearly
        /// frequencies.
        /// </summary>
        /// <param name="r">A reference to the recurrence</param>
        /// <param name="dates">A reference to the collection of current instances that have been generated</param>
        /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
        /// checked as there's nothing else to do.</returns>
        /// <remarks>If an expanded date is invalid, it will be discarded</remarks>
        public static int ByDayInMonths(Recurrence r, RecurDateTimeCollection dates)
        {
            RecurDateTime rdt, rdtNew;
            DayOfWeek     dow;
            int           expIdx, instance, count = dates.Count;

            DayInstanceCollection byDay = r.ByDay;

            // Don't bother if either collection is empty
            if (count != 0 && byDay.Count != 0)
            {
                for (int idx = 0; idx < count; idx++)
                {
                    rdt = dates[0];
                    dates.RemoveAt(0);

                    // Expand the date/time by adding a new entry for each week day instance specified
                    for (expIdx = 0; expIdx < byDay.Count; expIdx++)
                    {
                        instance = byDay[expIdx].Instance;
                        dow      = byDay[expIdx].DayOfWeek;

                        if (instance == 0)
                        {
                            // Expand to every specified day of the week
                            // in the month.
                            rdtNew = new RecurDateTime(rdt)
                            {
                                Day = 1
                            };

                            rdtNew.AddDays(((int)dow + 7 - (int)rdtNew.DayOfWeek) % 7);

                            while (rdtNew.IsValidDate() && rdtNew.Year == rdt.Year && rdtNew.Month == rdt.Month)
                            {
                                dates.Add(new RecurDateTime(rdtNew));
                                rdtNew.AddDays(7);
                            }

                            continue;
                        }

                        if (instance > 0)
                        {
                            // Add the nth instance of the day of the week
                            rdtNew = new RecurDateTime(rdt)
                            {
                                Day = 1
                            };

                            rdtNew.AddDays((((int)dow + 7 - (int)rdtNew.DayOfWeek) % 7) + ((instance - 1) * 7));
                        }
                        else
                        {
                            // Add the nth instance of the day of the week
                            // from the end of the month.
                            rdtNew = new RecurDateTime(rdt)
                            {
                                Day = DateTime.DaysInMonth(rdt.Year, rdt.Month + 1)
                            };

                            rdtNew.AddDays(0 - (((int)rdtNew.DayOfWeek + 7 - (int)dow) % 7) + ((instance + 1) * 7));
                        }

                        // If not in the year, discard it
                        if (rdtNew.Year != rdt.Year || rdtNew.Month != rdt.Month)
                        {
                            continue;
                        }

                        dates.Add(new RecurDateTime(rdtNew));
                    }
                }
            }

            return(dates.Count);
        }
Пример #36
0
        /// <summary>
        /// This is used to initialize the control with settings from an existing recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence from which to get the settings.  If null, it uses a default daily
        /// recurrence pattern.</param>
        public void SetRecurrence(Recurrence recurrence)
        {
            rRecur = new Recurrence();

            if(recurrence == null)
            {
                rRecur.StartDateTime = DateTime.Today;
                rRecur.RecurDaily(1);
            }
            else
            {
                rRecur.Parse(recurrence.ToStringWithStartDateTime());

                // Reset to daily if undefined
                if(rRecur.Frequency == RecurFrequency.Undefined)
                    rRecur.RecurDaily(rRecur.Interval);
            }

            // If the given pattern is not available, set it to the next best pattern
            if(this.MaximumPattern < rRecur.Frequency)
                switch(this.MaximumPattern)
                {
                    case RecurFrequency.Yearly:
                        rRecur.RecurYearly(DateTime.Now.Month, DateTime.Now.Day, rRecur.Interval);
                        break;

                    case RecurFrequency.Monthly:
                        rRecur.RecurMonthly(DateTime.Now.Day, rRecur.Interval);
                        break;

                    case RecurFrequency.Weekly:
                        rRecur.RecurWeekly(rRecur.Interval, DateUtils.ToDaysOfWeek(DateTime.Now.DayOfWeek));
                        break;

                    case RecurFrequency.Daily:
                        rRecur.RecurDaily(rRecur.Interval);
                        break;

                    case RecurFrequency.Hourly:
                        rRecur.RecurDaily(rRecur.Interval);
                        rRecur.Frequency = RecurFrequency.Hourly;
                        break;

                    default:
                        rRecur.RecurDaily(rRecur.Interval);
                        rRecur.Frequency = RecurFrequency.Minutely;
                        break;
                }
        }
Пример #37
0
 /// <summary>
 /// This is used to initialize the dialog box with settings from an existing recurrence object
 /// </summary>
 /// <param name="recurrence">The recurrence from which to get the settings.  If null, it uses a default
 /// daily recurrence pattern.</param>
 public void SetRecurrence(Recurrence recurrence)
 {
     rpRecurrence.SetRecurrence(recurrence);
 }
Пример #38
0
        //=====================================================================

        /// <summary>
        /// This is used to load the recurrence data for the control on post back
        /// </summary>
        /// <param name="postDataKey">The key identifier for the control</param>
        /// <param name="postCollection">The collection of values</param>
        /// <returns>True if the server control's state changes as a result of the postback; otherwise, false</returns>
        public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            string[] options;
            string pattern = null;
            DaysOfWeek daysOfWeek = DaysOfWeek.None;
            int val;

            if(postCollection != null)
                pattern = postCollection[this.ID + "_Value"];

            if(!String.IsNullOrEmpty(pattern))
            {
                // Parse and load the recurrence
                rRecur = new Recurrence();
                options = pattern.Split('\xFF');

                // Parse the pattern options
                if(options[0] == "1")
                    this.ParseAdvancedOptions(options);
                else
                {
                    switch(options[1])
                    {
                        case "1":   // Yearly
                            if(options[2] == "0")
                            {
                                rRecur.RecurYearly(
                                    Convert.ToInt32(options[3], CultureInfo.InvariantCulture) + 1,
                                    Convert.ToInt32(options[4], CultureInfo.InvariantCulture),
                                    Convert.ToInt32(options[5], CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                val = Convert.ToInt32(options[4], CultureInfo.InvariantCulture);

                                if(val < 7)
                                    daysOfWeek = DateUtils.ToDaysOfWeek((DayOfWeek)val);
                                else
                                    if(val == 7)
                                        daysOfWeek = DaysOfWeek.Weekdays;
                                    else
                                        if(val == 8)
                                            daysOfWeek = DaysOfWeek.Weekends;
                                        else
                                            daysOfWeek = DaysOfWeek.EveryDay;

                                val = Convert.ToInt32(options[3], CultureInfo.InvariantCulture) + 1;

                                rRecur.RecurYearly((DayOccurrence)val, daysOfWeek,
                                    Convert.ToInt32(options[5], CultureInfo.InvariantCulture) + 1,
                                    Convert.ToInt32(options[6], CultureInfo.InvariantCulture));
                            }
                            break;

                        case "2":   // Monthly
                            if(options[2] == "0")
                            {
                                rRecur.RecurMonthly(
                                    Convert.ToInt32(options[3], CultureInfo.InvariantCulture),
                                    Convert.ToInt32(options[4], CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                val = Convert.ToInt32(options[4], CultureInfo.InvariantCulture);

                                if(val < 7)
                                    daysOfWeek = DateUtils.ToDaysOfWeek((DayOfWeek)val);
                                else
                                    if(val == 7)
                                        daysOfWeek = DaysOfWeek.Weekdays;
                                    else
                                        if(val == 8)
                                            daysOfWeek = DaysOfWeek.Weekends;
                                        else
                                            daysOfWeek = DaysOfWeek.EveryDay;

                                val = Convert.ToInt32(options[3], CultureInfo.InvariantCulture) + 1;

                                rRecur.RecurMonthly((DayOccurrence)val, daysOfWeek, Convert.ToInt32(options[5],
                                    CultureInfo.InvariantCulture));
                            }
                            break;

                        case "3":   // Weekly
                            if(options[3][0] == '1')
                                daysOfWeek |= DaysOfWeek.Sunday;

                            if(options[3][1] == '1')
                                daysOfWeek |= DaysOfWeek.Monday;

                            if(options[3][2] == '1')
                                daysOfWeek |= DaysOfWeek.Tuesday;

                            if(options[3][3] == '1')
                                daysOfWeek |= DaysOfWeek.Wednesday;

                            if(options[3][4] == '1')
                                daysOfWeek |= DaysOfWeek.Thursday;

                            if(options[3][5] == '1')
                                daysOfWeek |= DaysOfWeek.Friday;

                            if(options[3][6] == '1')
                                daysOfWeek |= DaysOfWeek.Saturday;

                            rRecur.RecurWeekly(Convert.ToInt32(options[2], CultureInfo.InvariantCulture), daysOfWeek);
                            break;

                        case "4":   // Daily
                            if(options[2] == "1")
                            {
                                // Every week day
                                rRecur.Frequency = RecurFrequency.Daily;
                                rRecur.Interval = 1;
                                rRecur.ByDay.AddRange(new [] { DayOfWeek.Monday, DayOfWeek.Tuesday,
                                    DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday });
                            }
                            else
                                rRecur.RecurDaily(Convert.ToInt32(options[3], CultureInfo.InvariantCulture));
                            break;

                        default:    // Hourly, minutely, secondly
                            rRecur.Frequency = (RecurFrequency)Convert.ToInt32(options[1], CultureInfo.InvariantCulture);
                            rRecur.Interval = Convert.ToInt32(options[2], CultureInfo.InvariantCulture);
                            break;
                    }
                }

                // Parse the range options
                rRecur.WeekStart = (DayOfWeek)Convert.ToInt32(options[options.Length - 4], CultureInfo.InvariantCulture);
                rRecur.CanOccurOnHoliday = (options[options.Length - 3] == "1");

                switch(options[options.Length - 2])
                {
                    case "1":   // End after N occurrences
                        rRecur.MaximumOccurrences = Convert.ToInt32(options[options.Length - 1],
                            CultureInfo.InvariantCulture);
                        break;

                    case "2":   // End after a specific date
                        rRecur.RecurUntil = Convert.ToDateTime(options[options.Length - 1],
                            CultureInfo.InvariantCulture);
                        break;

                    default:    // Never ends
                        break;
                }
            }

            return false;
        }
Пример #39
0
        public void ScheduleJobOnlyOnce <T>(string uniqueName, T jobInfo, DateTime schedule, Recurrence r = null, string jobRoute = null) where T : class
        {
            var exists = true;

            exists = (from si in _jobs where si.UniqueName == uniqueName select si).Any();



            if (!exists)
            {
                var si = new ScheduledItem(uniqueName, JsonConvert.SerializeObject(jobInfo, _settings),
                                           typeof(T), jobRoute, schedule, r);
                _jobs.Add(si);
            }
        }
Пример #40
0
        //=====================================================================

	    /// <summary>
        /// This method is overridden to generate the controls
	    /// </summary>
        protected override void CreateChildControls()
        {
            if(this.DesignMode)
                return;

            Assembly asm = Assembly.GetExecutingAssembly();
            StringBuilder sb = new StringBuilder(4096);

            if(rRecur == null)
            {
                rRecur = new Recurrence();
                rRecur.StartDateTime = DateTime.Today;
                rRecur.RecurDaily(1);
            }

            // For this control, JavaScript support is required
            if(this.Page.Request.Browser.EcmaScriptVersion.Major < 1)
            {
                this.Controls.Add(new LiteralControl(String.Format(CultureInfo.InvariantCulture,
                    "<div class='{0}'>The <strong>EWSoftware.PDI.Web.Controls.RecurrencePattern</strong> " +
                    "control requires that JavaScript be enabled in order to work correctly.</div>",
                    String.IsNullOrWhiteSpace(this.CssPanel) ? "EWS_RP_Panel" : this.CssPanel)));
                return;
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "RecurrencePattern.html")))
            {
                sb.Append(sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "SecondlyPattern.html")))
            {
                sb.Replace("<@Secondly@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "MinutelyPattern.html")))
            {
                sb.Replace("<@Minutely@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "HourlyPattern.html")))
            {
                sb.Replace("<@Hourly@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "DailyPattern.html")))
            {
                sb.Replace("<@Daily@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "WeeklyPattern.html")))
            {
                sb.Replace("<@Weekly@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "MonthlyPattern.html")))
            {
                sb.Replace("<@Monthly@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "YearlyPattern.html")))
            {
                sb.Replace("<@Yearly@>", sr.ReadToEnd().Trim());
            }

            using(var sr = new StreamReader(asm.GetManifestResourceStream(RecurrencePatternHtml +
              "AdvancedPattern.html")))
            {
                sb.Replace("<@Advanced@>", sr.ReadToEnd().Trim());
            }

            // Set the ID for all contained HTML controls and method calls
            sb.Replace("@_", this.ID + "_");
            sb.Replace("@.", "RP_" + this.ID + ".");

            // Replace styles as needed
            if(!String.IsNullOrWhiteSpace(this.CssButton))
                sb.Replace("EWS_RP_Button", this.CssButton);

            if(!String.IsNullOrWhiteSpace(this.CssErrorMessage))
                sb.Replace("EWS_RP_ErrorMessage", this.CssErrorMessage);

            if(!String.IsNullOrWhiteSpace(this.CssInput))
                sb.Replace("EWS_RP_Input", this.CssInput);

            if(!String.IsNullOrWhiteSpace(this.CssPanelBody))
                sb.Replace("EWS_RP_PanelBody", this.CssPanelBody);

            if(!String.IsNullOrWhiteSpace(this.CssPanelHeading))
                sb.Replace("EWS_RP_PanelHeading", this.CssPanelHeading);

            if(!String.IsNullOrWhiteSpace(this.CssPanelTitle))
                sb.Replace("EWS_RP_PanelTitle", this.CssPanelTitle);

            // Do this after the others or it matches them too
            if(!String.IsNullOrWhiteSpace(this.CssPanel))
                sb.Replace("EWS_RP_Panel", this.CssPanel);

            if(!String.IsNullOrWhiteSpace(this.CssSelect))
                sb.Replace("EWS_RP_Select", this.CssSelect);

            // Add the default style sheet if needed.  Try to put it in the header. If not, just add it as a
            // child of this control.
            if(String.IsNullOrWhiteSpace(this.CssButton) || String.IsNullOrWhiteSpace(this.CssErrorMessage) ||
              String.IsNullOrWhiteSpace(this.CssInput) || String.IsNullOrWhiteSpace(this.CssPanel) ||
              String.IsNullOrWhiteSpace(this.CssPanelBody) || String.IsNullOrWhiteSpace(this.CssPanelHeading) ||
              String.IsNullOrWhiteSpace(this.CssPanelTitle) || String.IsNullOrWhiteSpace(this.CssSelect))
            {
                LiteralControl cssLink = new LiteralControl(String.Format(CultureInfo.InvariantCulture,
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\">",
                    this.Page.ClientScript.GetWebResourceUrl(typeof(RecurrencePattern),
                        RecurrencePattern.RecurrencePatternHtml + "RecurrenceStyle.css")));

                cssLink.ID = "EWS_RP_Stylesheet";

                if(this.Page != null && this.Page.Header != null && this.Page.Header.FindControl(cssLink.ID) == null)
                    this.Page.Header.Controls.Add(cssLink);
                else
                    this.Controls.Add(cssLink);
            }

            this.Controls.Add(new LiteralControl(sb.ToString()));

            // Add the validator if supported.  If not, use an OnSubmit function with a custom
            // Page_ClientValidate function for __doPostBack (added by OnPreRender).
            if(this.DetermineRenderUplevel)
            {
                validator = new CustomValidator();
                validator.ID = this.ID + "_Validator";
                validator.ClientValidationFunction = this.ID + "_Validate";
                validator.Display = ValidatorDisplay.None;
                validator.ErrorMessage = "The recurrence pattern is not valid";
                this.Controls.Add(validator);
            }
            else
                this.Page.ClientScript.RegisterOnSubmitStatement(typeof(RecurrencePattern), this.ID + "_Submit",
                    "return RP_" + this.ID + ".ValidateRecurrence();");

            this.Page.RegisterRequiresPostBack(this);
        }
Пример #41
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="recurrence">The <see cref="Recurrence" /> object to enumerate</param>
        public RecurrenceEnumerator(Recurrence recurrence)
        {
            this.recurrence = recurrence;
            this.Reset();
        }
Пример #42
0
        /// <param name='resourceId'>
        /// Required. The resource ID.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";

            url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AutoscaleSettingGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new AutoscaleSettingGetResponse();
                    JToken responseDoc = null;
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        responseDoc = JToken.Parse(responseContent);
                    }

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        AutoscaleSetting settingInstance = new AutoscaleSetting();
                        result.Setting = settingInstance;

                        JToken profilesArray = responseDoc["Profiles"];
                        if (profilesArray != null && profilesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken profilesValue in ((JArray)profilesArray))
                            {
                                AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
                                settingInstance.Profiles.Add(autoscaleProfileInstance);

                                JToken nameValue = profilesValue["Name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    string nameInstance = ((string)nameValue);
                                    autoscaleProfileInstance.Name = nameInstance;
                                }

                                JToken capacityValue = profilesValue["Capacity"];
                                if (capacityValue != null && capacityValue.Type != JTokenType.Null)
                                {
                                    ScaleCapacity capacityInstance = new ScaleCapacity();
                                    autoscaleProfileInstance.Capacity = capacityInstance;

                                    JToken minimumValue = capacityValue["Minimum"];
                                    if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                    {
                                        string minimumInstance = ((string)minimumValue);
                                        capacityInstance.Minimum = minimumInstance;
                                    }

                                    JToken maximumValue = capacityValue["Maximum"];
                                    if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                    {
                                        string maximumInstance = ((string)maximumValue);
                                        capacityInstance.Maximum = maximumInstance;
                                    }

                                    JToken defaultValue = capacityValue["Default"];
                                    if (defaultValue != null && defaultValue.Type != JTokenType.Null)
                                    {
                                        string defaultInstance = ((string)defaultValue);
                                        capacityInstance.Default = defaultInstance;
                                    }
                                }

                                JToken rulesArray = profilesValue["Rules"];
                                if (rulesArray != null && rulesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken rulesValue in ((JArray)rulesArray))
                                    {
                                        ScaleRule scaleRuleInstance = new ScaleRule();
                                        autoscaleProfileInstance.Rules.Add(scaleRuleInstance);

                                        JToken metricTriggerValue = rulesValue["MetricTrigger"];
                                        if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
                                        {
                                            MetricTrigger metricTriggerInstance = new MetricTrigger();
                                            scaleRuleInstance.MetricTrigger = metricTriggerInstance;

                                            JToken metricNameValue = metricTriggerValue["MetricName"];
                                            if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                            {
                                                string metricNameInstance = ((string)metricNameValue);
                                                metricTriggerInstance.MetricName = metricNameInstance;
                                            }

                                            JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
                                            if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                            {
                                                string metricNamespaceInstance = ((string)metricNamespaceValue);
                                                metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
                                            }

                                            JToken metricSourceValue = metricTriggerValue["MetricSource"];
                                            if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
                                            {
                                                string metricSourceInstance = ((string)metricSourceValue);
                                                metricTriggerInstance.MetricSource = metricSourceInstance;
                                            }

                                            JToken timeGrainValue = metricTriggerValue["TimeGrain"];
                                            if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                                metricTriggerInstance.TimeGrain = timeGrainInstance;
                                            }

                                            JToken statisticValue = metricTriggerValue["Statistic"];
                                            if (statisticValue != null && statisticValue.Type != JTokenType.Null)
                                            {
                                                MetricStatisticType statisticInstance = ((MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), ((string)statisticValue), true));
                                                metricTriggerInstance.Statistic = statisticInstance;
                                            }

                                            JToken timeWindowValue = metricTriggerValue["TimeWindow"];
                                            if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan(((string)timeWindowValue));
                                                metricTriggerInstance.TimeWindow = timeWindowInstance;
                                            }

                                            JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
                                            if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
                                            {
                                                TimeAggregationType timeAggregationInstance = ((TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), ((string)timeAggregationValue), true));
                                                metricTriggerInstance.TimeAggregation = timeAggregationInstance;
                                            }

                                            JToken operatorValue = metricTriggerValue["Operator"];
                                            if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                            {
                                                ComparisonOperationType operatorInstance = ((ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), ((string)operatorValue), true));
                                                metricTriggerInstance.Operator = operatorInstance;
                                            }

                                            JToken thresholdValue = metricTriggerValue["Threshold"];
                                            if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                            {
                                                double thresholdInstance = ((double)thresholdValue);
                                                metricTriggerInstance.Threshold = thresholdInstance;
                                            }
                                        }

                                        JToken scaleActionValue = rulesValue["ScaleAction"];
                                        if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
                                        {
                                            ScaleAction scaleActionInstance = new ScaleAction();
                                            scaleRuleInstance.ScaleAction = scaleActionInstance;

                                            JToken directionValue = scaleActionValue["Direction"];
                                            if (directionValue != null && directionValue.Type != JTokenType.Null)
                                            {
                                                ScaleDirection directionInstance = ((ScaleDirection)Enum.Parse(typeof(ScaleDirection), ((string)directionValue), true));
                                                scaleActionInstance.Direction = directionInstance;
                                            }

                                            JToken typeValue = scaleActionValue["Type"];
                                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                                            {
                                                ScaleType typeInstance = ((ScaleType)Enum.Parse(typeof(ScaleType), ((string)typeValue), true));
                                                scaleActionInstance.Type = typeInstance;
                                            }

                                            JToken valueValue = scaleActionValue["Value"];
                                            if (valueValue != null && valueValue.Type != JTokenType.Null)
                                            {
                                                string valueInstance = ((string)valueValue);
                                                scaleActionInstance.Value = valueInstance;
                                            }

                                            JToken cooldownValue = scaleActionValue["Cooldown"];
                                            if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan(((string)cooldownValue));
                                                scaleActionInstance.Cooldown = cooldownInstance;
                                            }
                                        }
                                    }
                                }

                                JToken fixedDateValue = profilesValue["FixedDate"];
                                if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
                                {
                                    TimeWindow fixedDateInstance = new TimeWindow();
                                    autoscaleProfileInstance.FixedDate = fixedDateInstance;

                                    JToken timeZoneValue = fixedDateValue["TimeZone"];
                                    if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
                                    {
                                        string timeZoneInstance = ((string)timeZoneValue);
                                        fixedDateInstance.TimeZone = timeZoneInstance;
                                    }

                                    JToken startValue = fixedDateValue["Start"];
                                    if (startValue != null && startValue.Type != JTokenType.Null)
                                    {
                                        DateTime startInstance = ((DateTime)startValue);
                                        fixedDateInstance.Start = startInstance;
                                    }

                                    JToken endValue = fixedDateValue["End"];
                                    if (endValue != null && endValue.Type != JTokenType.Null)
                                    {
                                        DateTime endInstance = ((DateTime)endValue);
                                        fixedDateInstance.End = endInstance;
                                    }
                                }

                                JToken recurrenceValue = profilesValue["Recurrence"];
                                if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
                                {
                                    Recurrence recurrenceInstance = new Recurrence();
                                    autoscaleProfileInstance.Recurrence = recurrenceInstance;

                                    JToken frequencyValue = recurrenceValue["Frequency"];
                                    if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
                                    {
                                        RecurrenceFrequency frequencyInstance = ((RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), ((string)frequencyValue), true));
                                        recurrenceInstance.Frequency = frequencyInstance;
                                    }

                                    JToken scheduleValue = recurrenceValue["Schedule"];
                                    if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
                                    {
                                        RecurrentSchedule scheduleInstance = new RecurrentSchedule();
                                        recurrenceInstance.Schedule = scheduleInstance;

                                        JToken timeZoneValue2 = scheduleValue["TimeZone"];
                                        if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
                                        {
                                            string timeZoneInstance2 = ((string)timeZoneValue2);
                                            scheduleInstance.TimeZone = timeZoneInstance2;
                                        }

                                        JToken daysArray = scheduleValue["Days"];
                                        if (daysArray != null && daysArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken daysValue in ((JArray)daysArray))
                                            {
                                                scheduleInstance.Days.Add(((string)daysValue));
                                            }
                                        }

                                        JToken hoursArray = scheduleValue["Hours"];
                                        if (hoursArray != null && hoursArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken hoursValue in ((JArray)hoursArray))
                                            {
                                                scheduleInstance.Hours.Add(((int)hoursValue));
                                            }
                                        }

                                        JToken minutesArray = scheduleValue["Minutes"];
                                        if (minutesArray != null && minutesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken minutesValue in ((JArray)minutesArray))
                                            {
                                                scheduleInstance.Minutes.Add(((int)minutesValue));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        JToken enabledValue = responseDoc["Enabled"];
                        if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                        {
                            bool enabledInstance = ((bool)enabledValue);
                            settingInstance.Enabled = enabledInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Пример #43
0
 /// <summary>
 /// This is used to expand the weekly frequency by day of the week
 /// </summary>
 /// <param name="r">A reference to the recurrence</param>
 /// <param name="dates">A reference to the collection of current instances that have been generated</param>
 /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
 /// checked as there's nothing else to do.</returns>
 /// <remarks>If an expanded date is invalid, it will be discarded</remarks>
 public int ByDay(Recurrence r, RecurDateTimeCollection dates)
 {
     return(Expand.ByDayInWeeks(r, dates));
 }
Пример #44
0
		public Schedule(DateTime startTime, DateTime endTime, Recurrence recurrence, int activationLimit) :
			this(new List<DateTimeRange> { new DateTimeRange(startTime, endTime) }, recurrence, activationLimit)
		{
		}
Пример #45
0
        /// <summary>
        /// This is used to initialize the control with settings from an existing recurrence object
        /// </summary>
        /// <param name="recurrence">The recurrence from which to get the settings.  If null, it uses a default
        /// daily recurrence pattern.</param>
        public void SetRecurrence(Recurrence recurrence)
        {
            Recurrence r = new Recurrence();

            if (recurrence == null)
            {
                r.StartDateTime = DateTime.Today;
                r.RecurDaily(1);
            }
            else
            {
                r.Parse(recurrence.ToStringWithStartDateTime());
            }

            // If the given pattern is not available, set it to the next best pattern
            if (maxPattern < r.Frequency)
            {
                switch (maxPattern)
                {
                case RecurFrequency.Yearly:
                    r.RecurYearly(DateTime.Now.Month, DateTime.Now.Day, r.Interval);
                    break;

                case RecurFrequency.Monthly:
                    r.RecurMonthly(DateTime.Now.Day, r.Interval);
                    break;

                case RecurFrequency.Weekly:
                    r.RecurWeekly(r.Interval, DateUtils.ToDaysOfWeek(DateTime.Now.DayOfWeek));
                    break;

                case RecurFrequency.Daily:
                    r.RecurDaily(r.Interval);
                    break;

                case RecurFrequency.Hourly:
                    r.RecurDaily(r.Interval);
                    r.Frequency = RecurFrequency.Hourly;
                    break;

                default:
                    r.RecurDaily(r.Interval);
                    r.Frequency = RecurFrequency.Minutely;
                    break;
                }
            }

            switch (r.Frequency)
            {
            case RecurFrequency.Yearly:
                rbYearly.Checked = true;
                break;

            case RecurFrequency.Monthly:
                rbMonthly.Checked = true;
                break;

            case RecurFrequency.Weekly:
                rbWeekly.Checked = true;
                break;

            case RecurFrequency.Hourly:
                rbHourly.Checked = true;
                break;

            case RecurFrequency.Minutely:
                rbMinutely.Checked = true;
                break;

            case RecurFrequency.Secondly:
                rbSecondly.Checked = true;
                break;

            default:        // Daily or undefined
                rbDaily.Checked = true;
                break;
            }

            cboWeekStartDay.SelectedValue = r.WeekStart;
            dtpEndDate.Value     = DateTime.Today;
            udcOccurrences.Value = 1;

            // If not visible, this option is always on in the recurrence
            if (holidayVisible)
            {
                chkHolidays.Checked = r.CanOccurOnHoliday;
            }
            else
            {
                chkHolidays.Checked = true;
            }

            if (r.MaximumOccurrences != 0)
            {
                rbEndAfter.Checked   = true;
                udcOccurrences.Value = (r.MaximumOccurrences < 1000) ? r.MaximumOccurrences : 999;
            }
            else
            if (r.RecurUntil == DateTime.MaxValue)
            {
                rbNeverEnds.Checked = true;
            }
            else
            {
                rbEndByDate.Checked = true;
                dtpEndDate.Value    = r.RecurUntil;
            }

            // Set parameters in the sub-controls.  Set them all so that when the Advanced pane is hidden or
            // shown, it keeps them consistent when first opened.
            ucYearly.SetValues(r);
            ucMonthly.SetValues(r);
            ucWeekly.SetValues(r);
            ucDaily.SetValues(r);
            ucHourly.SetValues(r);
            ucMinutely.SetValues(r);
            ucSecondly.SetValues(r);
            ucAdvanced.SetValues(r);

            if (advancedVisible)
            {
                noCopy = true;
                chkAdvanced.Checked = r.IsAdvancedPattern;
                noCopy = false;
            }
        }
 /// <summary>
 /// This is used to expand the yearly frequency by month day
 /// </summary>
 /// <param name="r">A reference to the recurrence</param>
 /// <param name="dates">A reference to the collection of current instances that have been generated</param>
 /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
 /// checked as there's nothing else to do.</returns>
 public int ByMonthDay(Recurrence r, RecurDateTimeCollection dates)
 {
     return(Expand.ByMonthDay(r, dates));
 }
Пример #47
0
 /// <summary>
 /// ByWeekNo is only applicable in the Yearly frequency and is ignored for the Hourly frequency
 /// </summary>
 /// <param name="r">A reference to the recurrence</param>
 /// <param name="dates">A reference to the collection of current instances that have been generated</param>
 /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
 /// checked as there's nothing else to do.</returns>
 public int ByWeekNo(Recurrence r, RecurDateTimeCollection dates)
 {
     return(dates.Count);
 }
Пример #48
0
 // fromDate, toDate, eventStartDate - in UTC format
 public static ArrayList GetRecurDates(DateTime fromDate, DateTime toDate, int startTime, DateTime eventStartDate, Recurrence recurrence)
 {
     return GetRecurDates(fromDate, toDate, startTime, eventStartDate, recurrence, 0, Disposition.First);
 }
Пример #49
0
 /// <summary>
 /// This is used to filter the hourly frequency by month
 /// </summary>
 /// <param name="r">A reference to the recurrence</param>
 /// <param name="dates">A reference to the collection of current instances that have been generated</param>
 /// <returns>The number of instances in the collection.  If zero, subsequent rules don't have to be
 /// checked as there's nothing else to do.</returns>
 public int ByMonth(Recurrence r, RecurDateTimeCollection dates)
 {
     return(Filter.ByMonth(r, dates));
 }
Пример #50
0
        //TODO: When this method is called from IBNProject webservices dateTime and dateTo should be in UTC
        public static void GetCalendarXml(XmlDocument retValDoc, DateTime dateFrom, DateTime dateTo)
        {
            XmlNode eventRoot = retValDoc.SelectSingleNode("ibnCalendar/events");

            using (IDataReader reader = CalendarEntry.GetListEventsForUser())
            {
                while (reader.Read())
                {
                    XmlDocumentFragment EventItem = retValDoc.CreateDocumentFragment();
                    EventItem.InnerXml = "<event><id/><title/><description/><location/><startDate/><finishDate/><priority/><reminderInterval/><resources/></event>";

                    XmlDocumentFragment ResourceItem = retValDoc.CreateDocumentFragment();
                    ResourceItem.InnerXml = "<resource><login/><type/><name/><address/></resource>";

                    int EventId = (int)reader["EventId"];
                    int ManagerId = (int)reader["ManagerId"];

                    DateTime StartDate = (DateTime)reader["StartDate"];
                    DateTime FinishDate = (DateTime)reader["FinishDate"];

                    Recurrence recurrence = new Recurrence(0, 0, 0, 0, 0, 0, 0, 0, DateTime.Now, DateTime.Now, 0);
                    int StartTime = 0;
                    int EndTime = 0;
                    bool HasRecurrence = false;

                    bool bAddEvent = false;

                    using (IDataReader rr_reader = DBCommon.GetRecurrence((int)CALENDAR_ENTRY_TYPE, EventId))
                    {
                        if (rr_reader.Read())	// recurrence exists
                        {

                            recurrence = new Recurrence(
                                (byte)rr_reader["Pattern"],
                                (byte)rr_reader["SubPattern"],
                                (byte)rr_reader["Frequency"],
                                (byte)rr_reader["Weekdays"],
                                (byte)rr_reader["DayOfMonth"],
                                (byte)rr_reader["WeekNumber"],
                                (byte)rr_reader["MonthNumber"],
                                (int)rr_reader["EndAfter"],
                                StartDate,
                                FinishDate,
                                (int)rr_reader["TimeZoneId"]);

                            StartTime = (int)rr_reader["StartTime"];
                            EndTime = (int)rr_reader["EndTime"];

                            HasRecurrence = true;
                        }
                    }

                    ArrayList RecurDatesList = null;

                    if (HasRecurrence)
                    {
                        RecurDatesList = CalendarEntry.GetRecurDates(dateFrom, dateTo, StartTime, Security.CurrentUser.CurrentTimeZone.ToUniversalTime(StartDate), recurrence);
                        bAddEvent = (RecurDatesList.Count > 0);
                    }
                    else
                    {
                        if (StartDate >= dateFrom && StartDate <= dateTo)
                            bAddEvent = true;
                    }

                    if (bAddEvent)
                    {
                        ArrayList addedUserId = new ArrayList();

                        EventItem.SelectSingleNode("event/id").InnerText = ((int)reader["EventId"]).ToString();
                        EventItem.SelectSingleNode("event/title").InnerText = (string)reader["Title"];
                        EventItem.SelectSingleNode("event/description").InnerText = (string)reader["Description"];
                        EventItem.SelectSingleNode("event/location").InnerText = (string)reader["Location"];
                        EventItem.SelectSingleNode("event/startDate").InnerText = ((DateTime)reader["StartDate"]).ToString("s");
                        EventItem.SelectSingleNode("event/finishDate").InnerText = ((DateTime)reader["FinishDate"]).ToString("s");
                        EventItem.SelectSingleNode("event/priority").InnerText = ((int)reader["PriorityId"]).ToString();
                        EventItem.SelectSingleNode("event/reminderInterval").InnerText = ((int)reader["Interval"]).ToString();

                        XmlNode resourceRoot = EventItem.SelectSingleNode("event/resources");

                        using (IDataReader r_reader = User.GetUserInfo(ManagerId))
                        {
                            if (r_reader.Read())
                            {
                                ResourceItem.SelectSingleNode("resource/login").InnerText = (string)r_reader["Login"];
                                ResourceItem.SelectSingleNode("resource/type").InnerText = "manager";
                                ResourceItem.SelectSingleNode("resource/name").InnerText = string.Format("{0} {1}", r_reader["FirstName"], r_reader["LastName"]);
                                ResourceItem.SelectSingleNode("resource/address").InnerText = (string)r_reader["Email"];

                                resourceRoot.AppendChild(ResourceItem.CloneNode(true));
                                addedUserId.Add(ManagerId);
                            }
                        }

                        using (IDataReader r_reader = CalendarEntry.GetListResources(EventId))
                        {
                            while (r_reader.Read())
                            {
                                int PrincipalId = (int)r_reader["PrincipalId"];
                                bool IsGroup = (bool)r_reader["IsGroup"];
                                bool MustBeConfirmed = (bool)r_reader["MustBeConfirmed"];
                                bool ResponsePending = (bool)r_reader["ResponsePending"];
                                bool IsConfirmed = (bool)r_reader["IsConfirmed"];

                                if (IsGroup)
                                {
                                    using (IDataReader g_reader = SecureGroup.GetGroup(PrincipalId))
                                    {
                                        if (g_reader.Read())
                                        {
                                            ResourceItem.SelectSingleNode("resource/login").InnerText = "";
                                            ResourceItem.SelectSingleNode("resource/type").InnerText = "group";
                                            ResourceItem.SelectSingleNode("resource/name").InnerText = Common.GetWebResourceString(g_reader["GroupName"].ToString());
                                            ResourceItem.SelectSingleNode("resource/address").InnerText = "";

                                            resourceRoot.AppendChild(ResourceItem.CloneNode(true));
                                        }
                                    }
                                }
                                else if (!MustBeConfirmed ||
                                    MustBeConfirmed && ResponsePending ||
                                    MustBeConfirmed && !ResponsePending && IsConfirmed)
                                {
                                    if (!addedUserId.Contains(PrincipalId))
                                    {
                                        using (IDataReader u_reader = User.GetUserInfo(PrincipalId))
                                        {
                                            if (u_reader.Read())
                                            {
                                                ResourceItem.SelectSingleNode("resource/login").InnerText = (string)u_reader["Login"];
                                                ResourceItem.SelectSingleNode("resource/type").InnerText = MustBeConfirmed ? "optional" : "required";
                                                ResourceItem.SelectSingleNode("resource/name").InnerText = string.Format("{0} {1}", u_reader["FirstName"], u_reader["LastName"]);
                                                ResourceItem.SelectSingleNode("resource/address").InnerText = (string)u_reader["Email"];

                                                resourceRoot.AppendChild(ResourceItem.CloneNode(true));
                                                addedUserId.Add(ManagerId);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (HasRecurrence)	// recurrence exists
                        {
                            XmlDocumentFragment RecurrenceItem = retValDoc.CreateDocumentFragment();
                            RecurrenceItem.InnerXml = "<recurrence><recurrenceType></recurrenceType><interval/><dayOfWeek/><dayOfMonth/><monthOfYear/><instance/><startTime/><endTime/><occurrences/></recurrence>";

                            // Common Information [2/9/2005]
                            RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "";
                            RecurrenceItem.SelectSingleNode("recurrence/startTime").InnerText = string.Format("{0:d2}:{1:d2}:00", StartTime / 60, StartTime % 60);
                            RecurrenceItem.SelectSingleNode("recurrence/endTime").InnerText = string.Format("{0:d2}:{1:d2}:00", EndTime / 60, EndTime % 60);
                            RecurrenceItem.SelectSingleNode("recurrence/occurrences").InnerText = recurrence.EndAfter.ToString();

                            //								RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = rr_reader["Frequency"].ToString();
                            //								RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = rr_reader["Weekdays"].ToString();
                            //								RecurrenceItem.SelectSingleNode("recurrence/dayOfMonth").InnerText = rr_reader["DayOfMonth"].ToString();
                            //								RecurrenceItem.SelectSingleNode("recurrence/monthOfYear").InnerText = rr_reader["MonthNumber"].ToString();
                            //								RecurrenceItem.SelectSingleNode("recurrence/instance").InnerText = rr_reader["WeekNumber"].ToString(); // ??? MonthNumber

                            // 1-Daily 2-Weekly 3-Monthly 4-Yearly
                            switch ((int)recurrence.Pattern)
                            {
                                case 1:
                                    if (recurrence.SubPattern == RecurSubPattern.SubPattern1)
                                    {
                                        RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "daily";
                                        RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = recurrence.Frequency.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = "0";
                                    }
                                    else // SubPattern 2
                                    {
                                        if (recurrence.Frequency == 1)
                                        {
                                            RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "weekly";
                                            RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = "1";// [2/11/2005] recurrence.Frequency.ToString();
                                            RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = ((int)BitDayOfWeek.Weekdays).ToString();
                                        }
                                        else
                                        {
                                            //HasRecurrence = false;
                                            // Unpack Recurring calendar Item [2/11/2005]
                                            foreach (DateTime dt in RecurDatesList)
                                            {
                                                DateTime UserDt = DBCommon.GetLocalDate(Security.CurrentUser.TimeZoneId, dt);	// from UTC to User's time
                                                DateTime _StartDate = UserDt.AddMinutes(StartTime);
                                                DateTime _FinishDate = UserDt.AddMinutes(EndTime);

                                                XmlNode xmlRecEvent = EventItem.CloneNode(true);

                                                xmlRecEvent.SelectSingleNode("event/startDate").InnerText = _StartDate.ToString("s");
                                                xmlRecEvent.SelectSingleNode("event/finishDate").InnerText = _FinishDate.ToString("s");

                                                eventRoot.AppendChild(xmlRecEvent);
                                            }

                                            continue;
                                        }
                                    }
                                    break;
                                case 2:
                                    RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "weekly";
                                    RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = recurrence.Frequency.ToString();
                                    RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = recurrence.WeekDays.ToString();
                                    break;
                                case 3:
                                    if (recurrence.SubPattern == RecurSubPattern.SubPattern1)
                                    {
                                        RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "monthly";
                                        RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = recurrence.Frequency.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/dayOfMonth").InnerText = recurrence.DayOfMonth.ToString();

                                    }
                                    else // SubPattern 2
                                    {
                                        RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "monthNth";
                                        RecurrenceItem.SelectSingleNode("recurrence/interval").InnerText = recurrence.Frequency.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = recurrence.WeekDays.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/instance").InnerText = recurrence.RecurWeekNumber.ToString();
                                    }
                                    break;
                                case 4:
                                    if (recurrence.SubPattern == RecurSubPattern.SubPattern1)
                                    {
                                        RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "yearly";
                                        RecurrenceItem.SelectSingleNode("recurrence/dayOfMonth").InnerText = recurrence.DayOfMonth.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/monthOfYear").InnerText = recurrence.MonthNumber.ToString();
                                    }
                                    else // SubPattern 2
                                    {
                                        RecurrenceItem.SelectSingleNode("recurrence/recurrenceType").InnerText = "yearNth";
                                        RecurrenceItem.SelectSingleNode("recurrence/monthOfYear").InnerText = recurrence.MonthNumber.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/dayOfWeek").InnerText = recurrence.WeekDays.ToString();
                                        RecurrenceItem.SelectSingleNode("recurrence/instance").InnerText = recurrence.RecurWeekNumber.ToString();

                                    }
                                    break;
                            }

                            //
                            EventItem.SelectSingleNode("event").AppendChild(RecurrenceItem);
                        }

                        eventRoot.AppendChild(EventItem);
                    }
                }
            }
        }
 /// <summary>
 /// Checks if two recurrence objects are identical. 
 /// </summary>
 /// <param name="otherRecurrence">The recurrence to compare this one to.</param>
 /// <returns>true if the two recurrences are identical, false otherwise.</returns>
 public override bool IsSame(Recurrence otherRecurrence)
 {
     return base.IsSame(otherRecurrence) && this.interval == ((IntervalPattern)otherRecurrence).interval;
 }
Пример #52
0
 /// <summary>
 /// Setup the recurrence.
 /// </summary>
 /// <param name="recurrence">The recurrence.</param>
 internal virtual void SetupRecurrence(Recurrence recurrence)
 {
     recurrence.StartDate = this.StartDate;
 }
Пример #53
0
        /// <summary>
        /// Returns ArrayList of DateTime objects 
        /// (fromDate, toDate, eventStartDate - in UTC format)
        /// (return dates in UTC too, but without time part. 
        ///		To get the real Start DateTime you need to add recurrence StartTime to the returned dates)
        /// </summary>
        public static ArrayList GetRecurDates(DateTime fromDate, DateTime toDate, int startTime, DateTime eventStartDate, Recurrence recurrence, int maxCount, Disposition disp)
        {
            ArrayList list = new ArrayList();
            DateTime addDate;
            bool add;
            bool WeekDaysCalculated = false;
            int count = 0;
            // ѕереводим fromDate и toDate из UTC во временную зону рекурсии
            fromDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, fromDate);
            toDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, toDate);
            eventStartDate = DBCommon.GetLocalDate(recurrence.TimeZoneId, eventStartDate);

            DateTime startDate = recurrence.StartDate.Date;
            DateTime finishDate = recurrence.FinishDate.Date;
            DateTime curDate = startDate;

            if (recurrence.EndAfter == 0 && finishDate < toDate)
                toDate = finishDate;

            while (curDate <= toDate.AddDays(1))	// O.R.: добавл¤ем один день, чтобы не потер¤ть данные за счЄт разницы временных зон рекурсии и пользовател¤
            {
                // O.R.: if curDate is not appropriate - skip
                if (curDate.AddMinutes(startTime) < eventStartDate)
                {
                    curDate = curDate.AddDays(1);
                    continue;
                }

                add = false;
                addDate = curDate;

                if (recurrence.Pattern == RecurPattern.Daily && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on every Nth day.
                    TimeSpan span = curDate - startDate;
                    if (span.Days % recurrence.Frequency == 0)
                    {
                        add = true;
                        curDate = curDate.AddDays(recurrence.Frequency);
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Daily && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on every Nth weekday.
                    if (WeekDaysCalculated)
                    {
                        add = true;
                        curDate = AddWeekDays(curDate, recurrence.Frequency);
                    }
                    else
                    {
                        int weekDaysElapsed = GetElapsedWeekDays(startDate, curDate);
                        if (weekDaysElapsed % recurrence.Frequency == 0 && GetFirstWeekDay(startDate) <= curDate)
                        {
                            WeekDaysCalculated = true;
                            add = true;
                            curDate = AddWeekDays(curDate, recurrence.Frequency);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Weekly)
                {
                    // Repeat on every selected day of Nth week.
                    BitDayOfWeek bdow = GetBitDayOfWeek(curDate.DayOfWeek);
                    if ((byte)BitDayOfWeek.Unknown != ((byte)bdow & recurrence.WeekDays))
                    {
                        int week = GetRelativeWeekNumber(startDate, curDate);
                        if ((double)week % recurrence.Frequency == 0)
                        {
                            add = true;
                            curDate = curDate.AddDays(1);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Monthly && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on selected day of every Nth month.
                    if (curDate.Day == recurrence.DayOfMonth)
                    {
                        int month = GetRelativeMonthNumber(startDate, curDate);
                        if ((double)month % recurrence.Frequency == 0)
                        {
                            add = true;
                            curDate = curDate.AddMonths(recurrence.Frequency);
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Monthly && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on selected week and day of week of every Nth month.
                    if (curDate.DayOfWeek == GetDayOfWeekByBit((BitDayOfWeek)recurrence.WeekDays))
                    {
                        WeekNumber week = GetWeekNumber(curDate);
                        if ((week & ~WeekNumber.Last) == recurrence.RecurWeekNumber || (week & WeekNumber.Last) == recurrence.RecurWeekNumber)
                        {
                            int month = GetRelativeMonthNumber(startDate, curDate);
                            if ((double)month % recurrence.Frequency == 0)
                            {
                                add = true;
                                curDate = curDate.AddMonths(recurrence.Frequency).Subtract(new TimeSpan(7, 0, 0, 0));
                            }
                        }
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Yearly && recurrence.SubPattern == RecurSubPattern.SubPattern1)
                {
                    // Repeat on selected day and month of every year.
                    if (curDate.Month == recurrence.MonthNumber && curDate.Day == recurrence.DayOfMonth)
                    {
                        add = true;
                        curDate = curDate.AddYears(1);
                    }
                }
                else if (recurrence.Pattern == RecurPattern.Yearly && recurrence.SubPattern == RecurSubPattern.SubPattern2)
                {
                    // Repeat on selected month, week and day of week of every year.
                    if (curDate.Month == recurrence.MonthNumber && curDate.DayOfWeek == GetDayOfWeekByBit((BitDayOfWeek)recurrence.WeekDays))
                    {
                        WeekNumber week = GetWeekNumber(curDate);
                        if ((week & ~WeekNumber.Last) == recurrence.RecurWeekNumber || (week & WeekNumber.Last) == recurrence.RecurWeekNumber)
                        {
                            add = true;
                            curDate = curDate.AddYears(1).Subtract(new TimeSpan(7, 0, 0, 0));
                        }
                    }
                }

                if (add && addDate >= fromDate.Date && addDate <= toDate.Date.AddDays(1))
                {
                    list.Add(DBCommon.GetUTCDate(recurrence.TimeZoneId, addDate));	// to UTC

                    if (maxCount > 0 && disp == Disposition.First && list.Count >= maxCount)
                        break;

                    if (maxCount > 0 && disp == Disposition.Last && list.Count > maxCount)
                        list.RemoveAt(0);
                }

                if (add)
                {
                    count++;
                    if (recurrence.EndAfter > 0 && count >= recurrence.EndAfter)
                        break;
                }
                else
                    curDate = curDate.AddDays(1);
            }

            return list;
        }
Пример #54
0
        static void Main(string[] args)
        {
            SetUpServiceAccounts();
            API api = new API();

            log4net.Config.XmlConfigurator.Configure();
            var route_config = new List <Route>()
            {
                new Route {
                    Name     = "Hello Handler",
                    UrlRegex = @"^/$",
                    Method   = "POST",
                    Callable = (HttpRequest request) => {
                        try{
                            Console.WriteLine(request.Content);
                            JarvisRecurrenceRequest booking = JsonConvert.DeserializeObject <JarvisRecurrenceRequest>(request.Content);
                            string        roomEmail         = "*****@*****.**";
                            DateTime      start             = DateTime.Parse("2019-04-14T02:00:00");
                            DateTime      end       = DateTime.Parse("2019-04-14T04:00:00");
                            string        subject   = "Jarvis";
                            string        body      = "daily stand-up";
                            List <string> attendees = null;

                            Recurrence recurrence = null;
                            switch (booking.type)
                            {
                            case "W":
                                DayOfTheWeek[] daysOfWeek = new DayOfTheWeek[booking.daysOfWeek.Count];
                                int            count      = 0;
                                foreach (int day in booking.daysOfWeek)
                                {
                                    daysOfWeek[count++] = (DayOfTheWeek)day;
                                }
                                recurrence = new Recurrence.WeeklyPattern(DateTime.Parse(booking.start),
                                                                          booking.interval,
                                                                          daysOfWeek);
                                if (!string.IsNullOrEmpty(booking.end))
                                {
                                    recurrence.EndDate = DateTime.Parse(booking.end);
                                }
                                else
                                {
                                    recurrence.NeverEnds();
                                }
                                break;

                            case "M":
                                recurrence = new Recurrence.MonthlyPattern(DateTime.Parse(booking.start),
                                                                           booking.interval,
                                                                           booking.dayOfMonth);
                                if (!string.IsNullOrEmpty(booking.end))
                                {
                                    recurrence.EndDate = DateTime.Parse(booking.end);
                                }
                                else
                                {
                                    recurrence.NeverEnds();
                                }
                                break;

                            case "D":
                                recurrence = new Recurrence.DailyPattern(DateTime.Parse(booking.start),
                                                                         booking.interval);
                                if (!string.IsNullOrEmpty(booking.end))
                                {
                                    recurrence.EndDate = DateTime.Parse(booking.end);
                                }
                                else
                                {
                                    recurrence.NeverEnds();
                                }
                                break;

                            default:

                                break;
                            }


                            ExchangeService service = GetService(3);

                            FindItemsResults <Appointment> appointments = api.GetAppointments(service, roomEmail, start.AddSeconds(1), end);
                            Console.WriteLine(appointments.TotalCount);

                            if (0 == appointments.TotalCount)
                            {
                                api.CreateMeeting(service, roomEmail, subject, body, start, end, attendees, recurrence);

                                return(new HttpResponse()
                                {
                                    ContentAsUTF8 = "Hii",
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }

                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Hello from SimpleHttpServer",
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        } catch (Exception ex)
                        {
                            Console.WriteLine(ex);

                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Hello from SimpleHttpServer",
                                ReasonPhrase = "Boo",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route {
                    Name     = "Send Mail",
                    UrlRegex = @"^/send$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try {
                            Console.WriteLine(req.Content);
                            JarvisRequest booking = JsonConvert.DeserializeObject <JarvisRequest>(req.Content);

                            string to      = booking.to;
                            string subject = booking.subject;
                            string body    = booking.body;

                            ExchangeService service = GetService(0);
                            api.sendMail(service, to, subject, body);
                            Console.WriteLine("mail sent.");

                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Sent",
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Error",
                                ReasonPhrase = "OK",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route {
                    Name     = "Test Post",
                    UrlRegex = @"^/booking$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try {
                            Console.WriteLine(req.Content);
                            JarvisRequest booking = JsonConvert.DeserializeObject <JarvisRequest>(req.Content);

                            string        roomEmail = booking.room;
                            DateTime      start     = DateTime.Parse(booking.start);
                            DateTime      end       = DateTime.Parse(booking.end);
                            string        subject   = booking.subject;
                            string        body      = booking.body;
                            int           floor     = booking.floor;
                            List <string> attendees = booking.attendees;

                            // attendees.Add("*****@*****.**");

                            /*
                             * RecurrencePattern booking = booking.booking;
                             *
                             * Recurrence recurrence;
                             *
                             * if (booking != null)
                             * {
                             *  switch(booking.type)
                             *  {
                             *      case "weekly":
                             *          DayOfTheWeek[] daysOfWeek = new DayOfTheWeek[booking.daysOfWeek.Count];
                             *          int count = 0;
                             *          foreach (int day in booking.daysOfWeek)
                             *          {
                             *              daysOfWeek[count++] = (DayOfTheWeek)day;
                             *          }
                             *          recurrence = new Recurrence.WeeklyPattern(DateTime.Parse(booking.start),
                             *                                                    booking.interval,
                             *                                                    daysOfWeek);
                             *
                             *          break;
                             *      case "monthly":
                             *      break;
                             *      case "daily":
                             *      default:
                             *      break;
                             *  }
                             * }
                             */

                            Console.WriteLine("booking room: " + booking.room);
                            Console.WriteLine("booking start: " + booking.start);
                            Console.WriteLine("booking end: " + booking.end);
                            Console.WriteLine("booking subject: " + booking.subject);
                            Console.WriteLine("booking body: " + booking.body);
                            Console.WriteLine("booking floor: " + booking.floor);

                            ExchangeService service = GetService(floor);

                            FindItemsResults <Appointment> appointments = api.GetAppointments(service, roomEmail, start.AddSeconds(1), end);
                            Console.WriteLine(appointments.TotalCount);

                            if (0 == appointments.TotalCount)
                            {
                                ItemId newAppointment = api.CreateMeeting(service, roomEmail, subject, body, start, end, attendees, null);

                                JarvisResponse res = new JarvisResponse();
                                res.eventId = newAppointment;
                                string resJSON = JsonConvert.SerializeObject(res);
                                return(new HttpResponse()
                                {
                                    ContentAsUTF8 = resJSON,
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }

                            else
                            {
                                return(new HttpResponse()
                                {
                                    ContentAsUTF8 = "Boo",
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Error",
                                ReasonPhrase = "OK",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route()
                {
                    Name     = "Availability",
                    UrlRegex = @"^/avail$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try {
                            JarvisRequest booking   = JsonConvert.DeserializeObject <JarvisRequest>(req.Content);
                            DateTime      start     = DateTime.Parse(booking.start);
                            DateTime      end       = DateTime.Parse(booking.end);
                            string        roomEmail = booking.room;
                            int           floor     = booking.floor;

                            Console.WriteLine("booking room: " + booking.room);
                            Console.WriteLine("booking start: " + booking.start);
                            Console.WriteLine("booking end: " + booking.end);
                            Console.WriteLine("booking floor: " + booking.floor);

                            ExchangeService service = GetService(floor);
                            //service.TraceEnabled = true;
                            //service.TraceFlags = TraceFlags.All;
                            FindItemsResults <Appointment> appointments = api.GetAppointments(service, roomEmail, start.AddSeconds(1), end);

                            if (0 == appointments.TotalCount)
                            {
                                return(new HttpResponse()
                                {
                                    ContentAsUTF8 = "free",
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }
                            else
                            {
                                return(new HttpResponse()
                                {
                                    ContentAsUTF8 = "busy",
                                    ReasonPhrase = "OK",
                                    StatusCode = "200"
                                });
                            }
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "error",
                                ReasonPhrase = "Error",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route()
                {
                    Name     = "Cancel",
                    UrlRegex = @"^/cancel$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try{
                            JarvisRequest booking   = JsonConvert.DeserializeObject <JarvisRequest>(req.Content);
                            string        roomEmail = booking.room;
                            string        eventId   = booking.eventID;
                            int           floor     = booking.floor;

                            Console.WriteLine("booking room: " + booking.room);
                            Console.WriteLine("booking eventId: " + booking.eventID);
                            Console.WriteLine("booking floor: " + booking.floor);

                            ExchangeService service = GetService(floor);
                            api.cancelMeeting(service, eventId);
                            //service.TraceEnabled = true;
                            //service.TraceFlags = TraceFlags.All;
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "cancelled",
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "error",
                                ReasonPhrase = "Error",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route()
                {
                    Name     = "Recur",
                    UrlRegex = @"^/recur$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try {
                            Console.WriteLine(req.Content);
                            JarvisRecurrenceRequest booking = JsonConvert.DeserializeObject <JarvisRecurrenceRequest>(req.Content);

                            Recurrence recurrence = null;
                            switch (booking.type)
                            {
                            case "weekly":
                                DayOfTheWeek[] daysOfWeek = new DayOfTheWeek[booking.daysOfWeek.Count];
                                int            count      = 0;
                                foreach (int day in booking.daysOfWeek)
                                {
                                    daysOfWeek[count++] = (DayOfTheWeek)day;
                                }
                                recurrence = new Recurrence.WeeklyPattern(DateTime.Parse(booking.start),
                                                                          booking.interval,
                                                                          daysOfWeek);
                                break;

                            case "monthly":
                                recurrence = new Recurrence.MonthlyPattern(DateTime.Parse(booking.start),
                                                                           booking.interval,
                                                                           booking.dayOfMonth);
                                break;

                            case "daily":
                                recurrence = new Recurrence.DailyPattern(DateTime.Parse(booking.start),
                                                                         booking.interval);
                                break;

                            default:

                                break;
                            }

                            if (booking.endDate != null)
                            {
                                recurrence.EndDate = DateTime.Parse(booking.endDate);
                            }
                            else if (booking.numberOfOccurrences != -1)
                            {
                                recurrence.NumberOfOccurrences = booking.numberOfOccurrences;
                            }

                            Console.WriteLine(recurrence.HasEnd);

                            // ExchangeService service = GetService(floor);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "free",
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = "Error",
                                ReasonPhrase = "No",
                                StatusCode = "300"
                            });
                        }
                    }
                },
                new Route()
                {
                    Name     = "Find Avail",
                    UrlRegex = @"^/findAvail$",
                    Method   = "POST",
                    Callable = (HttpRequest req) => {
                        try {
                            JarvisRequest booking  = JsonConvert.DeserializeObject <JarvisRequest>(req.Content);
                            string        room     = booking.room;
                            int           floor    = booking.floor;
                            int           duration = booking.duration;
                            DateTime      start    = DateTime.Parse(booking.start);
                            DateTime      end      = DateTime.Parse(booking.end);

                            Console.WriteLine("booking room: " + booking.room);
                            Console.WriteLine("booking floor: " + booking.floor);
                            Console.WriteLine("booking duration: " + booking.duration);
                            Console.WriteLine("booking start: " + booking.start);
                            Console.WriteLine("booking end: " + booking.end);

                            ExchangeService service   = GetService(floor);
                            List <string>   times     = api.GetSuggestedMeetingTimes(service, room, duration, start, end);
                            string          timesJSON = JsonConvert.SerializeObject(times);
                            Console.WriteLine("times: " + timesJSON);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = timesJSON,
                                ReasonPhrase = "OK",
                                StatusCode = "200"
                            });
                        } catch (Exception e)
                        {
                            Console.WriteLine(e);
                            return(new HttpResponse()
                            {
                                ContentAsUTF8 = e.ToString(),
                                ReasonPhrase = "Error",
                                StatusCode = "200"
                            });
                        }
                    }
                }
            };

            HttpServer httpServer = new HttpServer(8080, route_config);

            Thread thread = new Thread(new ThreadStart(httpServer.Listen));

            thread.Start();
        }
Пример #55
0
        internal static Hashtable GetEventInstances(int object_id, out int reminder_interval)
        {
            Hashtable ret = new Hashtable();

            reminder_interval = -1;

            DateTime StartDate;
            DateTime FinishDate;
            int HasRecurrence = 0;

            // Get info
            using (IDataReader reader = GetEvent(object_id, false, true))
            {
                reader.Read();

                StartDate = (DateTime)reader["StartDate"];
                FinishDate = (DateTime)reader["FinishDate"];
                HasRecurrence = (int)reader["HasRecurrence"];
                reminder_interval = (int)reader["ReminderInterval"];
            }

            if (HasRecurrence == 0)
            {
                ret[StartDate] = FinishDate;
            }
            else	// Recurrence
            {
                int StartTime;
                int EndTime;
                Recurrence recurrence;

                using (IDataReader reader = DBCommon.GetRecurrence((int)ObjectTypes.CalendarEntry, object_id))
                {
                    reader.Read();
                    recurrence = new Recurrence(
                        (byte)reader["Pattern"],
                        (byte)reader["SubPattern"],
                        (byte)reader["Frequency"],
                        (byte)reader["Weekdays"],
                        (byte)reader["DayOfMonth"],
                        (byte)reader["WeekNumber"],
                        (byte)reader["MonthNumber"],
                        (int)reader["EndAfter"],
                        StartDate,
                        FinishDate,
                        (int)reader["TimeZoneId"]);
                    StartTime = (int)reader["StartTime"];
                    EndTime = (int)reader["EndTime"];
                }

                // Get new StartDate and FinishDate for recurrence TimeOffset (not UserTimeOffset)
                using (IDataReader reader = DBEvent.GetEventDates(object_id, recurrence.TimeZoneId))
                {
                    reader.Read();
                    recurrence.StartDate = ((DateTime)reader["StartDate"]).Date;
                    recurrence.FinishDate = ((DateTime)reader["FinishDate"]).Date;
                }

                // from_date, to_date, StartDate - in UTC
                ArrayList dates = GetRecurDates(DBCommon.GetUTCDate(recurrence.TimeZoneId, recurrence.StartDate), DBCommon.GetUTCDate(recurrence.TimeZoneId, recurrence.FinishDate), StartTime, StartDate, recurrence);
                foreach (DateTime dt in dates)	// Dates in UTC
                {
                    ret[dt.AddMinutes(StartTime)] = dt.AddMinutes(EndTime);
                }
            }

            return ret;
        }
Пример #56
0
 public Schedule(DateTime startTime, DateTime endTime, Recurrence recurrence, int activationLimit) :
     this(new List <DateTimeRange> {
     new DateTimeRange(startTime, endTime)
 }, recurrence, activationLimit)
 {
 }
            /// <summary>
            /// Checks if two recurrence objects are identical. 
            /// </summary>
            /// <param name="otherRecurrence">The recurrence to compare this one to.</param>
            /// <returns>true if the two recurrences are identical, false otherwise.</returns>
            public override bool IsSame(Recurrence otherRecurrence)
            {
                RelativeYearlyPattern otherYearlyPattern = (RelativeYearlyPattern)otherRecurrence;

                return base.IsSame(otherRecurrence) &&
                       this.dayOfTheWeek == otherYearlyPattern.dayOfTheWeek &&
                       this.dayOfTheWeekIndex == otherYearlyPattern.dayOfTheWeekIndex &&
                       this.month == otherYearlyPattern.month;
            }
            /// <summary>
            /// Checks if two recurrence objects are identical. 
            /// </summary>
            /// <param name="otherRecurrence">The recurrence to compare this one to.</param>
            /// <returns>true if the two recurrences are identical, false otherwise.</returns>
            public override bool IsSame(Recurrence otherRecurrence)
            {
                WeeklyPattern otherWeeklyPattern = (WeeklyPattern)otherRecurrence;

                return base.IsSame(otherRecurrence) &&
                       this.daysOfTheWeek.ToString(",") == otherWeeklyPattern.daysOfTheWeek.ToString(",") &&
                       this.firstDayOfWeek == otherWeeklyPattern.firstDayOfWeek;
            }
            /// <summary>
            /// Checks if two recurrence objects are identical. 
            /// </summary>
            /// <param name="otherRecurrence">The recurrence to compare this one to.</param>
            /// <returns>true if the two recurrences are identical, false otherwise.</returns>
            public override bool IsSame(Recurrence otherRecurrence)
            {
                YearlyPattern otherYearlyPattern = (YearlyPattern)otherRecurrence;

                return base.IsSame(otherRecurrence) &&
                       this.month == otherYearlyPattern.month &&
                       this.dayOfMonth == otherYearlyPattern.dayOfMonth;
            }
Пример #60
0
 internal RecurrenceUtilities(Recurrence recurrence, TextWriter output)
 {
     this.recurrence     = recurrence;
     this.output         = output;
     this.recurrenceType = this.MapRecurrenceType();
 }