private static void InitCustomers()
        {
            DateTimeOffset dto = new DateTimeOffset(2015, 1, 1, 1, 2, 3, 4, TimeSpan.Zero);
            _customers = Enumerable.Range(1, 5).Select(e =>
                new DCustomer
                {
                    Id = e,
                    DateTime = dto.AddYears(e).DateTime,
                    Offset = e % 2 == 0 ? dto.AddMonths(e) : dto.AddDays(e).AddMilliseconds(10),
                    Date = e % 2 == 0 ? dto.AddDays(e).Date : dto.AddDays(-e).Date,
                    TimeOfDay = e % 3 == 0 ? dto.AddHours(e).TimeOfDay : dto.AddHours(-e).AddMilliseconds(10).TimeOfDay,

                    NullableDateTime = e % 2 == 0 ? (DateTime?)null : dto.AddYears(e).DateTime,
                    NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dto.AddMonths(e),
                    NullableDate = e % 2 == 0 ? (Date?)null : dto.AddDays(e).Date,
                    NullableTimeOfDay = e % 3 == 0 ? (TimeOfDay?)null : dto.AddHours(e).TimeOfDay,

                    DateTimes = new [] { dto.AddYears(e).DateTime, dto.AddMonths(e).DateTime },
                    Offsets = new [] { dto.AddMonths(e), dto.AddDays(e) },
                    Dates = new [] { (Date)dto.AddYears(e).Date, (Date)dto.AddMonths(e).Date },
                    TimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                    NullableDateTimes = new [] { dto.AddYears(e).DateTime, (DateTime?)null, dto.AddMonths(e).DateTime },
                    NullableOffsets = new [] { dto.AddMonths(e), (DateTimeOffset?)null, dto.AddDays(e) },
                    NullableDates = new [] { (Date)dto.AddYears(e).Date, (Date?)null, (Date)dto.AddMonths(e).Date },
                    NullableTimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay?)null, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                }).ToList();
        }
        public void Between()
        {
            var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero);

            Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3)));
            Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3)));
            Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3)));
            Assert.IsFalse(date.AddHours(-2).Between(date, date.AddMonths(3)));

            Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3), false));
            Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3), false));
            Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3), false));
            Assert.IsTrue(date.AddHours(-2).Between(date, date.AddMonths(3), false));
            Assert.IsFalse(date.AddHours(-24).Between(date, date.AddMonths(3), false));
        }
Example #3
0
		internal long GetNextOccurrence()
		{
			DateTimeOffset now = _ClockSource.Now;
			DateTimeOffset next;

			switch (this.Periodicity)
			{
				case PeriodicityType.Hourly:
					next = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, this.MinuteOffset, 0, now.Offset);

					if (next <= now)
					{
						next = next.AddHours(1.0);
					}

					break;

				case PeriodicityType.Daily:
					next = new DateTimeOffset(now.Year, now.Month, now.Day, this.HourOffset, this.MinuteOffset, 0, now.Offset);

					if (next <= now)
					{
						next = next.AddDays(1.0);
					}

					break;

				default:
					goto case PeriodicityType.Hourly;
			}

			return next.ToUniversalTime().Ticks;
		}
        /// <summary>
        /// Returns a value indicating whether the provided DaysOfWeek value is applicable today.
        /// </summary>
        public static bool IsToday(DaysOfWeek days, DateTimeOffset currentTime)
        {
            // special handling for Night Owl so that its schedule is visible after midnight
            // i.e., if it's 2AM on Sunday, we still consider "today" to be Saturday.
            var time = (days == DaysOfWeek.NightOwl)
                ? currentTime.AddHours(-4)
                : currentTime;

            return (ToDaysOfWeek(time.DayOfWeek) & days) != DaysOfWeek.None;
        }
Example #5
0
        public void CanAddHoursAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dto = new DateTimeOffset(2015, 3, 8, 1, 0, 0, TimeSpan.FromHours(-8));
            var result = dto.AddHours(1, tz);

            var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7));
            Assert.Equal(expected, result);
            Assert.Equal(expected.Offset, result.Offset);
        }
Example #6
0
 public void Dividing()
 {
     var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
     var availableTime = new TimeRange(now, now.AddHours(1));
     var freeSlots = availableTime
         .Divide(TimeSpan.FromMinutes(15))
         .ToArray();
     Assert.AreEqual(4, freeSlots.Length);
     Assert.IsTrue(freeSlots.All(s => s.Duration == TimeSpan.FromMinutes(15)));
 }
