예제 #1
0
파일: Trigger.cs 프로젝트: clamwin/clamwind
 /// <summary>
 /// Creates a MonthlyTrigger that fires only during specified months of the year.
 /// </summary>
 /// <param name="hour">Hour of day trigger will fire.</param>
 /// <param name="minutes">Minutes of hour (specified in "hour") trigger will fire.</param>
 /// <param name="daysOfMonth">Days of the month trigger will fire.  (See <see cref="Days"/> property.</param>
 /// <param name="months">Months of the year trigger will fire.</param>
 public MonthlyTrigger(short hour, short minutes, int[] daysOfMonth, MonthsOfTheYear months) : base()
 {
     SetStartTime((ushort)hour, (ushort)minutes);
     taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_MONTHLYDATE;
     taskTrigger.Data.monthlyDate.Months = (ushort)months;
     taskTrigger.Data.monthlyDate.Days   = (uint)IndicesToMask(daysOfMonth);
 }
예제 #2
0
        static void Main(string[] args)
        {
            MonthsOfTheYear march = MonthsOfTheYear.March;

            Console.WriteLine("{0} is the month of maying.\n", march);

            bool b1 = true;

            do
            {
                DaysOfTheWeek favouriteDay;
                Console.Write("Enter a number for your favourite day: ");
                string strVar = Console.ReadLine();

                if (Enum.TryParse(strVar, out favouriteDay))
                {
                    Console.WriteLine("{0} is your favourite day.", favouriteDay);
                    b1 = false;
                }
                else
                {
                    Console.WriteLine("Try Again!");
                    b1 = true;
                }
            } while(b1);

            Console.ReadKey();
        }
예제 #3
0
        private static IEnumerable <Int32> GetMonthNumbers(MonthsOfTheYear monthsOfTheYear)
        {
            foreach (var monthOfTheYear in Enum.GetValues(typeof(MonthsOfTheYear)).Cast <MonthsOfTheYear>().Where(flag => monthsOfTheYear.HasFlag(flag)))
            {
                switch (monthOfTheYear)
                {
                case MonthsOfTheYear.January:   yield return(1);   break;

                case MonthsOfTheYear.February:  yield return(2);   break;

                case MonthsOfTheYear.March:     yield return(3);   break;

                case MonthsOfTheYear.April:     yield return(4);   break;

                case MonthsOfTheYear.May:       yield return(5);   break;

                case MonthsOfTheYear.June:      yield return(6);   break;

                case MonthsOfTheYear.July:      yield return(7);   break;

                case MonthsOfTheYear.August:    yield return(8);   break;

                case MonthsOfTheYear.September: yield return(9);   break;

                case MonthsOfTheYear.October:   yield return(10);  break;

                case MonthsOfTheYear.November:  yield return(11);  break;

                case MonthsOfTheYear.December:  yield return(12);  break;
                }
            }
        }
예제 #4
0
 public MonthlyDOWTrigger(DaysOfTheWeek daysOfWeek = (DaysOfTheWeek)1, MonthsOfTheYear monthsOfYear = (MonthsOfTheYear)0xfff, WhichWeek weeksOfMonth = (WhichWeek)1)
     : base(TaskTriggerType.MonthlyDOW)
 {
     DaysOfWeek   = daysOfWeek;
     MonthsOfYear = monthsOfYear;
     WeeksOfMonth = weeksOfMonth;
 }
 /// <summary>
 /// Creates a MonthlyDowTrigger that fires during specified months only.
 /// </summary>
 /// <param name="hour">Hour of day trigger will fire.</param>
 /// <param name="minutes">Minute of the hour trigger will fire.</param>
 /// <param name="daysOfTheWeek">Days of the week trigger will fire.</param>
 /// <param name="whichWeeks">Weeks of the month trigger will fire.</param>
 /// <param name="months">Months of the year trigger will fire.</param>
 public MonthlyDowTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek, WhichWeek whichWeeks, MonthsOfTheYear months) : base()
 {
     SetStartTime((ushort)hour, (ushort)minutes);
     taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_MONTHLYDOW;
     taskTrigger.Data.monthlyDOW.WhichWeek = (ushort)whichWeeks;
     taskTrigger.Data.monthlyDOW.DaysOfTheWeek = (ushort)daysOfTheWeek;
     taskTrigger.Data.monthlyDOW.Months = (ushort)months;
 }
 internal TriggerBuilder(BuilderInfo taskBuilder, MonthsOfTheYear moy)
     : this(taskBuilder)
 {
     TaskDef.Triggers.Add(trigger = new MonthlyTrigger()
     {
         MonthsOfYear = moy
     });
 }
예제 #7
0
        public void ShowMonths()
        {
            MonthsOfTheYear monthOfTheYear = MonthsOfTheYear.January;

            for (int i = 0; i < 12; i++)
            {
                Console.WriteLine($"{i + 1}. {monthOfTheYear.ToPolishString()}");
                monthOfTheYear += 1;
            }
        }
예제 #8
0
        /// <summary>
        /// Check if the "month" parameter is one of the months inside the enumeration "MonthsOfTheYear"
        /// This function is able to translate the number of the month to one of MonthsOfTheYear enum values
        /// </summary>
        /// <param name="month">The month as a number e.g. January (1), February (2), March (3), April (4) ...</param>
        /// <param name="monthsOfTheYear">An enumeration containing one or many months values like None (0), January (1), February (2), March (4), April (8) ...</param>
        /// <returns>True if there is an equivalent month inside the "MonthsOfTheYear" enumeration, otherwise False</returns>
        static public bool ContainsMonthsOfTheYear(int month, MonthsOfTheYear monthsOfTheYear)
        {
            if (month < 1 || month > 12)
            {
                return(false);
            }
            MonthsOfTheYear test = (MonthsOfTheYear)(int)Math.Pow(2, month - 1);

            if ((test & monthsOfTheYear) != MonthsOfTheYear.None)
            {
                return(true);
            }

            return(false);
        }
