-
Notifications
You must be signed in to change notification settings - Fork 233
/
RecurrencePatternEvaluator.cs
927 lines (830 loc) · 36.6 KB
/
RecurrencePatternEvaluator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
using Ical.Net.DataTypes;
using Ical.Net.Utility;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Ical.Net.Evaluation
{
/// <summary>
/// Much of this code comes from iCal4j, as Ben Fortuna has done an
/// excellent job with the recurrence pattern evaluation there.
///
/// Here's the iCal4j license:
/// ==================
/// iCal4j - License
/// ==================
///
/// Copyright (c) 2009, Ben Fortuna
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions
/// are met:
///
/// o Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
///
/// o Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
///
/// o Neither the name of Ben Fortuna nor the names of any other contributors
/// may be used to endorse or promote products derived from this software
/// without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
/// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
/// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
/// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
/// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
/// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
/// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
/// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/// </summary>
public class RecurrencePatternEvaluator : Evaluator
{
// FIXME: in ical4j this is configurable.
private const int _maxIncrementCount = 1000;
protected RecurrencePattern Pattern { get; set; }
public RecurrencePatternEvaluator(RecurrencePattern pattern)
{
Pattern = pattern;
}
private RecurrencePattern ProcessRecurrencePattern(IDateTime referenceDate)
{
var r = new RecurrencePattern();
r.CopyFrom(Pattern);
// Convert the UNTIL value to one that matches the same time information as the reference date
if (r.Until != DateTime.MinValue)
{
r.Until = DateUtil.MatchTimeZone(referenceDate, new CalDateTime(r.Until, referenceDate.TzId)).Value;
}
if (r.Frequency > FrequencyType.Secondly && r.BySecond.Count == 0 && referenceDate.HasTime
/* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
{
r.BySecond.Add(referenceDate.Second);
}
if (r.Frequency > FrequencyType.Minutely && r.ByMinute.Count == 0 && referenceDate.HasTime
/* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
{
r.ByMinute.Add(referenceDate.Minute);
}
if (r.Frequency > FrequencyType.Hourly && r.ByHour.Count == 0 && referenceDate.HasTime
/* NOTE: Fixes a bug where all-day events have BySecond/ByMinute/ByHour added incorrectly */)
{
r.ByHour.Add(referenceDate.Hour);
}
// If BYDAY, BYYEARDAY, or BYWEEKNO is specified, then
// we don't default BYDAY, BYMONTH or BYMONTHDAY
if (r.ByDay.Count == 0)
{
// If the frequency is weekly, use the original date's day of week.
// NOTE: fixes WeeklyCount1() and WeeklyUntil1() handling
// If BYWEEKNO is specified and BYMONTHDAY/BYYEARDAY is not specified,
// then let's add BYDAY to BYWEEKNO.
// NOTE: fixes YearlyByWeekNoX() handling
if (r.Frequency == FrequencyType.Weekly || (r.ByWeekNo.Count > 0 && r.ByMonthDay.Count == 0 && r.ByYearDay.Count == 0))
{
r.ByDay.Add(new WeekDay(referenceDate.DayOfWeek));
}
// If BYMONTHDAY is not specified,
// default to the current day of month.
// NOTE: fixes YearlyByMonth1() handling, added BYYEARDAY exclusion
// to fix YearlyCountByYearDay1() handling
if (r.Frequency > FrequencyType.Weekly && r.ByWeekNo.Count == 0 && r.ByYearDay.Count == 0 && r.ByMonthDay.Count == 0)
{
r.ByMonthDay.Add(referenceDate.Day);
}
// If BYMONTH is not specified, default to
// the current month.
// NOTE: fixes YearlyCountByYearDay1() handling
if (r.Frequency > FrequencyType.Monthly && r.ByWeekNo.Count == 0 && r.ByYearDay.Count == 0 && r.ByMonth.Count == 0)
{
r.ByMonth.Add(referenceDate.Month);
}
}
return r;
}
private void EnforceEvaluationRestrictions(RecurrencePattern pattern)
{
RecurrenceEvaluationModeType? evaluationMode = pattern.EvaluationMode;
RecurrenceRestrictionType? evaluationRestriction = pattern.RestrictionType;
if (evaluationRestriction != RecurrenceRestrictionType.NoRestriction)
{
switch (evaluationMode)
{
case RecurrenceEvaluationModeType.AdjustAutomatically:
switch (pattern.Frequency)
{
case FrequencyType.Secondly:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.Default:
case RecurrenceRestrictionType.RestrictSecondly:
pattern.Frequency = FrequencyType.Minutely;
break;
case RecurrenceRestrictionType.RestrictMinutely:
pattern.Frequency = FrequencyType.Hourly;
break;
case RecurrenceRestrictionType.RestrictHourly:
pattern.Frequency = FrequencyType.Daily;
break;
}
}
break;
case FrequencyType.Minutely:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.RestrictMinutely:
pattern.Frequency = FrequencyType.Hourly;
break;
case RecurrenceRestrictionType.RestrictHourly:
pattern.Frequency = FrequencyType.Daily;
break;
}
}
break;
case FrequencyType.Hourly:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.RestrictHourly:
pattern.Frequency = FrequencyType.Daily;
break;
}
}
break;
}
break;
case RecurrenceEvaluationModeType.ThrowException:
case RecurrenceEvaluationModeType.Default:
switch (pattern.Frequency)
{
case FrequencyType.Secondly:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.Default:
case RecurrenceRestrictionType.RestrictSecondly:
case RecurrenceRestrictionType.RestrictMinutely:
case RecurrenceRestrictionType.RestrictHourly:
throw new ArgumentException();
}
}
break;
case FrequencyType.Minutely:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.RestrictMinutely:
case RecurrenceRestrictionType.RestrictHourly:
throw new ArgumentException();
}
}
break;
case FrequencyType.Hourly:
{
switch (evaluationRestriction)
{
case RecurrenceRestrictionType.RestrictHourly:
throw new ArgumentException();
}
}
break;
}
break;
}
}
}
/**
* Returns a list of start dates in the specified period represented by this recur. This method includes a base date
* argument, which indicates the start of the fist occurrence of this recurrence. The base date is used to inject
* default values to return a set of dates in the correct format. For example, if the search start date (start) is
* Wed, Mar 23, 12:19PM, but the recurrence is Mon - Fri, 9:00AM - 5:00PM, the start dates returned should all be at
* 9:00AM, and not 12:19PM.
*/
private HashSet<DateTime> GetDates(IDateTime seed, DateTime periodStart, DateTime periodEnd, int maxCount, RecurrencePattern pattern,
bool includeReferenceDateInResults)
{
var dates = new HashSet<DateTime>();
var originalDate = DateUtil.GetSimpleDateTimeData(seed);
var seedCopy = DateUtil.GetSimpleDateTimeData(seed);
// optimize the start time for selecting candidates
// (only applicable where a COUNT is not specified)
if (pattern.Count == int.MinValue)
{
var incremented = seedCopy;
while (incremented < periodStart)
{
seedCopy = incremented;
IncrementDate(ref incremented, pattern, pattern.Interval);
}
}
var expandBehavior = RecurrenceUtil.GetExpandBehaviorList(pattern);
var noCandidateIncrementCount = 0;
var candidate = DateTime.MinValue;
while (maxCount < 0 || dates.Count < maxCount)
{
if (pattern.Until != DateTime.MinValue && candidate != DateTime.MinValue && candidate > pattern.Until)
{
break;
}
if (candidate != DateTime.MinValue && candidate > periodEnd)
{
break;
}
if (pattern.Count >= 1 && dates.Count >= pattern.Count)
{
break;
}
//No need to continue if the seed is after the periodEnd
if (seedCopy > periodEnd)
{
break;
}
var candidates = GetCandidates(seedCopy, pattern, expandBehavior);
if (candidates.Count > 0)
{
noCandidateIncrementCount = 0;
foreach (var t in candidates.OrderBy(c => c).Where(t => t >= originalDate))
{
candidate = t;
// candidates MAY occur before periodStart
// For example, FREQ=YEARLY;BYWEEKNO=1 could return dates
// from the previous year.
//
// exclude candidates that start at the same moment as periodEnd if the period is a range but keep them if targeting a specific moment
if (pattern.Count >= 1 && dates.Count >= pattern.Count)
{
break;
}
if ((candidate >= periodEnd && periodStart != periodEnd) || candidate > periodEnd && periodStart == periodEnd)
{
continue;
}
if (pattern.Until == DateTime.MinValue || candidate <= pattern.Until)
{
dates.Add(candidate);
}
}
}
else
{
noCandidateIncrementCount++;
if (_maxIncrementCount > 0 && noCandidateIncrementCount > _maxIncrementCount)
{
break;
}
}
IncrementDate(ref seedCopy, pattern, pattern.Interval);
}
return dates;
}
/**
* Returns a list of possible dates generated from the applicable BY* rules, using the specified date as a seed.
* @param date the seed date
* @param value the type of date list to return
* @return a DateList
*/
private List<DateTime> GetCandidates(DateTime date, RecurrencePattern pattern, bool?[] expandBehaviors)
{
var dates = new List<DateTime> { date };
dates = GetMonthVariants(dates, pattern, expandBehaviors[0]);
dates = GetWeekNoVariants(dates, pattern, expandBehaviors[1]);
dates = GetYearDayVariants(dates, pattern, expandBehaviors[2]);
dates = GetMonthDayVariants(dates, pattern, expandBehaviors[3]);
dates = GetDayVariants(dates, pattern, expandBehaviors[4]);
dates = GetHourVariants(dates, pattern, expandBehaviors[5]);
dates = GetMinuteVariants(dates, pattern, expandBehaviors[6]);
dates = GetSecondVariants(dates, pattern, expandBehaviors[7]);
dates = ApplySetPosRules(dates, pattern);
return dates;
}
/**
* Applies BYSETPOS rules to <code>dates</code>. Valid positions are from 1 to the size of the date list. Invalid
* positions are ignored.
* @param dates
*/
private List<DateTime> ApplySetPosRules(List<DateTime> dates, RecurrencePattern pattern)
{
// return if no SETPOS rules specified..
if (pattern.BySetPosition.Count == 0)
{
return dates;
}
// sort the list before processing..
dates.Sort();
var size = dates.Count;
var setPosDates = pattern.BySetPosition
.Where(p => p > 0 && p <= size || p < 0 && p >= -size) //Protect against out of range access
.Select(p => p > 0 && p <= size
? dates[p - 1]
: dates[size + p])
.ToList();
return setPosDates;
}
/**
* Applies BYMONTH rules specified in this Recur instance to the specified date list. If no BYMONTH rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetMonthVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByMonth.Count == 0)
{
return dates;
}
if (expand.Value)
{
// Expand behavior
return dates
.SelectMany(d => pattern.ByMonth.Select(month => d.AddMonths(month - d.Month)))
.ToList();
}
// Limit behavior
var dateSet = new HashSet<DateTime>(dates);
dateSet.ExceptWith(dates.Where(date => pattern.ByMonth.All(t => t != date.Month)));
return dateSet.ToList();
}
/**
* Applies BYWEEKNO rules specified in this Recur instance to the specified date list. If no BYWEEKNO rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetWeekNoVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByWeekNo.Count == 0)
{
return dates;
}
if (!expand.Value)
{
return new List<DateTime>();
}
// Expand behavior
var weekNoDates = new List<DateTime>();
foreach (var t in dates)
{
foreach (var weekNo in pattern.ByWeekNo)
{
var date = t;
// Determine our current week number
var currWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
while (currWeekNo > weekNo)
{
// If currWeekNo > weekNo, then we're likely at the start of a year
// where currWeekNo could be 52 or 53. If we simply step ahead 7 days
// we should be back to week 1, where we can easily make the calculation
// to move to weekNo.
date = date.AddDays(7);
currWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
}
// Move ahead to the correct week of the year
date = date.AddDays((weekNo - currWeekNo) * 7);
// Step backward single days until we're at the correct DayOfWeek
while (date.DayOfWeek != pattern.FirstDayOfWeek)
{
date = date.AddDays(-1);
}
for (var k = 0; k < 7; k++)
{
weekNoDates.Add(date);
date = date.AddDays(1);
}
}
}
return weekNoDates;
}
/**
* Applies BYYEARDAY rules specified in this Recur instance to the specified date list. If no BYYEARDAY rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetYearDayVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByYearDay.Count == 0)
{
return dates;
}
if (expand.Value)
{
var yearDayDates = new List<DateTime>(dates.Count);
foreach (var date in dates)
{
var date1 = date;
yearDayDates.AddRange(pattern.ByYearDay.Select(yearDay => yearDay > 0
? date1.AddDays(-date1.DayOfYear + yearDay)
: date1.AddDays(-date1.DayOfYear + 1).AddYears(1).AddDays(yearDay)));
}
return yearDayDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.ByYearDay.Count; j++)
{
var yearDay = pattern.ByYearDay[j];
var newDate = yearDay > 0
? date.AddDays(-date.DayOfYear + yearDay)
: date.AddDays(-date.DayOfYear + 1).AddYears(1).AddDays(yearDay);
if (newDate.DayOfYear == date.DayOfYear)
{
goto Next;
}
}
dates.RemoveAt(i);
Next:
;
}
return dates;
}
/**
* Applies BYMONTHDAY rules specified in this Recur instance to the specified date list. If no BYMONTHDAY rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetMonthDayVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByMonthDay.Count == 0)
{
return dates;
}
if (expand.Value)
{
var monthDayDates = new List<DateTime>();
foreach (var date in dates)
{
monthDayDates.AddRange(
from monthDay in pattern.ByMonthDay
let daysInMonth = Calendar.GetDaysInMonth(date.Year, date.Month)
where Math.Abs(monthDay) <= daysInMonth
select monthDay > 0
? date.AddDays(-date.Day + monthDay)
: date.AddDays(-date.Day + 1).AddMonths(1).AddDays(monthDay)
);
}
return monthDayDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.ByMonthDay.Count; j++)
{
var monthDay = pattern.ByMonthDay[j];
var daysInMonth = Calendar.GetDaysInMonth(date.Year, date.Month);
if (Math.Abs(monthDay) > daysInMonth)
{
throw new ArgumentException("Invalid day of month: " + date + " (day " + monthDay + ")");
}
// Account for positive or negative numbers
var newDate = monthDay > 0
? date.AddDays(-date.Day + monthDay)
: date.AddDays(-date.Day + 1).AddMonths(1).AddDays(monthDay);
if (newDate.Day.Equals(date.Day))
{
goto Next;
}
}
Next:
dates.RemoveAt(i);
}
return dates;
}
/**
* Applies BYDAY rules specified in this Recur instance to the specified date list. If no BYDAY rules are specified
* the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetDayVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByDay.Count == 0)
{
return dates;
}
if (expand.Value)
{
// Expand behavior
var weekDayDates = new List<DateTime>();
foreach (var date in dates)
{
foreach (var day in pattern.ByDay)
{
weekDayDates.AddRange(GetAbsWeekDays(date, day, pattern));
}
}
return weekDayDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.ByDay.Count; j++)
{
var weekDay = pattern.ByDay[j];
if (weekDay.DayOfWeek.Equals(date.DayOfWeek))
{
// If no offset is specified, simply test the day of week!
// FIXME: test with offset...
if (date.DayOfWeek.Equals(weekDay.DayOfWeek))
{
goto Next;
}
}
}
dates.RemoveAt(i);
Next:
;
}
return dates;
}
/**
* Returns a list of applicable dates corresponding to the specified week day in accordance with the frequency
* specified by this recurrence rule.
* @param date
* @param weekDay
* @return
*/
private List<DateTime> GetAbsWeekDays(DateTime date, WeekDay weekDay, RecurrencePattern pattern)
{
var days = new List<DateTime>();
var dayOfWeek = weekDay.DayOfWeek;
if (pattern.Frequency == FrequencyType.Daily)
{
if (date.DayOfWeek == dayOfWeek)
{
days.Add(date);
}
}
else if (pattern.Frequency == FrequencyType.Weekly || pattern.ByWeekNo.Count > 0)
{
var weekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
// construct a list of possible week days..
while (date.DayOfWeek != dayOfWeek)
{
date = date.AddDays(1);
}
var nextWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
var currentWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
//When we manage weekly recurring pattern and we have boundary case:
//Weekdays: Dec 31, Jan 1, Feb 1, Mar 1, Apr 1, May 1, June 1, Dec 31 - It's the 53th week of the year, but all another are 1st week number.
//So we need an EXRULE for this situation, but only for weekly events
while (currentWeekNo == weekNo || (nextWeekNo < weekNo && currentWeekNo == nextWeekNo && pattern.Frequency == FrequencyType.Weekly))
{
if ((pattern.ByWeekNo.Count == 0 || pattern.ByWeekNo.Contains(currentWeekNo))
&& (pattern.ByMonth.Count == 0 || pattern.ByMonth.Contains(date.Month)))
{
days.Add(date);
}
date = date.AddDays(7);
currentWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
}
}
else if (pattern.Frequency == FrequencyType.Monthly || pattern.ByMonth.Count > 0)
{
var month = date.Month;
// construct a list of possible month days..
date = date.AddDays(-date.Day + 1);
while (date.DayOfWeek != dayOfWeek)
{
date = date.AddDays(1);
}
while (date.Month == month)
{
var currentWeekNo = Calendar.GetIso8601WeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, pattern.FirstDayOfWeek);
if ((pattern.ByWeekNo.Count == 0 || pattern.ByWeekNo.Contains(currentWeekNo))
&& (pattern.ByMonth.Count == 0 || pattern.ByMonth.Contains(date.Month)))
{
days.Add(date);
}
date = date.AddDays(7);
}
}
else if (pattern.Frequency == FrequencyType.Yearly)
{
var year = date.Year;
// construct a list of possible year days..
date = date.AddDays(-date.DayOfYear + 1);
while (date.DayOfWeek != dayOfWeek)
{
date = date.AddDays(1);
}
while (date.Year == year)
{
days.Add(date);
date = date.AddDays(7);
}
}
return GetOffsetDates(days, weekDay.Offset);
}
/**
* Returns a single-element sublist containing the element of <code>list</code> at <code>offset</code>. Valid
* offsets are from 1 to the size of the list. If an invalid offset is supplied, all elements from <code>list</code>
* are added to <code>sublist</code>.
* @param list
* @param offset
* @param sublist
*/
private List<DateTime> GetOffsetDates(List<DateTime> dates, int offset)
{
if (offset == int.MinValue)
{
return dates;
}
var offsetDates = new List<DateTime>();
var size = dates.Count;
if (offset < 0 && offset >= -size)
{
offsetDates.Add(dates[size + offset]);
}
else if (offset > 0 && offset <= size)
{
offsetDates.Add(dates[offset - 1]);
}
return offsetDates;
}
/**
* Applies BYHOUR rules specified in this Recur instance to the specified date list. If no BYHOUR rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetHourVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByHour.Count == 0)
{
return dates;
}
if (expand.Value)
{
// Expand behavior
var hourlyDates = new List<DateTime>();
for (var i = 0; i < dates.Count; i++)
{
var date = dates[i];
for (var j = 0; j < pattern.ByHour.Count; j++)
{
var hour = pattern.ByHour[j];
date = date.AddHours(-date.Hour + hour);
hourlyDates.Add(date);
}
}
return hourlyDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.ByHour.Count; j++)
{
var hour = pattern.ByHour[j];
if (date.Hour == hour)
{
goto Next;
}
}
// Remove unmatched dates
dates.RemoveAt(i);
Next:
;
}
return dates;
}
/**
* Applies BYMINUTE rules specified in this Recur instance to the specified date list. If no BYMINUTE rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetMinuteVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.ByMinute.Count == 0)
{
return dates;
}
if (expand.Value)
{
// Expand behavior
var minutelyDates = new List<DateTime>();
for (var i = 0; i < dates.Count; i++)
{
var date = dates[i];
for (var j = 0; j < pattern.ByMinute.Count; j++)
{
var minute = pattern.ByMinute[j];
date = date.AddMinutes(-date.Minute + minute);
minutelyDates.Add(date);
}
}
return minutelyDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.ByMinute.Count; j++)
{
var minute = pattern.ByMinute[j];
if (date.Minute == minute)
{
goto Next;
}
}
// Remove unmatched dates
dates.RemoveAt(i);
Next:
;
}
return dates;
}
/**
* Applies BYSECOND rules specified in this Recur instance to the specified date list. If no BYSECOND rules are
* specified the date list is returned unmodified.
* @param dates
* @return
*/
private List<DateTime> GetSecondVariants(List<DateTime> dates, RecurrencePattern pattern, bool? expand)
{
if (expand == null || pattern.BySecond.Count == 0)
{
return dates;
}
if (expand.Value)
{
// Expand behavior
var secondlyDates = new List<DateTime>();
for (var i = 0; i < dates.Count; i++)
{
var date = dates[i];
for (var j = 0; j < pattern.BySecond.Count; j++)
{
var second = pattern.BySecond[j];
date = date.AddSeconds(-date.Second + second);
secondlyDates.Add(date);
}
}
return secondlyDates;
}
// Limit behavior
for (var i = dates.Count - 1; i >= 0; i--)
{
var date = dates[i];
for (var j = 0; j < pattern.BySecond.Count; j++)
{
var second = pattern.BySecond[j];
if (date.Second == second)
{
goto Next;
}
}
// Remove unmatched dates
dates.RemoveAt(i);
Next:
;
}
return dates;
}
private Period CreatePeriod(DateTime dt, IDateTime referenceDate)
{
// Turn each resulting date/time into an IDateTime and associate it
// with the reference date.
IDateTime newDt = new CalDateTime(dt, referenceDate.TzId);
// NOTE: fixes bug #2938007 - hasTime missing
newDt.HasTime = referenceDate.HasTime;
newDt.AssociateWith(referenceDate);
// Create a period from the new date/time.
return new Period(newDt);
}
public override HashSet<Period> Evaluate(IDateTime referenceDate, DateTime periodStart, DateTime periodEnd, bool includeReferenceDateInResults)
{
if ((this.Pattern.Frequency != FrequencyType.None) && (this.Pattern.Frequency < FrequencyType.Daily) && !referenceDate.HasTime)
{
// This case is not defined by RFC 5545. We handle it by evaluating the rule
// as if referenceDate had a time (i.e. set to midnight).
referenceDate = referenceDate.Copy<IDateTime>();
referenceDate.HasTime = true;
}
// Create a recurrence pattern suitable for use during evaluation.
var pattern = ProcessRecurrencePattern(referenceDate);
// Enforce evaluation restrictions on the pattern.
EnforceEvaluationRestrictions(pattern);
Periods.Clear();
var periodQuery = GetDates(referenceDate, periodStart, periodEnd, -1, pattern, includeReferenceDateInResults)
.Select(dt => CreatePeriod(dt, referenceDate));
Periods.UnionWith(periodQuery);
return Periods;
}
}
}