Example #7
0
        static void Main(string[] args)
        {
            //var offset = DateTimeOffset.Now;
            //Debug.WriteLine(offset);

            //Debug.WriteLine(DateTimeOffset.UtcNow);

            //String s = "10/1/2014 6:17 PM";
            //DateTime dt = DateTime.ParseExact(s, "MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
            //DateTimeOffset dto = new DateTimeOffset(dt);
            DateTimeOffset dto1 = new DateTimeOffset();

            dto1 = DateTimeOffset.Now;
            dto1 = dto1.AddHours(2);
            dto1 = dto1.AddMinutes(30);

            Debug.WriteLine(DateTimeOffset.Now);
            Debug.WriteLine(dto1);

            TimeSpan diff = dto1.Subtract(DateTimeOffset.Now);
            Debug.WriteLine(diff);
            Debug.WriteLine(diff.TotalHours);
            Debug.WriteLine(diff.TotalSeconds);
            var diffsec = (DateTimeOffset.Now - dto1).TotalSeconds;
            Debug.WriteLine(diffsec);

            //dtoff.Value.ToLocalTime().ToString("dddd, MMM dd yyyy HH:mm", new CultureInfo("en-US"));

            //Debug.WriteLine(dto1);
            //Debug.WriteLine(dto2);
            //Debug.WriteLine(DateTimeOffset.Now);
            //Debug.WriteLine(dto1 - DateTimeOffset.Now);
            //Debug.WriteLine(DateTimeOffset.Now - dto1);
            //Debug.WriteLine(dto1.CompareTo(DateTimeOffset.Now));
            //Debug.WriteLine(DateTimeOffset.Now.CompareTo(dto1));
            //Debug.WriteLine("  ");

            //Debug.WriteLine(dto1.Hour);

            double temp = -26;
            double res = 0;
            for (int i = 0; i < 40; i++)
            {
                temp++;
                res = 0.5 - (temp * 0.1);
                Debug.WriteLine("Temp: " + temp + "  Result: " + res);
            }

            //Debug.WriteLine(s);
            //Debug.WriteLine(dt.ToString());
            //Debug.WriteLine(dt.ToUniversalTime().ToString());
            //Debug.WriteLine(dto.ToString());
        }
Example #8
0
 public void Time()
 {
     var date = new DateTimeOffset(year: 2016, month: 4, day: 1, hour: 1, minute: 0, second: 0, offset: TimeSpan.Zero);
     EqualityUnit
         .Create(new DateTimeKey(date, DateTimeKeyFlags.Time))
         .WithEqualValues(
             new DateTimeKey(date, DateTimeKeyFlags.Time),
             new DateTimeKey(date.AddDays(1), DateTimeKeyFlags.Time))
         .WithNotEqualValues(
             new DateTimeKey(date, DateTimeKeyFlags.Date),
             new DateTimeKey(date.AddHours(1), DateTimeKeyFlags.Time))
         .RunAll(
             (x, y) => x == y,
             (x, y) => x != y);
 }