예제 #9
0
        private static string GetCultureEquivalentString(MonthsOfTheYear val) {
            if (val == MonthsOfTheYear.AllMonths) {
                return Resources.MOYAllMonths;
            }

            var s = new List<string>(12);
            var vals = Enum.GetValues(val.GetType());
            for (var i = 0; i < vals.Length - 1; i++) {
                if ((val & (MonthsOfTheYear)vals.GetValue(i)) > 0) {
                    s.Add(DateTimeFormatInfo.CurrentInfo.GetMonthName(i + 1));
                }
            }

            return string.Join(Resources.ListSeparator, s.ToArray());
        }
예제 #10
0
        static void Main(string[] args)
        {
            string month;

            Console.WriteLine("Give me a number: ");
            int             month_int  = Convert.ToInt32(Console.ReadLine());
            MonthsOfTheYear month_enum = (MonthsOfTheYear)month_int;

            if (month_int >= 1 && month_int < 13)
            {
                Console.WriteLine(month_enum);
            }
            else
            {
                Console.WriteLine("The number does not fall in the range of 1 to 12");
            }
            Console.ReadKey();
        }
예제 #11
0
        public static string ToPolishString(this MonthsOfTheYear monthsOfTheYear)
        {
            switch (monthsOfTheYear)
            {
            case MonthsOfTheYear.January:
                return("Styczeń");

            case MonthsOfTheYear.February:
                return("Luty");

            case MonthsOfTheYear.March:
                return("Marzec");

            case MonthsOfTheYear.April:
                return("Kwiecień");

            case MonthsOfTheYear.May:
                return("Maj");

            case MonthsOfTheYear.June:
                return("Czerwiec");

            case MonthsOfTheYear.July:
                return("Lipiec");

            case MonthsOfTheYear.August:
                return("Sierpień");

            case MonthsOfTheYear.September:
                return("Wrzesień");

            case MonthsOfTheYear.October:
                return("Październik");

            case MonthsOfTheYear.November:
                return("Listopad");

            case MonthsOfTheYear.December:
                return("Grudzień");

            default:
                return("NotSet");
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            // Get the month number from the user.
            Console.WriteLine("Enter a number from 1 to 12: ");
            int monthNumber = Convert.ToInt32(Console.ReadLine());

            // Check the range to make sure it is valid.
            if (monthNumber > 0 && monthNumber <= 12)
            {
                // Print out the corresponding month name.
                MonthsOfTheYear month = (MonthsOfTheYear)monthNumber;
                Console.WriteLine(month);
            }
            else // If it's not in the right range, print an error message.
            {
                Console.WriteLine("That number was too high or too low.");
            }

            Console.ReadKey();
        }
예제 #13
0
        private static string ToMonthOfTheYearString(MonthsOfTheYear monthsOfTheYear)
        {
            var dictionary = new[]
            {
                new { Key = MonthsOfTheYear.January, Resource = Resources.Word_January },
                new { Key = MonthsOfTheYear.February, Resource = Resources.Word_February },
                new { Key = MonthsOfTheYear.March, Resource = Resources.Word_March },
                new { Key = MonthsOfTheYear.April, Resource = Resources.Word_April },
                new { Key = MonthsOfTheYear.May, Resource = Resources.Word_May },
                new { Key = MonthsOfTheYear.June, Resource = Resources.Word_June },
                new { Key = MonthsOfTheYear.July, Resource = Resources.Word_July },
                new { Key = MonthsOfTheYear.August, Resource = Resources.Word_August },
                new { Key = MonthsOfTheYear.September, Resource = Resources.Word_September },
                new { Key = MonthsOfTheYear.October, Resource = Resources.Word_October },
                new { Key = MonthsOfTheYear.November, Resource = Resources.Word_November },
                new { Key = MonthsOfTheYear.December, Resource = Resources.Word_December },
            };

            return(string.Join(", ", dictionary.Where(arg => (monthsOfTheYear & arg.Key) == arg.Key).Select(arg => arg.Resource)));
        }
예제 #14
0
        private static string GetCultureEquivalentString(MonthsOfTheYear val)
        {
            if (val == MonthsOfTheYear.AllMonths)
            {
                return(Resources.MOYAllMonths);
            }

            List <string> s    = new List <string>(12);
            Array         vals = Enum.GetValues(val.GetType());

            for (int i = 0; i < vals.Length - 1; i++)
            {
                if ((val & (MonthsOfTheYear)vals.GetValue(i)) > 0)
                {
                    s.Add(DateTimeFormatInfo.CurrentInfo.GetMonthName(i + 1));
                }
            }

            return(string.Join(Resources.ListSeparator, s.ToArray()));
        }
 /// <summary>
 /// Adds a trigger that executes monthly on specific days.
 /// </summary>
 /// <param name="moy">The months of the year in which to run.</param>
 /// <returns><see cref="MonthlyTriggerBuilder" /> instance.</returns>
 public MonthlyTriggerBuilder InTheMonthOf(MonthsOfTheYear moy)
 {
     return new MonthlyTriggerBuilder(tb, moy);
 }
        /// <summary>
        /// Creates a trigger using a cron string.
        /// </summary>
        /// <param name="cronString">String using cron defined syntax for specifying a time interval. See remarks for syntax.</param>
        /// <returns>Array of <see cref="Trigger" /> representing the specified cron string.</returns>
        /// <exception cref="System.NotImplementedException">Unsupported cron string.</exception>
        /// <remarks>
        ///   <para>NOTE: This method does not support all combinations of cron strings. Please test extensively before use. Please post an issue with any syntax that should work, but doesn't.</para>
        ///   <para>Currently the cronString only supports numbers and not any of the weekday or month strings. Please use numeric equivalent.</para>
        ///   <para>This section borrows liberally from the site http://www.nncron.ru/help/EN/working/cron-format.htm. The cron format consists of five fields separated by white spaces:</para>
        ///   <code>
        ///   &lt;Minute&gt; &lt;Hour&gt; &lt;Day_of_the_Month&gt; &lt;Month_of_the_Year&gt; &lt;Day_of_the_Week&gt;
        ///   </code>
        ///   <para>Each item has bounds as defined by the following:</para>
        ///   <code>
        ///   * * * * *
        ///   | | | | |
        ///   | | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
        ///   | | | +------ Month of the Year (range: 1-12)
        ///   | | +-------- Day of the Month  (range: 1-31)
        ///   | +---------- Hour              (range: 0-23)
        ///   +------------ Minute            (range: 0-59)
        ///   </code>
        ///   <para>Any of these 5 fields may be an asterisk (*). This would mean the entire range of possible values, i.e. each minute, each hour, etc.</para>
        ///   <para>Any of the first 4 fields can be a question mark ("?"). It stands for the current time, i.e. when a field is processed, the current time will be substituted for the question mark: minutes for Minute field, hour for Hour field, day of the month for Day of month field and month for Month field.</para>
        ///   <para>Any field may contain a list of values separated by commas, (e.g. 1,3,7) or a range of values (two integers separated by a hyphen, e.g. 1-5).</para>
        ///   <para>After an asterisk (*) or a range of values, you can use character / to specify that values are repeated over and over with a certain interval between them. For example, you can write "0-23/2" in Hour field to specify that some action should be performed every two hours (it will have the same effect as "0,2,4,6,8,10,12,14,16,18,20,22"); value "*/4" in Minute field means that the action should be performed every 4 minutes, "1-30/3"  means the same as "1,4,7,10,13,16,19,22,25,28".</para>
        /// </remarks>
        public static Trigger[] FromCronFormat(string cronString)
        {
            CronExpression cron = new CronExpression();

            cron.Parse(cronString);

            // TODO: Figure out all the permutations of expression and convert to Trigger(s)

            /* Time (fields 1-4 have single number and dow = *)
             * Time repeating
             * Daily
             * Weekly
             * Monthly
             * Monthly DOW
             */

            List <Trigger> ret = new List <Trigger>();

            // MonthlyDOWTrigger
            if (!cron.DOW.IsEvery)
            {
                // Determine DOW
                DaysOfTheWeek dow = 0;
                if (cron.DOW.vals.Length == 0)
                {
                    dow = DaysOfTheWeek.AllDays;
                }
                else if (cron.DOW.range)
                {
                    for (int i = cron.DOW.vals[0]; i <= cron.DOW.vals[1]; i += cron.DOW.step)
                    {
                        dow |= (DaysOfTheWeek)(1 << (i - 1));
                    }
                }
                else
                {
                    for (int i = 0; i < cron.DOW.vals.Length; i++)
                    {
                        dow |= (DaysOfTheWeek)(1 << (cron.DOW.vals[i] - 1));
                    }
                }

                // Determine months
                MonthsOfTheYear moy = 0;
                if ((cron.Months.vals.Length == 0 || (cron.Months.vals.Length == 1 && cron.Months.vals[0] == 1)) && cron.Months.IsEvery)
                {
                    moy = MonthsOfTheYear.AllMonths;
                }
                else if (cron.Months.range)
                {
                    for (int i = cron.Months.vals[0]; i <= cron.Months.vals[1]; i += cron.Months.step)
                    {
                        moy |= (MonthsOfTheYear)(1 << (i - 1));
                    }
                }
                else
                {
                    for (int i = 0; i < cron.Months.vals.Length; i++)
                    {
                        moy |= (MonthsOfTheYear)(1 << (cron.Months.vals[i] - 1));
                    }
                }

                Trigger tr = new MonthlyDOWTrigger(dow, moy, WhichWeek.AllWeeks);
                ret.AddRange(ProcessCronTimes(cron, tr));
            }
            // MonthlyTrigger
            else if (cron.Days.vals.Length > 0)
            {
                // Determine DOW
                List <int> days = new List <int>();
                if (cron.Days.range)
                {
                    for (int i = cron.Days.vals[0]; i <= cron.Days.vals[1]; i += cron.Days.step)
                    {
                        days.Add(i);
                    }
                }
                else
                {
                    for (int i = 0; i < cron.Days.vals.Length; i++)
                    {
                        days.Add(cron.Days.vals[i]);
                    }
                }

                // Determine months
                MonthsOfTheYear moy = 0;
                if ((cron.Months.vals.Length == 0 || (cron.Months.vals.Length == 1 && cron.Months.vals[0] == 1)) && cron.Months.IsEvery)
                {
                    moy = MonthsOfTheYear.AllMonths;
                }
                else if (cron.Months.range)
                {
                    for (int i = cron.Months.vals[0]; i <= cron.Months.vals[1]; i += cron.Months.step)
                    {
                        moy |= (MonthsOfTheYear)(1 << (i - 1));
                    }
                }
                else
                {
                    for (int i = 0; i < cron.Months.vals.Length; i++)
                    {
                        moy |= (MonthsOfTheYear)(1 << (cron.Months.vals[i] - 1));
                    }
                }

                Trigger tr = new MonthlyTrigger(1, moy)
                {
                    DaysOfMonth = days.ToArray()
                };
                ret.AddRange(ProcessCronTimes(cron, tr));
            }
            // DailyTrigger
            else if (cron.Months.IsEvery && cron.DOW.IsEvery && cron.Days.repeating)
            {
                Trigger tr = new DailyTrigger((short)cron.Days.step);
                ret.AddRange(ProcessCronTimes(cron, tr));
            }
            else
            {
                throw new NotImplementedException();
            }

            return(ret.ToArray());
        }
예제 #17
0
		/// <summary>
		/// Creates a MonthlyTrigger that fires only during specified months of the year.
		/// </summary>
		/// <param name="hour">Hour of day trigger will fire.</param>
		/// <param name="minutes">Minutes of hour (specified in "hour") trigger will fire.</param>
		/// <param name="daysOfMonth">Days of the month trigger will fire.  (See <see cref="Days"/> property.</param>
		/// <param name="months">Months of the year trigger will fire.</param>
		public MonthlyTrigger(short hour, short minutes, int[] daysOfMonth, MonthsOfTheYear months): base() {
			SetStartTime((ushort)hour, (ushort)minutes);
			taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_MONTHLYDATE;
			taskTrigger.Data.monthlyDate.Months = (ushort)months;
			taskTrigger.Data.monthlyDate.Days = (uint)IndicesToMask(daysOfMonth);
		}
 /// <summary>
 /// Adds a trigger that executes monthly on specific days.
 /// </summary>
 /// <param name="moy">The months of the year in which to run.</param>
 /// <returns><see cref="MonthlyTriggerBuilder" /> instance.</returns>
 public MonthlyTriggerBuilder InTheMonthOf(MonthsOfTheYear moy) => new MonthlyTriggerBuilder(tb, moy);
예제 #19
0
 public MonthlyTrigger(int dayOfMonth = 1, MonthsOfTheYear monthsOfYear = (MonthsOfTheYear)0xfff)
     : base(TaskTriggerType.Monthly)
 {
     DaysOfMonth  = new int[] { dayOfMonth };
     MonthsOfYear = monthsOfYear;
 }
예제 #20
0
 public Month(MonthsOfTheYear month, double temp, int sed)
 {
     this.MonthProp = month;
     AverTemp = temp;
     Sediment = sed;
 }
 internal TriggerBuilder(BuilderInfo taskBuilder, MonthsOfTheYear moy)
     : this(taskBuilder)
 {
     TaskDef.Triggers.Add(trigger = new MonthlyTrigger() { MonthsOfYear = moy });
 }
예제 #22
0
파일: Trigger.cs 프로젝트: hpie/hpie
 /// <summary>
 /// Creates an unbound instance of a <see cref="MonthlyDOWTrigger"/>.
 /// </summary>
 /// <param name="daysOfWeek">The days of the week.</param>
 /// <param name="monthsOfYear">The months of the year.</param>
 /// <param name="weeksOfMonth">The weeks of the month.</param>
 public MonthlyDOWTrigger(DaysOfTheWeek daysOfWeek = DaysOfTheWeek.Sunday, MonthsOfTheYear monthsOfYear = MonthsOfTheYear.AllMonths, WhichWeek weeksOfMonth = WhichWeek.FirstWeek)
     : base(TaskTriggerType.MonthlyDOW)
 {
     this.DaysOfWeek = daysOfWeek;
     this.MonthsOfYear = monthsOfYear;
     this.WeeksOfMonth = weeksOfMonth;
 }
예제 #23
0
파일: Trigger.cs 프로젝트: hpie/hpie
 /// <summary>
 /// Creates an unbound instance of a <see cref="MonthlyTrigger"/>.
 /// </summary>
 /// <param name="dayOfMonth">The day of the month.</param>
 /// <param name="monthsOfYear">The months of the year.</param>
 public MonthlyTrigger(int dayOfMonth = 1, MonthsOfTheYear monthsOfYear = MonthsOfTheYear.AllMonths)
     : base(TaskTriggerType.Monthly)
 {
     this.DaysOfMonth = new int[] { dayOfMonth };
     this.MonthsOfYear = monthsOfYear;
 }
 internal MonthlyTriggerBuilder(BuilderInfo taskBuilder, MonthsOfTheYear moy)
     : base(taskBuilder)
 {
     this.trb = new TriggerBuilder(taskBuilder, moy);
 }
 /// <summary>
 /// Adds a trigger that executes monthly on specific days.
 /// </summary>
 /// <param name="moy">The months of the year in which to run.</param>
 /// <returns><see cref="MonthlyTriggerBuilder" /> instance.</returns>
 public MonthlyTriggerBuilder InTheMonthOf(MonthsOfTheYear moy)
 {
     return(new MonthlyTriggerBuilder(tb, moy));
 }
 internal MonthlyTriggerBuilder(BuilderInfo taskBuilder, MonthsOfTheYear moy)
     : base(taskBuilder)
 {
     this.trb = new TriggerBuilder(taskBuilder, moy);
 }
예제 #27
0
        /// <summary>Creates a trigger using a cron string.</summary>
        /// <param name="cronString">String using cron defined syntax for specifying a time interval. See remarks for syntax.</param>
        /// <returns>Array of <see cref="Trigger"/> representing the specified cron string.</returns>
        /// <exception cref="System.NotImplementedException">Unsupported cron string.</exception>
        /// <remarks>
        /// <note type="note"> This method does not support all combinations of cron strings. Please test extensively before use. Please post an issue with any
        /// syntax that should work, but doesn't.</note>
        /// <para>The following combinations are known <c>not</c> to work:</para>
        /// <list type="bullet">
        /// <item><description>Intervals on months (e.g. "* * * */5 *")</description></item>
        /// <item><description>Intervals on DOW (e.g. "* * * * MON/3")</description></item>
        /// </list>
        /// <para>
        /// This section borrows liberally from the site http://www.nncron.ru/help/EN/working/cron-format.htm. The cron format consists of five fields separated
        /// by white spaces:
        /// </para>
        /// <code>
        ///   &lt;Minute&gt; &lt;Hour&gt; &lt;Day_of_the_Month&gt; &lt;Month_of_the_Year&gt; &lt;Day_of_the_Week&gt;
        /// </code>
        /// <para>Each item has bounds as defined by the following:</para>
        /// <code>
        ///   * * * * *
        ///   | | | | |
        ///   | | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
        ///   | | | +------ Month of the Year (range: 1-12)
        ///   | | +-------- Day of the Month  (range: 1-31)
        ///   | +---------- Hour              (range: 0-23)
        ///   +------------ Minute            (range: 0-59)
        /// </code>
        /// <para>Any of these 5 fields may be an asterisk (*). This would mean the entire range of possible values, i.e. each minute, each hour, etc.</para>
        /// <para>
        /// Any of the first 4 fields can be a question mark ("?"). It stands for the current time, i.e. when a field is processed, the current time will be
        /// substituted for the question mark: minutes for Minute field, hour for Hour field, day of the month for Day of month field and month for Month field.
        /// </para>
        /// <para>Any field may contain a list of values separated by commas, (e.g. 1,3,7) or a range of values (two integers separated by a hyphen, e.g. 1-5).</para>
        /// <para>
        /// After an asterisk (*) or a range of values, you can use character / to specify that values are repeated over and over with a certain interval between
        /// them. For example, you can write "0-23/2" in Hour field to specify that some action should be performed every two hours (it will have the same effect
        /// as "0,2,4,6,8,10,12,14,16,18,20,22"); value "*/4" in Minute field means that the action should be performed every 4 minutes, "1-30/3" means the same
        /// as "1,4,7,10,13,16,19,22,25,28".
        /// </para>
        /// </remarks>
        public static Trigger[] FromCronFormat([NotNull] string cronString)
        {
            var cron = CronExpression.Parse(cronString);

            System.Diagnostics.Debug.WriteLine($"{cronString}=M:{cron.Minutes}; H:{cron.Hours}; D:{cron.Days}; M:{cron.Months}; W:{cron.DOW}");

            var ret = new List <Trigger>();

            // There isn't a clean mechanism to handle intervals on DOW or months, so punt
            if (cron.DOW.IsIncr)
            {
                throw new NotSupportedException();
            }
            if (cron.Months.IsIncr)
            {
                throw new NotSupportedException();
            }

            // MonthlyDOWTrigger
            if (!cron.DOW.IsEvery)
            {
                // Determine DOW
                DaysOfTheWeek dow = 0;
                foreach (var i in cron.DOW.Values)
                {
                    dow |= (DaysOfTheWeek)(1 << i);
                }

                // Determine months
                MonthsOfTheYear moy = 0;
                if (cron.Months.IsEvery)
                {
                    moy = MonthsOfTheYear.AllMonths;
                }
                else
                {
                    foreach (var i in cron.Months.Values)
                    {
                        moy |= (MonthsOfTheYear)(1 << (i - 1));
                    }
                }

                var tr = new MonthlyDOWTrigger(dow, moy, WhichWeek.AllWeeks);
                ret.AddRange(ProcessCronTimes(cron, tr));
            }

            // MonthlyTrigger
            if (!cron.Days.IsEvery)
            {
                // Determine months
                MonthsOfTheYear moy = 0;
                if (cron.Months.IsEvery)
                {
                    moy = MonthsOfTheYear.AllMonths;
                }
                else
                {
                    foreach (var i in cron.Months.Values)
                    {
                        moy |= (MonthsOfTheYear)(1 << (i - 1));
                    }
                }

                var tr = new MonthlyTrigger(1, moy)
                {
                    DaysOfMonth = cron.Days.Values.ToArray()
                };
                ret.AddRange(ProcessCronTimes(cron, tr));
            }

            // DailyTrigger
            else if (cron.Months.IsEvery && (cron.Days.IsEvery || cron.Days.IsIncr))
            {
                var tr = new DailyTrigger((short)cron.Days.Increment);
                ret.AddRange(ProcessCronTimes(cron, tr));
            }
            else
            {
                if (ret.Count == 0)
                {
                    throw new NotSupportedException();
                }
            }

            return(ret.ToArray());
        }
 /// <summary>
 /// Updates a monthly trigger to specify the months of the year in which it will run.
 /// </summary>
 /// <param name="moy">The month of the year.</param>
 /// <returns>
 ///   <see cref="TriggerBuilder" /> instance.
 /// </returns>
 public TriggerBuilder Of(MonthsOfTheYear moy)
 {
     ((MonthlyDOWTrigger)trb.trigger).MonthsOfYear = moy;
     return trb;
 }
예제 #29
0
    private void SaveTriggers()
    {
        for (int i = currentTaskDefinition.Triggers.Count - 1; i >= 0; i--)
        {
            if (currentTaskDefinition.Triggers[i] is WeeklyTrigger)
            {
                currentTaskDefinition.Triggers.RemoveAt(i);
                continue;
            }
            if (currentTaskDefinition.Triggers[i] is MonthlyTrigger)
            {
                currentTaskDefinition.Triggers.RemoveAt(i);
            }
        }

        foreach (DataRow dr in DS.Tables[dtSchedule.TableName].Rows)
        {
            short h = Convert.ToInt16(dr[SStartHour.ColumnName]);
            short m = Convert.ToInt16(dr[SStartMinute.ColumnName]);

            triggerDays = 0;
            AddDay(dr, DaysOfTheWeek.Monday);
            AddDay(dr, DaysOfTheWeek.Tuesday);
            AddDay(dr, DaysOfTheWeek.Wednesday);
            AddDay(dr, DaysOfTheWeek.Thursday);
            AddDay(dr, DaysOfTheWeek.Friday);
            AddDay(dr, DaysOfTheWeek.Saturday);
            AddDay(dr, DaysOfTheWeek.Sunday);

            var trigger = (WeeklyTrigger)currentTaskDefinition.Triggers.AddNew(TaskTriggerType.Weekly);
            trigger.DaysOfWeek    = triggerDays;
            trigger.WeeksInterval = 1;
            trigger.StartBoundary = DateTime.Now.Date.AddHours(h).AddMinutes(m);
        }

        foreach (DataRow dr in DS.Tables[dtScheduleMonth.TableName].Rows)
        {
            var   trigger = (MonthlyTrigger)currentTaskDefinition.Triggers.AddNew(TaskTriggerType.Monthly);
            short h       = Convert.ToInt16(dr[MSStartHour.ColumnName]);
            short m       = Convert.ToInt16(dr[MSStartMinute.ColumnName]);

            MonthsOfTheYear month;
            MonthsOfTheYear allmonth = 0;
            for (int i = 1; i <= 12; i++)
            {
                if ((byte)dr["m" + i] > 0)
                {
                    MonthsOfTheYear.TryParse((1 << (i - 1)).ToString(), true, out month);
                    allmonth |= month;
                }
            }
            var dayInt = new List <int>();
            for (int i = 1; i <= 31; i++)
            {
                if ((byte)dr["d" + i] > 0)
                {
                    dayInt.Add(i);
                    //monthInt |= i;
                }
            }
            trigger.DaysOfMonth = dayInt.ToArray();

            trigger.MonthsOfYear  = allmonth;
            trigger.StartBoundary = DateTime.Now.Date.AddHours(h).AddMinutes(m);
        }
    }
예제 #30
0
파일: Trigger.cs 프로젝트: clamwin/clamwind
 /// <summary>
 /// Creates a MonthlyDOWTrigger that fires every month.
 /// </summary>
 /// <param name="hour">Hour of day trigger will fire.</param>
 /// <param name="minutes">Minute of the hour trigger will fire.</param>
 /// <param name="daysOfTheWeek">Days of the week trigger will fire.</param>
 /// <param name="whichWeeks">Weeks of the month trigger will fire.</param>
 /// <param name="months">Months of the year trigger will fire.</param>
 public MonthlyDOWTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek, WhichWeek whichWeeks, MonthsOfTheYear months) : base()
 {
     SetStartTime((ushort)hour, (ushort)minutes);
     taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_MONTHLYDOW;
     taskTrigger.Data.monthlyDOW.WhichWeek     = (ushort)whichWeeks;
     taskTrigger.Data.monthlyDOW.DaysOfTheWeek = (ushort)daysOfTheWeek;
     taskTrigger.Data.monthlyDOW.Months        = (ushort)months;
 }
