Beispiel #1
0
        internal static string ToSerializedValue(this RecurrenceFrequency value)
        {
            switch (value)
            {
            case RecurrenceFrequency.None:
                return("None");

            case RecurrenceFrequency.Second:
                return("Second");

            case RecurrenceFrequency.Minute:
                return("Minute");

            case RecurrenceFrequency.Hour:
                return("Hour");

            case RecurrenceFrequency.Day:
                return("Day");

            case RecurrenceFrequency.Week:
                return("Week");

            case RecurrenceFrequency.Month:
                return("Month");

            case RecurrenceFrequency.Year:
                return("Year");
            }
            return(null);
        }
 public static RecurrenceType GetRecurrenceType(RecurrenceFrequency recurrenceFrequency, PatternType patternType)
 {
     if (recurrenceFrequency == RecurrenceFrequency.Daily && patternType == PatternType.Day)
     {
         return(RecurrenceType.EveryNDays);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Daily && patternType == PatternType.Week)
     {
         return(RecurrenceType.EveryWeekday);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Weekly && patternType == PatternType.Week)
     {
         return(RecurrenceType.EveryNWeeks);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Monthly && patternType == PatternType.Month)
     {
         return(RecurrenceType.EveryNMonths);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Monthly && patternType == PatternType.MonthNth)
     {
         return(RecurrenceType.EveryNthDayOfEveryNMonths);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Yearly && patternType == PatternType.Month)
     {
         return(RecurrenceType.EveryNYears);
     }
     else if (recurrenceFrequency == RecurrenceFrequency.Yearly && patternType == PatternType.MonthNth)
     {
         return(RecurrenceType.EveryNthDayOfEveryNYears);
     }
     else
     {
         throw new InvalidRecurrencePatternException("Invalid combination of RecurrenceFrequency and PatternType");
     }
 }
        /// <summary>
        /// Converts RecurrencyFrequecy and Interval to TimeSpan.
        /// </summary>
        /// <param name="frequency">RecurrenceFrequency.</param>
        /// <param name="interval">Interval.</param>
        /// <returns></returns>
        public static TimeSpan ToTimeSpan(RecurrenceFrequency frequency, int interval)
        {
            DateTime epoch = DateTime.MinValue;

            switch (frequency)
            {
            case RecurrenceFrequency.Minute:
                return(epoch.AddMinutes(interval).Subtract(epoch));

            case RecurrenceFrequency.Hour:
                return(epoch.AddHours(interval).Subtract(epoch));

            case RecurrenceFrequency.Day:
                return(epoch.AddDays(interval).Subtract(epoch));

            case RecurrenceFrequency.Week:
                return(epoch.AddWeeks(interval).Subtract(epoch));

            case RecurrenceFrequency.Month:
                return(epoch.AddMonths(interval).Subtract(epoch));

            default:
                throw new InvalidOperationException("Unsupported recurrence frequency.");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
 /// </summary>
 public RecurrencePattern(
     TimeSpan startTime,
     TimeSpan stopTime,
     List <TimeSpan> times,
     RecurrenceFrequency dailyFrequency,
     int dailyInterval,
     int?dayOfMonth,
     RecurrenceDays daysOfWeekMask,
     RecurrenceFrequency frequency,
     int interval,
     int?monthOfYear,
     int?dayOrdinal)
     : this()
 {
     this._StartTime     = startTime;
     this._StopTime      = stopTime;
     this._Times         = times;
     this.dailyFrequency = dailyFrequency;
     this.dailyInterval  = dailyInterval;
     this.dayOfMonth     = dayOfMonth;
     this.daysOfWeekMask = daysOfWeekMask;
     this.frequency      = frequency;
     this.interval       = interval;
     this.monthOfYear    = monthOfYear;
     this.dayOrdinal     = dayOrdinal;
 }
 /// <summary>
 /// Initializes a new instance of the RecurrencePattern class.
 /// </summary>
 /// <param name="frequency">The frequency of the recurrence. Possible
 /// values include: 'Daily', 'Weekly'</param>
 /// <param name="expirationDate">When the recurrence will expire. This
 /// date is inclusive.</param>
 /// <param name="weekDays">The week days the schedule runs. Used for
 /// when the Frequency is set to Weekly.</param>
 /// <param name="interval">The interval to invoke the schedule on. For
 /// example, interval = 2 and RecurrenceFrequency.Daily will run every
 /// 2 days. When no interval is supplied, an interval of 1 is
 /// used.</param>
 public RecurrencePattern(RecurrenceFrequency frequency, System.DateTime expirationDate, IList <WeekDay?> weekDays = default(IList <WeekDay?>), int?interval = default(int?))
 {
     Frequency      = frequency;
     WeekDays       = weekDays;
     Interval       = interval;
     ExpirationDate = expirationDate;
     CustomInit();
 }
Beispiel #6
0
 public RecurrenceRuleValue(RecurrenceFrequency frequency, IEnumerable <IByListRule> listRules,
                            int interval = 1, DelimiterRule delimiter = null, DayOfWeek weekStart = DayOfWeek.Monday)
 {
     Frequency = frequency;
     ListRules = listRules.ToDictionary(x => x.RuleType);
     Interval  = interval;
     Delimiter = delimiter;
     WeekStart = weekStart;
 }
Beispiel #7
0
 // Constructor
 public RecurringAppointment(int recurrenceNumber, RecurrenceFrequency type, DateTime start, int length, string subject, string location)
 {
     this.recurrenceNumber    = recurrenceNumber;
     this.RecurrenceFrequency = type;
     this.start    = start;
     this.length   = length;
     this.subject  = subject;
     this.location = location;
 }
        public Recurrence(RecurrenceFrequency frequency, RecurrentSchedule schedule)
        {
            if (schedule == null)
            {
                throw new ArgumentNullException(nameof(schedule));
            }

            Frequency = frequency;
            Schedule  = schedule;
        }
 public RecurrenceRuleElement(RecurrenceFrequency frequency, List <RecurranceValue> values, DateTime?until, int?count, int?bySetPos, RecurrenceDayOfWeek?weekStart)
 {
     Frequency = frequency;
     Values    = values;
     Until     = until;
     WeekStart = weekStart;
     Count     = count;
     BySetPos  = bySetPos;
     WeekStart = weekStart;
 }
        internal static string ToSerializedValue(this RecurrenceFrequency value)
        {
            switch (value)
            {
            case RecurrenceFrequency.Daily:
                return("Daily");

            case RecurrenceFrequency.Weekly:
                return("Weekly");
            }
            return(null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
        /// </summary>
        public RecurrencePattern()
        {
            this.dayOfMonth     = null;
            this.daysOfWeekMask = RecurrenceDays.None;
            this.frequency      = RecurrenceFrequency.None;
            this.interval       = 1;
            this.monthOfYear    = null;
            this.dayOrdinal     = null;

            this.recursUntil    = null;
            this.maxOccurrences = null;
            this.firstDayOfWeek = DayOfWeek.Monday;
        }
Beispiel #12
0
        /// <summary>
        /// Get max recurrence for the job collection.
        /// </summary>
        /// <param name="frequencyInput">Frequence specified via powershell.</param>
        /// <param name="intervalInput">Interval specified via powershell.</param>
        /// <param name="minRecurrenceQuota">Min reurrence quota.</param>
        /// <param name="errorMessage">Error message for invalid recurrence.</param>
        /// <returns>Maximum recurrence.</returns>
        private JobMaxRecurrence GetMaxRecurrence(string frequencyInput, int?intervalInput, TimeSpan minRecurrenceQuota, string errorMessage)
        {
            int interval = intervalInput.HasValue ? intervalInput.Value : minRecurrenceQuota.GetInterval();
            RecurrenceFrequency frequency = frequencyInput.GetValueOrDefaultEnum <RecurrenceFrequency>(defaultValue: minRecurrenceQuota.GetFrequency());

            TimeSpan recurrenceTimeSpan = SchedulerUtility.ToTimeSpan(frequency, interval);

            if (recurrenceTimeSpan < minRecurrenceQuota)
            {
                throw new PSArgumentException(string.Format(errorMessage, recurrenceTimeSpan, minRecurrenceQuota));
            }

            return(new JobMaxRecurrence(frequency, interval));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
 /// </summary>
 public RecurrencePattern()
 {
     this.dayOfMonth     = null;
     this.daysOfWeekMask = RecurrenceDays.None;
     this.frequency      = RecurrenceFrequency.Daily;
     this.interval       = 1;
     this.monthOfYear    = null;
     this.dayOrdinal     = null;
     this._StartTime     = new TimeSpan(0, 0, 0);
     this._StopTime      = new TimeSpan(23, 59, 59);
     this._Times         = new List <TimeSpan>();
     this.dailyFrequency = RecurrenceFrequency.Minutely;
     this.dailyInterval  = 1;
     this.firstDayOfWeek = DayOfWeek.Monday;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
 /// </summary>
 /// <param name="dayOfMonth">The day of month.</param>
 /// <param name="daysOfWeekMask">The days of week mask.</param>
 /// <param name="frequency">The frequency.</param>
 /// <param name="interval">The interval.</param>
 /// <param name="monthOfYear">The month of year.</param>
 /// <param name="dayOrdinal">The week of month.</param>
 public RecurrencePattern(
     int?dayOfMonth,
     RecurrenceDays daysOfWeekMask,
     RecurrenceFrequency frequency,
     int interval,
     int?monthOfYear,
     int?dayOrdinal)
     : this()
 {
     this.dayOfMonth     = dayOfMonth;
     this.daysOfWeekMask = daysOfWeekMask;
     this.frequency      = frequency;
     this.interval       = interval;
     this.monthOfYear    = monthOfYear;
     this.dayOrdinal     = dayOrdinal;
 }
Beispiel #15
0
        private static void CreateOrUpdateJob(
            SchedulerManagementClient schedulerManagementClient,
            string resourceGroupName,
            string jobCollectionName,
            string jobName,
            RecurrenceFrequency recurrenceRequency)
        {
            var headers = new Dictionary <string, string>();

            var andomHour    = new Random();
            var randomMinute = new Random();
            var randomSecond = new Random();

            schedulerManagementClient.Jobs.CreateOrUpdate(
                resourceGroupName,
                jobCollectionName,
                jobName,
                new JobDefinition()
            {
                Properties = new JobProperties()
                {
                    StartTime = DateTime.UtcNow,
                    Action    = new JobAction()
                    {
                        Type    = JobActionType.Http,
                        Request = new HttpRequest()
                        {
                            Uri    = ConfigurationManager.AppSettings["HttpActionUrl"],
                            Method = "GET",
                        },
                        RetryPolicy = new RetryPolicy()
                        {
                            RetryType = RetryType.None,
                        }
                    },
                    Recurrence = new JobRecurrence()
                    {
                        Frequency = recurrenceRequency,
                        Interval  = 1,
                        Count     = 10000,
                    },
                    State = JobState.Enabled,
                }
            });
        }
        /// <summary>
        /// Converts RecurrencyFrequecy and Interval to TimeSpan.
        /// </summary>
        /// <param name="frequency">RecurrenceFrequency.</param>
        /// <param name="interval">Interval.</param>
        /// <returns></returns>
        public static TimeSpan ToTimeSpan(RecurrenceFrequency frequency, int interval)
        {
            DateTime epoch = DateTime.MinValue;

            switch (frequency)
            {
                case RecurrenceFrequency.Minute:
                    return epoch.AddMinutes(interval).Subtract(epoch);
                case RecurrenceFrequency.Hour:
                    return epoch.AddHours(interval).Subtract(epoch);
                case RecurrenceFrequency.Day:
                    return epoch.AddDays(interval).Subtract(epoch);
                case RecurrenceFrequency.Week:
                    return epoch.AddWeeks(interval).Subtract(epoch);
                case RecurrenceFrequency.Month:
                    return epoch.AddMonths(interval).Subtract(epoch);
                default:
                    throw new InvalidOperationException("Unsupported recurrence frequency.");
            }
        }
        internal static MonitorRecurrence DeserializeMonitorRecurrence(JsonElement element)
        {
            RecurrenceFrequency frequency = default;
            RecurrentSchedule   schedule  = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("frequency"))
                {
                    frequency = property.Value.GetString().ToRecurrenceFrequency();
                    continue;
                }
                if (property.NameEquals("schedule"))
                {
                    schedule = RecurrentSchedule.DeserializeRecurrentSchedule(property.Value);
                    continue;
                }
            }
            return(new MonitorRecurrence(frequency, schedule));
        }
Beispiel #18
0
        public static AppointmentRecurrencePatternStructure GetRecurrencePatternStructure(byte[] buffer)
        {
            RecurrenceFrequency frequency = (RecurrenceFrequency)LittleEndianConverter.ToInt16(buffer, 4);

            switch (frequency)
            {
            case RecurrenceFrequency.Daily:
                return(new DailyRecurrencePatternStructure(buffer));

            case RecurrenceFrequency.Weekly:
                return(new WeeklyRecurrencePatternStructure(buffer));

            case RecurrenceFrequency.Monthly:
                return(new MonthlyRecurrencePatternStructure(buffer));

            case RecurrenceFrequency.Yearly:
                return(new YearlyRecurrencePatternStructure(buffer));

            default:
                throw new InvalidRecurrencePatternException("Invalid recurrence pattern frequency");
            }
        }
        /// <summary>
        /// Handles the Click event of the saveButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void saveButton_Click(object sender, EventArgs e)
        {
            int numberOfOccurence = 0;

            if (occurenceTextBox.Text.Trim() != "")
            {
                try
                {
                    // Check for occurence
                    // Cant be 1 and more than a specific high number
                    numberOfOccurence = int.Parse(occurenceTextBox.Text);
                    if (numberOfOccurence > 999 || numberOfOccurence < 2)
                    {
                        MessageBox.Show("Please select a number between 2 and 999", "Invalid input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        occurenceTextBox.Text = "";
                        return;
                    }
                }
                catch
                {
                    // Cathing exception of error handling
                    MessageBox.Show("Please select a number between 2 and 999", "Invalid input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    occurenceTextBox.Text = "";
                }
            }
            TimeDuration duration = (TimeDuration)lengthComboBox.Items[lengthComboBox.SelectedIndex];
            int          length   = (duration.Hours * 60) + duration.Minutes;
            TimeSpan     timespan = (TimeSpan)startTimeComboBox.Items[startTimeComboBox.SelectedIndex];

            day = day.AddHours(timespan.TotalHours);
            RecurrenceFrequency type = (RecurrenceFrequency)frequencyComboBox.Items[frequencyComboBox.SelectedIndex];

            if (numberOfOccurence == 0)
            {
                return;
            }
            recurringAppointment = new RecurringAppointment(numberOfOccurence, type, day, length, subjectTextBox.Text, locationTextBox.Text);
            this.Close();
        }
Beispiel #20
0
        // http://msdn.microsoft.com/en-us/library/ee203303%28v=exchg.80%29
        /// <param name="period">In recurrence type units or recurrence frequency unit</param>
        /// <param name="startDTZone">Note: The date component of startDTZone may be different than the date of startDTUtc</param>
        public static int CalculateFirstDateTimeInDays(RecurrenceFrequency recurrenceFrequency, PatternType patternType, int period, DateTime startDTZone)
        {
            DateTime minimumDate = new DateTime(1601, 1, 1);

            switch (recurrenceFrequency)
            {
            case RecurrenceFrequency.Daily:
            {
                int daysSince1601 = (int)(startDTZone - minimumDate).TotalDays;
                return(daysSince1601 % period);
            }

            case RecurrenceFrequency.Weekly:
            {
                int daysSince1601 = (int)(DateTimeUtils.GetWeekStart(startDTZone) - minimumDate).TotalDays;
                int periodInDays  = period * 7;
                return(daysSince1601 % periodInDays);
            }

            case RecurrenceFrequency.Monthly:
            {
                int monthSpan = DateTimeHelper.GetMonthSpan(minimumDate, startDTZone);
                int remainder = monthSpan % period;
                return((int)(minimumDate.AddMonths(remainder) - minimumDate).TotalDays);
            }

            case RecurrenceFrequency.Yearly:
            {
                int monthSpan = DateTimeHelper.GetMonthSpan(minimumDate, startDTZone);
                int remainder = monthSpan % (period * 12);
                return((int)(minimumDate.AddMonths(remainder) - minimumDate).TotalDays);
            }

            default:
                throw new ArgumentException("Invalid Recurrence Frequency");
            }
        }
Beispiel #21
0
        static public Management.Monitor.Management.Models.RecurrenceFrequency ConvertNamespace(RecurrenceFrequency recurrenceFrequency)
        {
            int value = (int)recurrenceFrequency;

            return((Management.Monitor.Management.Models.RecurrenceFrequency)value);
        }
 /// <summary>
 /// Initializes a new instance of the Recurrence class.
 /// </summary>
 /// <param name="frequency">the recurrence frequency. How often the
 /// schedule profile should take effect. This value must be Week,
 /// meaning each week will have the same set of profiles. For example,
 /// to set a daily schedule, set **schedule** to every day of the week.
 /// The frequency property specifies that the schedule is repeated
 /// weekly. Possible values include: 'None', 'Second', 'Minute',
 /// 'Hour', 'Day', 'Week', 'Month', 'Year'</param>
 /// <param name="schedule">the scheduling constraints for when the
 /// profile begins.</param>
 public Recurrence(RecurrenceFrequency frequency, RecurrentSchedule schedule)
 {
     Frequency = frequency;
     Schedule  = schedule;
     CustomInit();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
 /// </summary>
 public RecurrencePattern(
     TimeSpan startTime,
     TimeSpan stopTime,
     List<TimeSpan> times,
     RecurrenceFrequency dailyFrequency,
     int dailyInterval,
     int? dayOfMonth,
     RecurrenceDays daysOfWeekMask,
     RecurrenceFrequency frequency,
     int interval,
     int? monthOfYear,
     int? dayOrdinal)
     : this()
 {
     this._StartTime = startTime;
     this._StopTime = stopTime;
     this._Times = times;
     this.dailyFrequency = dailyFrequency;
     this.dailyInterval = dailyInterval;
     this.dayOfMonth = dayOfMonth;
     this.daysOfWeekMask = daysOfWeekMask;
     this.frequency = frequency;
     this.interval = interval;
     this.monthOfYear = monthOfYear;
     this.dayOrdinal = dayOrdinal;
 }
 /// <summary>
 /// Initializes a new instance of the Recurrence class.
 /// </summary>
 /// <param name="frequency">the recurrence frequency. How often the
 /// schedule profile should take effect. This value must be Week,
 /// meaning each week will have the same set of profiles. Possible
 /// values include: 'None', 'Second', 'Minute', 'Hour', 'Day', 'Week',
 /// 'Month', 'Year'</param>
 /// <param name="schedule">the scheduling constraints for when the
 /// profile begins.</param>
 public Recurrence(RecurrenceFrequency frequency, RecurrentSchedule schedule)
 {
     Frequency = frequency;
     Schedule  = schedule;
 }
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
 /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
 /// <param name="formatProvider">not used by this TypeConverter.</param>
 /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
 /// <returns>
 /// an instance of <see cref="RecurrenceFrequency" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => RecurrenceFrequency.CreateFrom(sourceValue);
 /// <summary>
 /// Initializes a new instance of the <see cref="RecurrencePattern"/> class.
 /// </summary>
 public RecurrencePattern()
 {
     this.dayOfMonth = null;
     this.daysOfWeekMask = RecurrenceDays.None;
     this.frequency = RecurrenceFrequency.Daily;
     this.interval = 1;
     this.monthOfYear = null;
     this.dayOrdinal = null;
     this._StartTime = new TimeSpan(0, 0, 0);
     this._StopTime = new TimeSpan(23, 59, 59);
     this._Times = new List<TimeSpan>();
     this.dailyFrequency = RecurrenceFrequency.Minutely;
     this.dailyInterval = 1;
     this.firstDayOfWeek = DayOfWeek.Monday;
 }
        private AppointmentRecurrencePatternStructure GetRecurrencePattern(TimeZoneInfo timezone)
        {
            AppointmentRecurrencePatternStructure structure;
            RecurrenceFrequency recurrenceFrequency = RecurrenceTypeHelper.GetRecurrenceFrequency(RecurrenceType);
            PatternType         patternType         = RecurrenceTypeHelper.GetPatternType(RecurrenceType);

            switch (recurrenceFrequency)
            {
            case RecurrenceFrequency.Daily:
                structure = new DailyRecurrencePatternStructure();
                break;

            case RecurrenceFrequency.Weekly:
                structure = new WeeklyRecurrencePatternStructure();
                ((WeeklyRecurrencePatternStructure)structure).DaysOfWeek = (DaysOfWeekFlags)Day;
                break;

            case RecurrenceFrequency.Monthly:
                structure = new MonthlyRecurrencePatternStructure();
                if (patternType == PatternType.Month)
                {
                    ((MonthlyRecurrencePatternStructure)structure).DayOfMonth = (uint)Day;
                }
                else
                {
                    ((MonthlyRecurrencePatternStructure)structure).DayOfWeek          = (OutlookDayOfWeek)Day;
                    ((MonthlyRecurrencePatternStructure)structure).DayOccurenceNumber = DayOccurenceNumber;
                }
                break;

            case RecurrenceFrequency.Yearly:
                structure = new YearlyRecurrencePatternStructure();
                if (patternType == PatternType.Month)
                {
                    ((YearlyRecurrencePatternStructure)structure).DayOfMonth = (uint)Day;
                }
                else
                {
                    ((YearlyRecurrencePatternStructure)structure).DayOfWeek          = (OutlookDayOfWeek)Day;
                    ((YearlyRecurrencePatternStructure)structure).DayOccurenceNumber = DayOccurenceNumber;
                }
                break;

            default:
                throw new InvalidRecurrencePatternException("Recurrence frequency is invalid");
            }
            structure.PatternType = patternType;
            structure.PeriodInRecurrenceTypeUnits = Period;
            structure.SetStartAndDuration(m_startDTUtc, m_duration, timezone);
            DateTime startDTZone = TimeZoneInfo.ConvertTimeFromUtc(m_startDTUtc, timezone);

            structure.FirstDateTimeInDays   = AppointmentRecurrencePatternStructure.CalculateFirstDateTimeInDays(recurrenceFrequency, patternType, Period, startDTZone);
            structure.LastInstanceStartDate = m_lastInstanceStartDate;
            if (EndAfterNumberOfOccurences)
            {
                structure.OccurrenceCount = (uint)CalendarHelper.CalculateNumberOfOccurences(StartDTUtc, m_lastInstanceStartDate, this.RecurrenceType, Period, Day);
                structure.EndType         = RecurrenceEndType.EndAfterNOccurrences;
            }
            else if (m_lastInstanceStartDate.Year >= 4500)
            {
                structure.EndType         = RecurrenceEndType.NeverEnd;
                structure.OccurrenceCount = 10;
            }
            else
            {
                structure.EndType = RecurrenceEndType.EndAfterDate;
                // OccurrenceCount should not be 0, or otherwise Outlook 2003's Appointment recurrence window is not loaded properly
                structure.OccurrenceCount = 10;
            }

            structure.DeletedInstanceDates = DeletedInstanceDates;
            foreach (ExceptionInfoStructure exception in ExceptionList)
            {
                structure.ModifiedInstanceDates.Add(DateTimeUtils.GetDayStart(exception.NewStartDT));
            }
            structure.ExceptionList = ExceptionList;
            return(structure);
        }
Beispiel #28
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 url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";

            url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // 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;
            url = url.Replace(" ", "%20");

            // 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();
                }
            }
        }
        }                                                   // default Monday

        #region Constructors

        public RecurrenceRuleElement(RecurrenceFrequency frequency, List <RecurranceValue> values) :
            this(frequency, values, null, null, null, null)
        {
        }
 public static string ToSerialString(this RecurrenceFrequency value) => value switch
 {
 public RecurrenceRuleElement(RecurrenceFrequency frequency, List <RecurranceValue> values, DateTime?until, int?bySetPos) :
     this(frequency, values, until, null, bySetPos, null)
 {
 }
Beispiel #32
0
        public AppointmentRecurrencePatternStructure(byte[] buffer)
        {
            int position = 0;

            ReaderVersion  = LittleEndianReader.ReadUInt16(buffer, ref position);
            WriterVersion  = LittleEndianReader.ReadUInt16(buffer, ref position);
            RecurFrequency = (RecurrenceFrequency)LittleEndianReader.ReadUInt16(buffer, ref position);
            PatternType    = (PatternType)LittleEndianReader.ReadUInt16(buffer, ref position);
            CalendarType   = LittleEndianReader.ReadUInt16(buffer, ref position);
            FirstDateTime  = LittleEndianReader.ReadUInt32(buffer, ref position);
            Period         = LittleEndianReader.ReadUInt32(buffer, ref position);
            SlidingFlag    = LittleEndianReader.ReadUInt32(buffer, ref position);

            ReadPatternTypeSpecific(buffer, ref position);

            EndType = (RecurrenceEndType)LittleEndianReader.ReadUInt32(buffer, ref position);
            if ((uint)EndType == 0xFFFFFFFF) // SHOULD be 0x00002023 but can be 0xFFFFFFFF
            {
                EndType = RecurrenceEndType.NeverEnd;
            }
            OccurrenceCount = LittleEndianReader.ReadUInt32(buffer, ref position);
            FirstDOW        = LittleEndianReader.ReadUInt32(buffer, ref position);
            uint DeletedInstanceCount = LittleEndianReader.ReadUInt32(buffer, ref position);

            for (int index = 0; index < DeletedInstanceCount; index++)
            {
                DateTime date = DateTimeHelper.ReadDateTimeFromMinutes(buffer, ref position);
                DeletedInstanceDates.Add(date);
            }

            uint ModifiedInstanceCount = LittleEndianReader.ReadUInt32(buffer, ref position);

            if (ModifiedInstanceCount > DeletedInstanceCount)
            {
                throw new InvalidRecurrencePatternException("Invalid structure format");
            }
            for (int index = 0; index < ModifiedInstanceCount; index++)
            {
                DateTime date = DateTimeHelper.ReadDateTimeFromMinutes(buffer, ref position);
                ModifiedInstanceDates.Add(date);
            }

            StartDate = DateTimeHelper.ReadDateTimeFromMinutes(buffer, ref position);
            // end date will be in 31/12/4500 23:59:00 if there is no end date
            EndDate = DateTimeHelper.ReadDateTimeFromMinutes(buffer, ref position);

            ReaderVersion2 = LittleEndianReader.ReadUInt32(buffer, ref position);
            WriterVersion2 = LittleEndianReader.ReadUInt32(buffer, ref position);

            StartTimeOffset = LittleEndianReader.ReadUInt32(buffer, ref position);
            EndTimeOffset   = LittleEndianReader.ReadUInt32(buffer, ref position);
            ushort exceptionCount = LittleEndianReader.ReadUInt16(buffer, ref position);

            if (exceptionCount != ModifiedInstanceCount)
            {
                // This MUST be the same value as the value of the ModifiedInstanceCount in the associated ReccurencePattern structure
                throw new InvalidRecurrencePatternException("Invalid structure format");
            }
            for (int index = 0; index < exceptionCount; index++)
            {
                ExceptionInfoStructure exception = new ExceptionInfoStructure(buffer, position);
                ExceptionList.Add(exception);
                position += exception.RecordLength;
            }

            // Outlook 2003 SP3 was observed using a signature of older version (0x3006) when there was no need for extended exception
            if (WriterVersion2 >= Outlook2003VersionSignature)
            {
                uint reservedBlock1Size = LittleEndianReader.ReadUInt32(buffer, ref position);
                position += (int)reservedBlock1Size;

                foreach (ExceptionInfoStructure exception in ExceptionList)
                {
                    exception.ReadExtendedException(buffer, ref position, WriterVersion2);
                }

                uint reservedBlock2Size = LittleEndianReader.ReadUInt32(buffer, ref position);
                position += (int)reservedBlock2Size;
            }
        }
 public RecurrenceRuleElement(RecurrenceFrequency frequency, List <RecurranceValue> values, int?count, int?bySetPos) :
     this(frequency, values, null, count, bySetPos, null)
 {
 }