Example #9
0
    public static void TestAddition()
    {
        DateTimeOffset dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70));
        Assert.Equal(17, dt.AddDays(2).Day);
        Assert.Equal(13, dt.AddDays(-2).Day);

        Assert.Equal(10, dt.AddMonths(2).Month);
        Assert.Equal(6, dt.AddMonths(-2).Month);

        Assert.Equal(1996, dt.AddYears(10).Year);
        Assert.Equal(1976, dt.AddYears(-10).Year);

        Assert.Equal(13, dt.AddHours(3).Hour);
        Assert.Equal(7, dt.AddHours(-3).Hour);

        Assert.Equal(25, dt.AddMinutes(5).Minute);
        Assert.Equal(15, dt.AddMinutes(-5).Minute);

        Assert.Equal(35, dt.AddSeconds(30).Second);
        Assert.Equal(2, dt.AddSeconds(-3).Second);

        Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
        Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
    }
    public void From_FromFixedDateTime_Tests(int value)
    {
        var originalPointInTime = new DateTimeOffset(1976, 12, 31, 17, 0, 0, 0, TimeSpan.Zero);

        Assert.AreEqual(value.Years().From(originalPointInTime), originalPointInTime.AddYears(value));
        Assert.AreEqual(value.Months().From(originalPointInTime), originalPointInTime.AddMonths(value));
        Assert.AreEqual(value.Weeks().From(originalPointInTime), originalPointInTime.AddDays(value*DaysPerWeek));
        Assert.AreEqual(value.Days().From(originalPointInTime), originalPointInTime.AddDays(value));

        Assert.AreEqual(value.Hours().From(originalPointInTime), originalPointInTime.AddHours(value));
        Assert.AreEqual(value.Minutes().From(originalPointInTime), originalPointInTime.AddMinutes(value));
        Assert.AreEqual(value.Seconds().From(originalPointInTime), originalPointInTime.AddSeconds(value));
        Assert.AreEqual(value.Milliseconds().From(originalPointInTime), originalPointInTime.AddMilliseconds(value));
        Assert.AreEqual(value.Ticks().From(originalPointInTime), originalPointInTime.AddTicks(value));
    }
        internal AdmiralRankingPoints(Admiral rpAdmiral)
        {
            r_Owner = rpAdmiral;
            r_AdmiralID = rpAdmiral.ID;

            ApiService.SubscribeOnce("api_port/port", delegate
            {
                ReloadInitialRankingPoints();

                PreviousUpdateDifference = new AdmiralRankingPointsDifference(this, AdmiralRankingPointsDifferenceType.PreviousUpdate);
                DayDifference = new AdmiralRankingPointsDifference(this, AdmiralRankingPointsDifferenceType.Day);
                MonthDifference = new AdmiralRankingPointsDifference(this, AdmiralRankingPointsDifferenceType.Month);

                Update();

                var rRankUpdateTime = new DateTimeOffset(DateTimeOffset.Now.Date, TimeSpan.FromHours(6.0));
                var rDayTimeSpan = TimeSpan.FromDays(1.0);
                Observable.Timer(rRankUpdateTime.AddDays(1.0), rDayTimeSpan).Subscribe(delegate
                {
                    PreviousUpdateDifference.Reload();
                    DayDifference.Reload();
                    OnPropertyChanged(nameof(PreviousUpdateDifference));
                    OnPropertyChanged(nameof(DayDifference));
                });

                rRankUpdateTime += TimeSpan.FromHours(12.0);
                if (DateTimeOffset.Now > rRankUpdateTime)
                    rRankUpdateTime += rDayTimeSpan;
                Observable.Timer(rRankUpdateTime, rDayTimeSpan).Subscribe(delegate
                {
                    PreviousUpdateDifference.Reload();
                    OnPropertyChanged(nameof(PreviousUpdateDifference));
                });

                var rNow = DateTimeOffset.Now;
                var rFinalizationTime = new DateTimeOffset(rNow.Year, rNow.Month, 1, 0, 0, 0, TimeSpan.FromHours(9.0)).AddMonths(1).AddHours(-2.0);
                if (rNow >= rFinalizationTime)
                    FinalizeThisMonth();
                else
                    Observable.Return(Unit.Default).Delay(rFinalizationTime).Subscribe(_ => FinalizeThisMonth());

                Observable.Return(Unit.Default).Delay(rFinalizationTime.AddHours(2.0)).Subscribe(_ => r_IsFinalized = false);

                RecordService.Instance.Update += RecordService_Update;
            });
        }
        void Snippets()
        {
            #region Dividing
            var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
            var availableTime = new TimeRange(now, now.AddHours(1));
            var freeSlots = availableTime.Divide(TimeSpan.FromMinutes(15));
            foreach (var freeSlot in freeSlots)
            {
                Console.WriteLine(freeSlot);
            }

            // Produces 4 15 minute time ranges.
            //
            // 13 Aug 2013 1:00:00 p.m. +12:00 for 00:15:00
            // 13 Aug 2013 1:15:00 p.m. +12:00 for 00:15:00
            // 13 Aug 2013 1:30:00 p.m. +12:00 for 00:15:00
            // 13 Aug 2013 1:45:00 p.m. +12:00 for 00:15:00
            #endregion
        }