예제 #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Request.UrlReferrer == null || !Request.UrlReferrer.LocalPath.Contains("Schedule.aspx")) && Session["StartTaskTime"] != null)
        {
            Session.Remove("StartTaskTime");
        }

        if (Request["r"] == null)
        {
            Response.Redirect("GeneralReports.aspx");
        }

        _generalReport = GeneralReport.Find(Convert.ToUInt64(Request["r"]));

        taskService           = ScheduleHelper.GetService();
        reportsFolder         = ScheduleHelper.GetReportsFolder(taskService);
        currentTask           = ScheduleHelper.GetTaskOrCreate(taskService, reportsFolder, _generalReport.Id, _generalReport.Comment, "GR");
        currentTaskDefinition = currentTask.Definition;

        tempTask = ScheduleHelper.FindTaskNullable(reportsFolder, _generalReport.Id, "temp_");
        TaskState tempTaskState;
        string    tempTaskDescription = string.Empty;

        if (tempTask != null)
        {
            tempTaskState       = tempTask.State;
            tempTaskDescription = tempTask.Definition.RegistrationInfo.Description;
        }
        else
        {
            tempTaskState = TaskState.Unknown;
        }

        btnExecute.Enabled = currentTask.State != TaskState.Running && tempTaskState != TaskState.Running;
        btnExecute.Text    = (currentTask.State == TaskState.Running) ? StatusNotRunning : StatusRunning;

        var userName = HttpContext.Current.User.Identity.Name.Replace(@"ANALIT\", string.Empty);

        ErrorMassage.Text     = string.Empty;
        ErrorMassage.CssClass = "error";

        var description = tempTaskState == TaskState.Running ? string.Format("(запустил: {0})", tempTaskDescription) : string.Empty;

        if (tempTaskState == TaskState.Running || currentTask.State == TaskState.Running)
        {
            ExecAction action = null;
            var        currentReportNumber = "";
            ulong      runningNumber       = 0;
            if (tempTaskState == TaskState.Running)
            {
                if (tempTask != null)
                {
                    action = (ExecAction)tempTask.Definition.Actions.FirstOrDefault();
                }
            }
            else
            {
                action = (ExecAction)currentTask.Definition.Actions.FirstOrDefault();
            }
            if (action != null)
            {
                var arguments = (action).Arguments;
                if (!String.IsNullOrEmpty(arguments))
                {
                    if (arguments.IndexOf("/gr:") >= 0)
                    {
                        var substring    = arguments.Substring(arguments.IndexOf("/gr:") + 4);
                        var numberLength = substring.IndexOf(@" /");
                        var reportNumber = substring.Substring(0, numberLength != -1 ? numberLength : substring.Length);
                        if (!String.IsNullOrEmpty(reportNumber))
                        {
                            currentReportNumber += " № ";
                            currentReportNumber += reportNumber;
                            ulong.TryParse(reportNumber, out runningNumber);
                        }
                    }
                }
            }
            var startTime = GetStartTime(DbSession, runningNumber != 0 ? runningNumber : _generalReport.Id);

            var prefix = tempTaskState == TaskState.Running ? String.Format("Успешно запущен разовый отчет{0}", currentReportNumber)
                                : String.Format("Отчет запущен ({0})", currentReportNumber);
            if (tempTaskDescription == userName || currentTask.State == TaskState.Running)
            {
                ErrorMassage.Text      = string.Format("{0}, ожидайте окончания выполнения операции. {1}", prefix, startTime);
                ErrorMassage.BackColor = Color.LightGreen;
            }
            else
            {
                ErrorMassage.Text      = String.Format("{1}, выполнение данного отчета отложено {0}. {2}", description, prefix, startTime);
                ErrorMassage.BackColor = Color.Red;
            }
            btn_Mailing.Enabled = false;
            RadioSelf.Enabled   = false;
            RadioMails.Enabled  = false;
        }
        if (tempTaskState == TaskState.Queued || currentTask.State == TaskState.Queued)
        {
            var prefix = tempTaskState == TaskState.Running ? "Запускается разовый отчет" : "Отчет запускается";
            if (tempTaskDescription == userName || currentTask.State == TaskState.Queued)
            {
                ErrorMassage.Text      = string.Format("{0}, ожидайте окончания выполнения операции", prefix);
                ErrorMassage.BackColor = Color.LightGreen;
            }
            else
            {
                ErrorMassage.Text      = string.Format("{1} {0}, выполнение данного отчета отложено)", description, prefix);
                ErrorMassage.BackColor = Color.Red;
            }
            btn_Mailing.Enabled = false;
            RadioSelf.Enabled   = false;
            RadioMails.Enabled  = false;
        }
        if ((tempTaskState == TaskState.Ready && currentTask.State != TaskState.Running && currentTask.State != TaskState.Queued) ||
            (currentTask.State == TaskState.Ready && tempTaskState != TaskState.Running && tempTaskState != TaskState.Queued))
        {
            if (tempTaskDescription == userName || currentTask.State == TaskState.Ready)
            {
                // отчет выполнен
                if (Session["StartTaskTime"] != null)
                {
                    Session.Remove("StartTaskTime");
                    ErrorMassage.Text      = "Операция выполнена";
                    ErrorMassage.BackColor = Color.LightGreen;
                }
                else
                {
                    ErrorMassage.Text = "";
                }
            }
        }

        if ((tempTaskState == TaskState.Disabled && currentTask.State != TaskState.Running && currentTask.State != TaskState.Queued) ||
            (currentTask.State == TaskState.Disabled && tempTaskState != TaskState.Running && tempTaskState != TaskState.Queued))
        {
            if (Session["StartTaskTime"] != null)
            {
                Session.Remove("StartTaskTime");
                ErrorMassage.Text      = "Операция отменена";
                ErrorMassage.BackColor = Color.Red;
            }
            else
            {
                ErrorMassage.Text = "";
            }
        }

        var otherTriggers = new List <Trigger>();

        if (!IsPostBack)
        {
            var selfMail = GetSelfEmails();
            if ((selfMail.Count != 0) && (selfMail[0].Length != 0))
            {
                RadioSelf.Text = "Выполнить и отослать на: " + selfMail[0][0];
            }

            dtFrom.Value   = DateTime.Now.AddDays(-7).ToShortDateString();
            dtTo.Value     = DateTime.Now.ToShortDateString();
            mail_Text.Text = GetMailingAdresses();

            try {
                lblClient.Text        = _generalReport.Payer.Id + " - " + _generalReport.Payer.ShortName;
                lblReportComment.Text = _generalReport.Comment;
                var lastLogTimes = ObjectFromQuery(new[] { new MySqlParameter("?GeneralReportCode", _generalReport.Id) },
                                                   @"
SELECT
  Max(LogTime) as MaxLogTime
FROM
  logs.reportslogs
WHERE
  reportslogs.GeneralReportCode = ?GeneralReportCode
");
                if ((lastLogTimes.Count > 0) && (lastLogTimes[0].Length > 0))
                {
                    if (lastLogTimes[0][0] is DateTime)
                    {
                        MyCn.Open();
                        MyCmd.CommandText = @"
SELECT
  LogTime,
  EMail,
  SMTPID
FROM
  logs.reportslogs
WHERE
	reportslogs.GeneralReportCode = ?GeneralReportCode
and reportslogs.LogTime > ?LastLogTime
order by LogTime desc
";
                        MyCmd.Parameters.AddWithValue("?LastLogTime", ((DateTime)lastLogTimes[0][0]).AddDays(-1).Date);
                        var _logs = new DataTable();
                        MyDA.Fill(_logs);
                        gvLogs.DataSource = _logs;
                    }
                }
                gvLogs.DataBind();

                MyCmd.Parameters.Clear();
                MyCmd.CommandText = @"select
rel.StartTime,
if (not EndError, rel.EndTime, 'Ошибка при формировании отчета') as EndTime
from `logs`.reportexecutelogs rel
where rel.GeneralReportCode = ?GeneralReportCode
order by StartTime desc
limit 15;";
                MyCmd.Parameters.AddWithValue("?GeneralReportCode", _generalReport.Id);

                var startlogs = new DataTable();
                MyDA.Fill(startlogs);
                startLogs.DataSource = startlogs;

                startLogs.DataBind();
            }
            finally {
                MyCn.Close();
            }

            chbAllow.Checked = currentTask.Enabled;
            lblWork.Text     = ((ExecAction)currentTask.Definition.Actions[0]).Path + " " + ((ExecAction)currentTask.Definition.Actions[0]).Arguments;
            lblFolder.Text   = ((ExecAction)currentTask.Definition.Actions[0]).WorkingDirectory;
            if (_generalReport.FirmCode != null)
            {
                var ftpId = _generalReport.FirmCode.ToString().PadLeft(3, '0');
                FtpPath.Text = $"ftp://ftp.analit.net/OptBox/{ftpId}/Reports/";
            }
            else
            {
                FtpPath.Text = "";
            }
            var tl = currentTask.Definition.Triggers;

            for (int i = 0; i < tl.Count; i++)
            {
                if (tl[i] is WeeklyTrigger)
                {
                    var dr      = DS.Tables[dtSchedule.TableName].NewRow();
                    var trigger = ((WeeklyTrigger)tl[i]);
                    dr[SStartHour.ColumnName]   = trigger.StartBoundary.Hour;
                    dr[SStartMinute.ColumnName] = trigger.StartBoundary.Minute;
                    var days = trigger.DaysOfWeek;

                    SetWeekDays(dr, DaysOfTheWeek.Monday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Tuesday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Wednesday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Thursday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Friday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Saturday, days);
                    SetWeekDays(dr, DaysOfTheWeek.Sunday, days);

                    DS.Tables[dtSchedule.TableName].Rows.Add(dr);
                }
                else if (tl[i] is MonthlyTrigger)
                {
                    var dr = DS.Tables[dtScheduleMonth.TableName].NewRow();
                    //очищаем таблицу от значений по умолчанию
                    for (var k = 1; k <= 31; k++)
                    {
                        dr["d" + k] = 0;
                    }
                    for (var k = 1; k <= 12; k++)
                    {
                        dr["m" + k] = 0;
                    }

                    var trigger = ((MonthlyTrigger)tl[i]);
                    dr[MSStartHour.ColumnName]   = trigger.StartBoundary.Hour;
                    dr[MSStartMinute.ColumnName] = trigger.StartBoundary.Minute;
                    var             months = trigger.MonthsOfYear;
                    MonthsOfTheYear month;
                    for (int j = 0; j < 12; j++)
                    {
                        MonthsOfTheYear.TryParse((1 << j).ToString(), true, out month);
                        if (months.HasFlag(month))
                        {
                            dr["m" + (j + 1)] = 1;
                        }
                    }
                    foreach (int em in trigger.DaysOfMonth)
                    {
                        dr["d" + em] = 1;
                    }
                    DS.Tables[dtScheduleMonth.TableName].Rows.Add(dr);
                }
                else
                {
                    otherTriggers.Add(tl[i]);
                }
            }

            DS.Tables[dtSchedule.TableName].AcceptChanges();
            dgvSchedule.DataSource = DS;
            dgvSchedule.DataMember = dtSchedule.TableName;
            dgvSchedule.DataBind();

            dgvScheduleMonth.DataSource = DS;
            dgvScheduleMonth.DataMember = dtScheduleMonth.TableName;
            dgvScheduleMonth.DataBind();

            gvOtherTriggers.DataSource = otherTriggers;
            gvOtherTriggers.DataBind();

            Session[DSSchedule] = DS;

            CloseTaskService();
        }
        else
        {
            DS = ((DataSet)Session[DSSchedule]);
            if (DS == null)             // вероятно, сессия завершилась и все ее данные утеряны
            {
                Reports_GeneralReports.Redirect(this);
            }
        }

        send_created_report.Visible = _generalReport.IsSuccessfulyProcessed;
    }
 /// <summary>
 /// Updates a monthly trigger to specify the months of the year in which it will run.
 /// </summary>
 /// <param name="moy">The month of the year.</param>
 /// <returns>
 ///   <see cref="TriggerBuilder" /> instance.
 /// </returns>
 public TriggerBuilder Of(MonthsOfTheYear moy)
 {
     ((MonthlyDOWTrigger)trb.trigger).MonthsOfYear = moy;
     return(trb);
 }
예제 #33
0
        public MonthsOfTheYear ActuallyMonth()
        {
            MonthsOfTheYear monthsOfTheYear = MonthsOfTheYear.NotSet + months.Month;

            return(monthsOfTheYear);
        }
예제 #34
0
 public MonthlyTrigger(int dayOfMonth = 1, MonthsOfTheYear monthsOfYear = (MonthsOfTheYear)0xfff)
     : base(TaskTriggerType.Monthly)
 {
     DaysOfMonth = new int[] { dayOfMonth };
     MonthsOfYear = monthsOfYear;
 }
예제 #35
0
        static Trigger GetTriggerFromConsole()
        {
            // Trigger hours
            Console.WriteLine("Type trigger hours:");
            int.TryParse(Console.ReadLine(), out int hours);
            hours = hours > 23 ? 23 : (hours < 0 ? 0 : hours);

            // Trigger minutes
            Console.WriteLine("Type trigger minutes:");
            int.TryParse(Console.ReadLine(), out int minutes);
            minutes = minutes > 59 ? 59 : (minutes < 0 ? 0 : minutes);

            // Trigger type
            while (true)
            {
                Console.WriteLine("Trigger type:\nd - daily, w - weekly, m - monthly");
                string input = Console.ReadLine().ToLower();

                if (input == "d") // Daily
                {
                    // Interval
                    Console.WriteLine("Interval between days in days:");
                    short.TryParse(Console.ReadLine(), out short interval);
                    interval = interval < 0 ? (short)0 : interval;

                    // Return trigger
                    return(new DailyTrigger
                    {
                        DaysInterval = interval,
                        StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hours, minutes, 0)
                    });
                }
                else if (input == "w") // Weekly
                {
                    // Interval
                    Console.WriteLine("Interval between weeks in weeks:");
                    short.TryParse(Console.ReadLine(), out short interval);
                    interval = interval < 0 ? (short)0 : interval;

                    // Day of week
                    Console.WriteLine("Which day in week?\n0 - all days, 1 - Monday, 2 - Tuesday, ..., 7 - Sunday:");
                    int.TryParse(Console.ReadLine(), out int weekDay);
                    weekDay = weekDay > 7 ? 7 : (weekDay < 0 ? 0 : weekDay);

                    DaysOfTheWeek[] daysOfTheWeek = new DaysOfTheWeek[]
                    {
                        DaysOfTheWeek.AllDays, DaysOfTheWeek.Monday, DaysOfTheWeek.Tuesday,
                        DaysOfTheWeek.Wednesday, DaysOfTheWeek.Thursday, DaysOfTheWeek.Friday,
                        DaysOfTheWeek.Saturday, DaysOfTheWeek.Sunday
                    };

                    // Return trigger
                    return(new WeeklyTrigger
                    {
                        WeeksInterval = interval,
                        DaysOfWeek = daysOfTheWeek[weekDay],
                        StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hours, minutes, 0)
                    });
                }
                else if (input == "m") // Monthly
                {
                    // Month of year
                    Console.WriteLine("Which month in year?\n0 - All months, 1 - January, 2 - February, ..., 12 - December:");
                    int.TryParse(Console.ReadLine(), out int yearMonth);
                    yearMonth = yearMonth > 12 ? 12 : (yearMonth < 0 ? 0 : yearMonth);

                    MonthsOfTheYear[] monthsOfTheYear = new MonthsOfTheYear[]
                    {
                        MonthsOfTheYear.AllMonths,
                        MonthsOfTheYear.January, MonthsOfTheYear.February, MonthsOfTheYear.March, MonthsOfTheYear.April,
                        MonthsOfTheYear.May, MonthsOfTheYear.June, MonthsOfTheYear.July, MonthsOfTheYear.August,
                        MonthsOfTheYear.September, MonthsOfTheYear.October, MonthsOfTheYear.November, MonthsOfTheYear.December
                    };

                    Console.WriteLine("Which days in month?\n type numbers between 1 - 31\ntype 'last' to include last day of month\ntype 'end' to stop typing:");
                    List <int> daysOfMonth = new List <int>();
                    bool       lastDay     = false;
                    while (true)
                    {
                        string console = Console.ReadLine().ToLower();
                        int.TryParse(console, out int monthDay);
                        if (monthDay >= 1 && monthDay <= 31)
                        {
                            daysOfMonth.Add(monthDay);
                        }
                        if (console == "last")
                        {
                            lastDay = true;
                        }
                        if (console == "end")
                        {
                            break;
                        }
                    }

                    // Return trigger
                    return(new MonthlyTrigger
                    {
                        DaysOfMonth = daysOfMonth.ToArray(),
                        MonthsOfYear = monthsOfTheYear[yearMonth],
                        RunOnLastDayOfMonth = lastDay,
                        StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hours, minutes, 0)
                    });
                }
            }
        }