Example #13
0
 private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd)
 {
     switch (unit)
     {
         case IntervalUnit.Day:
             return date.AddDays(amountToAdd);
         case IntervalUnit.Hour:
             return date.AddHours(amountToAdd);
         case IntervalUnit.Minute:
             return date.AddMinutes(amountToAdd);
         case IntervalUnit.Month:
             return date.AddMonths(amountToAdd);
         case IntervalUnit.Second:
             return date.AddSeconds(amountToAdd);
         case IntervalUnit.Millisecond:
             return date.AddMilliseconds(amountToAdd);
         case IntervalUnit.Week:
             return date.AddDays(amountToAdd*7);
         case IntervalUnit.Year:
             return date.AddYears(amountToAdd);
         default:
             throw new ArgumentException("Unknown IntervalUnit");
     }
 }
		public static DateTimeOffset Round(this DateTimeOffset dateTime, RoundTo rt)
		{
			DateTimeOffset rounded;

		    switch (rt)
			{
				case RoundTo.Second:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second,dateTime.Offset);
						if (dateTime.Millisecond >= 500)
						{
							rounded = rounded.AddSeconds(1);
						}
						break;
					}
				case RoundTo.Minute:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0,dateTime.Offset);
						if (dateTime.Second >= 30)
						{
							rounded = rounded.AddMinutes(1);
						}
						break;
					}
				case RoundTo.Hour:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0,dateTime.Offset);
						if (dateTime.Minute >= 30)
						{
							rounded = rounded.AddHours(1);
						}
						break;
					}
				case RoundTo.Day:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0,dateTime.Offset);
						if (dateTime.Hour >= 12)
						{
							rounded = rounded.AddDays(1);
						}
						break;
					}
				default:
					{
                        throw new ArgumentOutOfRangeException("rt");
					}
			}

			return rounded;
		}
        public void TestHourlyIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero);

            CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
            yearlyTrigger.StartTimeUtc = startCalendar;
            yearlyTrigger.RepeatIntervalUnit = IntervalUnit.Hour;
            yearlyTrigger.RepeatInterval = 100; // every 100 hours

            DateTimeOffset targetCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero);

            targetCalendar = targetCalendar.AddHours(400); // jump 400 hours (4 intervals)

            IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6);
            DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Hour increment result not as expected.");
        }
        public void ToRelativeTimeTest()
        {
            var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero);
            var now = DateTimeOffset.Now;

            Assert.AreEqual("now", now.ToRelativeTimeString());
            Assert.AreEqual("now", now.ToRelativeTimeString(now));

            Assert.AreEqual("1 second ago", date.AddSeconds(-1).ToRelativeTimeString(date));
            Assert.AreEqual("10 seconds ago", date.AddSeconds(-10).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute ago", date.AddSeconds(-90).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute ago", date.AddSeconds(-100).ToRelativeTimeString(date));
            Assert.AreEqual("2 minutes ago", date.AddSeconds(-120).ToRelativeTimeString(date));
            Assert.AreEqual("7 minutes ago", date.AddMinutes(-7).ToRelativeTimeString(date));
            Assert.AreEqual("59 minutes ago", date.AddMinutes(-59).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour ago", date.AddMinutes(-60).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour ago", date.AddHours(-1).ToRelativeTimeString(date));
            Assert.AreEqual("9 hours ago", date.AddHours(-9).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddHours(-24).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddHours(-30).ToRelativeTimeString(date));
            Assert.AreEqual("2 days ago", date.AddHours(-48).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddDays(-1).ToRelativeTimeString(date));
            Assert.AreEqual("12 days ago", date.AddDays(-12).ToRelativeTimeString(date));
            Assert.AreEqual("29 days ago", date.AddDays(-29).ToRelativeTimeString(date));
            Assert.AreEqual("1 month ago", date.AddDays(-30).ToRelativeTimeString(date));
            Assert.AreEqual("1 month ago", date.AddMonths(-1).ToRelativeTimeString(date));
            Assert.AreEqual("3 months ago", date.AddMonths(-3).ToRelativeTimeString(date));
            Assert.AreEqual("11 months ago", date.AddMonths(-11).ToRelativeTimeString(date));
            Assert.AreEqual("1 year ago", date.AddMonths(-12).ToRelativeTimeString(date));
            Assert.AreEqual("1 year ago", date.AddYears(-1).ToRelativeTimeString(date));
            Assert.AreEqual("3 years ago", date.AddYears(-3).ToRelativeTimeString(date));

            Assert.AreEqual("1 second from now", date.AddSeconds(1).ToRelativeTimeString(date));
            Assert.AreEqual("10 seconds from now", date.AddSeconds(10).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(90).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(100).ToRelativeTimeString(date));
            Assert.AreEqual("2 minutes from now", date.AddSeconds(120).ToRelativeTimeString(date));
            Assert.AreEqual("7 minutes from now", date.AddMinutes(7).ToRelativeTimeString(date));
            Assert.AreEqual("59 minutes from now", date.AddMinutes(59).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddMinutes(60).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddHours(1).ToRelativeTimeString(date));
            Assert.AreEqual("9 hours from now", date.AddHours(9).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddDays(1).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddHours(24).ToRelativeTimeString(date));
            Assert.AreEqual("12 days from now", date.AddDays(12).ToRelativeTimeString(date));
            Assert.AreEqual("29 days from now", date.AddDays(29).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddDays(30).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddMonths(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 months from now", date.AddMonths(3).ToRelativeTimeString(date));
            Assert.AreEqual("11 months from now", date.AddMonths(11).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddMonths(12).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddYears(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 years from now", date.AddYears(3).ToRelativeTimeString(date));
        }
Example #17
0
        public void Subtracting()
        {
            var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
            var tick = new TimeSpan(1);
            var time = new TimeRange(now, now.AddHours(1));
            var before = new TimeRange(now - TimeSpan.FromHours(1), time.StartsOn);
            var after = new TimeRange(time.EndsOn, TimeSpan.FromHours(1));
            var mid = new TimeRange(now.AddMinutes(15), TimeSpan.FromMinutes(30));

            // No intersection
            Assert.AreEqual(1, time.Subtract(before).Count());
            Assert.AreEqual(time, time.Subtract(before).First());
            Assert.AreEqual(1, time.Subtract(after).Count());
            Assert.AreEqual(time, time.Subtract(after).First());

            // Identity
            Assert.AreEqual(0, time.Subtract(time).Count());

            // Subsumes
            Assert.AreEqual(0, time.Subtract(new TimeRange(before.StartsOn, after.EndsOn)).Count());

            // Middle
            Assert.AreEqual(2, time.Subtract(mid).Count());
            Assert.IsTrue(time.Subtract(mid).Any(t => t.StartsOn == now && t.Duration == TimeSpan.FromMinutes(15)));
            Assert.IsTrue(time.Subtract(mid).Any(t => t.StartsOn == now.AddMinutes(45) && t.Duration == TimeSpan.FromMinutes(15)));
        }
        public void When_date_is_at_least_one_day_before_another_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var target = new DateTimeOffset(2.October(2009));
            DateTimeOffset subject = target.AddHours(-24);

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target);
        }
        public void When_a_value_is_not_one_of_the_specified_values_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var value = new DateTimeOffset(31.December(2016), 1.Hours());
            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action action = () => value.Should().BeOneOf(value.AddDays(1), value.AddHours(4));

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            action.ShouldThrow<AssertFailedException>()
                .WithMessage("Expected value to be one of {<2017-01-01 +1h>, <2016-12-31 04:00:00 +1h>}, but found <2016-12-31 +1h>.");
        }
        public static CharacterModel GetCharacter(RegionsLookup region, string server, string name)
        {
            string key = string.Format("character_{0}_{1}_{2}", region, server, name);

            ObjectCache cache = MemoryCache.Default;
            CharacterModel item = cache[key] as CharacterModel;

            if (item == null)
            {
                string requestUrl = string.Format("{0}/character/{1}/{2}", GetBaseRequestURL(region), server, name);

                try
                {
                    WebClient client = new WebClient();
                    string result = client.DownloadString(requestUrl);

                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CharacterModel));

                    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(result)))
                    {
                        item = serializer.ReadObject(ms) as CharacterModel;
                    }

                    DateTimeOffset dto = new DateTimeOffset();

                    dto.AddHours(1);

                    cache.Set(key, item, DateTimeOffset.Now.AddMinutes(30));
                }
                catch (Exception ex)
                {
                }
            }

            return item;
        }
        public void TestTimeZone()
        {
            TimeZoneInfo GMT = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
            TimeZoneInfo EST = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

            // Calendar startTime = Calendar.getInstance(EST);
            var startTime = new DateTime(2006, 3, 7, 7, 0, 0, DateTimeKind.Utc);
            startTime = TimeZoneInfo.ConvertTimeFromUtc(startTime, EST);

            // Same timezone
            {
                NthIncludedDayTrigger t = new NthIncludedDayTrigger("name", "group");
                t.IntervalType = NthIncludedDayTrigger.IntervalTypeWeekly;
                t.N = 3;
                t.StartTimeUtc = startTime.ToUniversalTime();
                t.FireAtTime = "8:00";
                t.TimeZone = EST;

                DateTimeOffset? firstTime = t.ComputeFirstFireTimeUtc(null);

                // Calendar firstTimeCal = Calendar.getInstance(EST);
                DateTime firstTimeCal = new DateTime(startTime.Year, startTime.Month, startTime.Day, 8, 0, 0, 0, DateTimeKind.Utc);
                firstTimeCal = TimeZoneInfo.ConvertTimeFromUtc(firstTimeCal, EST);
                //roll start date forward to first day of the next week
                while (firstTimeCal.DayOfWeek != t.TriggerCalendarFirstDayOfWeek)
                {
                    firstTimeCal = firstTimeCal.AddDays(-1);
                }

                //first day of the week counts as one. add two more to get N=3.
                firstTimeCal = firstTimeCal.AddDays(2);

                //if we went back too far, shift forward a week.
                if (firstTimeCal < startTime)
                {
                    firstTimeCal = firstTimeCal.AddDays(7);
                }

                Assert.AreEqual(firstTime, firstTimeCal);
            }

            // Different timezones
            {
                NthIncludedDayTrigger t = new NthIncludedDayTrigger("name", "group");
                t.IntervalType = NthIncludedDayTrigger.IntervalTypeWeekly;
                t.N = 3;
                t.StartTimeUtc = startTime;
                t.FireAtTime = "8:00";
                t.TimeZone = GMT;

                DateTimeOffset? firstTime = t.ComputeFirstFireTimeUtc(null);
                // Calendar firstTimeCal = Calendar.getInstance(EST);
                DateTimeOffset firstTimeCal = new DateTimeOffset(startTime.Year, startTime.Month, startTime.Day, 8, 0, 0, 0, TimeSpan.Zero);

                //EST is GMT-5
                firstTimeCal.AddHours(-5);

                //roll start date forward to first day of the next week
                while (firstTimeCal.DayOfWeek != t.TriggerCalendarFirstDayOfWeek)
                {
                    firstTimeCal = firstTimeCal.AddDays(-1);
                }

                //first day of the week counts as one. add two more to get N=3.
                firstTimeCal = firstTimeCal.AddDays(2);

                //if we went back too far, shift forward a week.
                if (firstTimeCal < startTime)
                {
                    firstTimeCal = firstTimeCal.AddDays(7);
                }

                Assert.AreEqual(firstTime, firstTimeCal);
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="OneTimeToken"/> class.
		/// Recreates a previously issued token for verification
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="tokenStamp">The token stamp.</param>
		/// <param name="expiration">The expiration.</param>
		/// <exception cref="ArgumentNullException">
		/// </exception>
		public OneTimeToken(byte[] key, byte[] tokenStamp, DateTimeOffset expiration)
		{
			if (key != null || key.Length <= 0)
			{
				_hmacSha = new HMACSHA256(key);

				if (tokenStamp != null || tokenStamp.Length <= 0)
				{
					TokenStamp = tokenStamp;
				}
				else
				{
					throw new ArgumentNullException(nameof(tokenStamp));
				}

				_rng = System.Security.Cryptography.RandomNumberGenerator.Create();

				_issueTime = expiration.AddHours(-1);
			}
			else
			{
				throw new ArgumentNullException(nameof(key));
			}
		}
        public void When_date_is_not_within_50_hours_before_another_date_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var target = new DateTimeOffset(10.April(2010).At(12, 0), 0.Hours());
            DateTimeOffset subject = target.AddHours(-50).AddSeconds(-1);

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act =
                () => subject.Should().BeWithin(TimeSpan.FromHours(50)).Before(target, "{0} hours is enough", 50);

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage(
                "Expected date and/or time <2010-04-08 09:59:59> to be within 2d and 2h before <2010-04-10 12:00:00> because 50 hours is enough, but it differs 2d, 2h and 1s.");
        }
        public void When_date_is_not_at_least_one_day_before_another_it_should_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var target = new DateTimeOffset(2.October(2009), 0.Hours());
            DateTimeOffset subject = target.AddHours(-23);

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            Action act = () => subject.Should().BeAtLeast(TimeSpan.FromDays(1)).Before(target, "we like {0}", "that");

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            act.ShouldThrow<AssertFailedException>().WithMessage(
                "Expected date and/or time <2009-10-01 01:00:00> to be at least 1d before <2009-10-02> because we like that, but it differs 23h.");
        }
        public void When_date_is_more_than_the_required_one_day_before_another_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var target = new DateTimeOffset(2.October(2009));
            DateTimeOffset subject = target.AddHours(-25);

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            subject.Should().BeMoreThan(TimeSpan.FromDays(1)).Before(target);
        }
        /// <summary>
        /// Returns an enumerable collection of log blobs containing Analytics log records. The blobs are retrieved lazily.
        /// </summary>
        /// <param name="service">A <see cref="StorageService"/> enumeration value.</param>
        /// <param name="startTime">A <see cref="DateTimeOffset"/> object representing the start of the time range for which logs should be retrieved.</param>
        /// <param name="endTime">A <see cref="DateTimeOffset"/> object representing the end of the time range for which logs should be retrieved.</param>
        /// <param name="operations">A <see cref="LoggingOperations"/> enumeration value that indicates the types of logging operations on which to filter the log blobs.</param>
        /// <param name="details">A <see cref="BlobListingDetails"/> enumeration value that indicates whether or not blob metadata should be returned. Only <c>None</c> and <c>Metadata</c> are valid values. </param>
        /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>An enumerable collection of objects that implement <see cref="ICloudBlob"/> and are retrieved lazily.</returns>
        /// <remarks>Note that specifying a logging operation type for the <paramref name="operations"/> parameter will return any Analytics log blob that contains the specified logging operation,
        /// even if that log blob also includes other types of logging operations. Also note that the only currently supported values for the <paramref name="details"/> 
        /// parameter are <c>None</c> and <c>Metadata</c>.</remarks>
        public IEnumerable<ICloudBlob> ListLogs(StorageService service, DateTimeOffset startTime, DateTimeOffset? endTime, LoggingOperations operations, BlobListingDetails details, BlobRequestOptions options, OperationContext operationContext)
        {
            CloudBlobDirectory logDirectory = this.GetLogDirectory(service);
            BlobListingDetails metadataDetails = details;
            DateTimeOffset utcStartTime = startTime.ToUniversalTime();
            DateTimeOffset dateCounter = new DateTimeOffset(utcStartTime.Ticks - (utcStartTime.Ticks % TimeSpan.TicksPerHour), utcStartTime.Offset);
            DateTimeOffset? utcEndTime = null;
            string endPrefix = null;

            // Ensure that the date range is correct.
            if (endTime.HasValue)
            {
                utcEndTime = endTime.Value.ToUniversalTime();
                endPrefix = logDirectory.Prefix + utcEndTime.Value.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture);
                if (utcStartTime > utcEndTime.Value)
                {
                    string errorString = string.Format(CultureInfo.InvariantCulture, SR.StartTimeExceedsEndTime, startTime, endTime.Value);
                    throw new ArgumentException(errorString);
                }
            }

            // Currently only support the ability to retrieve metadata on logs.
            if (details.HasFlag(BlobListingDetails.Copy) || details.HasFlag(BlobListingDetails.Snapshots) || details.HasFlag(BlobListingDetails.UncommittedBlobs))
            {
                throw new ArgumentException(SR.InvalidListingDetails);
            }

            // At least one LogType must be specified.
            if (operations == LoggingOperations.None)
            {
                throw new ArgumentException(SR.InvalidLoggingLevel);
            }

            // If metadata or a specific LogType is specified, metadata should be retrieved.
            if (details.HasFlag(BlobListingDetails.Metadata) || !operations.HasFlag(LoggingOperations.All))
            {
                metadataDetails = BlobListingDetails.Metadata;
            }

            // Check logs using an hour-based prefix until we reach a day boundary.
            while (dateCounter.Hour > 0)
            {
                string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture);
                IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext);

                foreach (ICloudBlob log in currentLogs)
                {
                    if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0)
                    {
                        if (IsCorrectLogType(log, operations))
                        {
                            yield return log;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                dateCounter = dateCounter.AddHours(1);
                if (dateCounter > DateTimeOffset.UtcNow.AddHours(1))
                {
                    yield break;
                }
            }

            // Check logs using a day-based prefix until we reach a month boundary.
            while (dateCounter.Day > 1)
            {
                string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext);

                foreach (ICloudBlob log in currentLogs)
                {
                    if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0)
                    {
                        if (IsCorrectLogType(log, operations))
                        {
                            yield return log;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                dateCounter = dateCounter.AddDays(1);
                if (dateCounter > DateTimeOffset.UtcNow.AddHours(1))
                {
                    yield break;
                }
            }

            // Check logs using a month-based prefix until we reach a year boundary.
            while (dateCounter.Month > 1)
            {
                string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM", CultureInfo.InvariantCulture);
                IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext);

                foreach (ICloudBlob log in currentLogs)
                {
                    if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0)
                    {
                        if (IsCorrectLogType(log, operations))
                        {
                            yield return log;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                dateCounter = dateCounter.AddMonths(1);
                if (dateCounter > DateTimeOffset.UtcNow.AddHours(1))
                {
                    yield break;
                }
            }

            // Continue using a year-based prefix. 
            while (true)
            {
                string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy", CultureInfo.InvariantCulture);
                IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext);

                foreach (ICloudBlob log in currentLogs)
                {
                    if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0)
                    {
                        if (IsCorrectLogType(log, operations))
                        {
                            yield return log;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                dateCounter = dateCounter.AddYears(1);
                if (dateCounter > DateTimeOffset.UtcNow.AddHours(1))
                { 
                    yield break;
                }
            }
        }
        public IHttpActionResult ResetDataSource()
        {
            DateAndTimeOfDayContext db = new DateAndTimeOfDayContext();
            if (!db.Customers.Any())
            {
                DateTimeOffset dateTime = new DateTimeOffset(2014, 12, 24, 1, 2, 3, 4, new TimeSpan(-8, 0, 0));
                IEnumerable<EfCustomer> customers = Enumerable.Range(1, 5).Select(e =>
                    new EfCustomer
                    {
                        Id = e,
                        DateTime = dateTime.AddYears(e).AddHours(e).AddMilliseconds(e).DateTime,
                        NullableDateTime = e % 2 == 0 ? (DateTime?)null : dateTime.AddHours(e * 5).AddMilliseconds(e * 5).DateTime,
                        Offset = dateTime.AddMonths(e).AddHours(e).AddMilliseconds(e),
                        NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dateTime.AddDays(e).AddHours(e * 5)
                    }).ToList();

                foreach (EfCustomer customer in customers)
                {
                    db.Customers.Add(customer);
                }

                db.SaveChanges();
            }

            return Ok();
        }
Example #28
0
 public static void AddHours(DateTimeOffset dateTimeOffset, double hours, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddHours(hours));
 }
        public void When_date_is_within_1d_before_another_date_it_should_not_throw()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var target = new DateTimeOffset(10.April(2010));
            DateTimeOffset subject = target.AddHours(-23);

            //-----------------------------------------------------------------------------------------------------------
            // Act / Assert
            //-----------------------------------------------------------------------------------------------------------
            subject.Should().BeWithin(TimeSpan.FromHours(24)).Before(target);
        }
Example #30
0
        private async Task CreateTimerResults(TimerCounter timerCounter)
        {
            var userId = await GetUserId();

            if (timerCounter == null) return;

            try
            {
                // remove previous results, if any
                var results = await _context.TimerResults.Where(e => e.TimerCounterId == timerCounter.TimerCounterId && e.DiteUserId == userId).ToListAsync();
                if (results != null) _context.TimerResults.RemoveRange(results);
            }
            catch (Exception ex)
            {
                // required connection string parameter - MultipleActiveResultSets=True
                throw new Exception("error removing old results", ex);
            }

            DateTimeOffset localStart = timerCounter.TimerStartLocal;
            DateTimeOffset localEnd = timerCounter.TimerEndLocal;

            // first end
            var nextEnd = new DateTimeOffset(localStart.Year, localStart.Month, localStart.Day, localStart.Hour, 0, 0, localStart.Offset);
            nextEnd = nextEnd.AddHours(1);

            if(nextEnd>localEnd)
            {
                // within same hour; only result
                TimerResult result = NewTimerResult(timerCounter, userId, localStart, localEnd);
                _context.TimerResults.Add(result);
                return;
            }
            else
            {
                // first hour; first result
                TimerResult result = NewTimerResult(timerCounter, userId, localStart, nextEnd);
                _context.TimerResults.Add(result);
               
                // sequence
                var nextStart = new DateTimeOffset(localStart.Year, localStart.Month, localStart.Day, localStart.Hour, 0, 0, localStart.Offset);

                while ((nextStart = nextStart.AddHours(1)) < localEnd 
                    && ((nextEnd = nextEnd.AddHours(1)) < localEnd))
                {
                    var seqResult = NewTimerResult(timerCounter, userId, nextStart, nextEnd);
                    _context.TimerResults.Add(seqResult);
                }

                // last hour; last result
                TimerResult resultLast = NewTimerResult(timerCounter, userId, nextStart, localEnd);
                _context.TimerResults.Add(resultLast);

            }
        }