public void QuickPulseCollectionTimeSlotManagerHandlesFirstHalfOfSecond()
        {
            // ARRANGE
            var manager = new QuickPulseCollectionTimeSlotManager();

            var now = new DateTimeOffset(2016, 1, 1, 0, 0, 1, TimeSpan.Zero);
            now = now.AddMilliseconds(499);

            // ACT
            DateTimeOffset slot = manager.GetNextCollectionTimeSlot(now);

            // ASSERT
            Assert.AreEqual(now.AddMilliseconds(1), slot);
        }
Example #2
0
        public void SortingFinelyDifferentDateTimes()
        {
            using (var transaction = _realm.BeginWrite())
            {
                foreach (var ms in new int[] { 10, 999, 998, 42 })
                {
                    var birthday = new DateTimeOffset(1912, 6, 23, 23, 59, 59, ms, TimeSpan.Zero);
                    foreach (var addMs in new double[] { -2000.0, 1.0, -1.0, 1000.0, 100.0 })
                    {
                        _realm.Add(new Person { Birthday = birthday.AddMilliseconds(addMs) });
                    }
                }

                transaction.Commit();
            }

            // Assert
            var sortedTurings = _realm.All<Person>().OrderBy(p => p.Birthday);
            var prevB = new DateTimeOffset();
            foreach (var t in sortedTurings)
            {
                Assert.That(t.Birthday, Is.GreaterThan(prevB));
                prevB = t.Birthday;
            }
        }
        public static DateTime ToDateTime(this long value)
        {
            var dateTime = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            dateTime = dateTime.AddMilliseconds(value);

            return dateTime.UtcDateTime;
        }
Example #4
0
        public void RoundsToNearestSecond()
        {
            var now = new DateTimeOffset(2015, 03, 04, 20, 07, 21, TimeSpan.Zero);

            var testDto1 = now.AddMilliseconds(450);
            var actualDto1 = testDto1.RoundToNearestSecond();

            Assert.AreEqual(now, actualDto1);
            TestHelper.AssertSerialiseEqual(now, actualDto1);

            var expectedDto2 = now.AddSeconds(1);
            var testDto2 = now.AddMilliseconds(550);
            var actualDto2 = testDto2.RoundToNearestSecond();

            Assert.AreEqual(expectedDto2, actualDto2);
            TestHelper.AssertSerialiseEqual(expectedDto2, actualDto2);
        }
        public DateTimeOffset GetNextSchedule(DateTimeOffset withinThisMinute)
        {
            Contract.Requires(null != withinThisMinute);
            Contract.Ensures(null != Contract.Result<DateTimeOffset>());

            // we only add a millisecond as we get exceptions on certain Windows versions 
            // while converting DateTime to DateTimeOffset
            // see https://support.microsoft.com/en-us/kb/2346777 for details

            if(0 == withinThisMinute.Millisecond)
            {
                withinThisMinute = withinThisMinute.AddMilliseconds(1);
            }

            //Test Name:	IsScheduledToRunOnTheMinuteReturnsTrue
            //Test Outcome:	Failed
            //Result Message:	
            //Test method biz.dfch.CS.Appclusive.Scheduler.Core.Tests.ScheduledJobSchedulerTest.IsScheduledToRunOnTheMinuteReturnsTrue threw exception: 
            //System.ArgumentOutOfRangeException: The UTC time represented when the offset is applied must be between year 0 and 10,000.
            //Parameter name: offset
            //Result StandardOutput:	
            //2019-04-13 20:00:00,000|ERROR|[email protected]: 'The UTC time represented when the offset is applied must be between year 0 and 10,000.
            //Parameter name: offset'
            //[The UTC time represented when the offset is applied must be between year 0 and 10,000.
            //Parameter name: offset]
            //   at System.DateTimeOffset.ValidateDate(DateTime dateTime, TimeSpan offset)
            //   at System.DateTimeOffset..ctor(DateTime dateTime, TimeSpan offset)
            //   at biz.dfch.CS.Appclusive.Scheduler.Core.ScheduledJobScheduler.GetNextSchedule(DateTimeOffset withinThisMinute) 
            // in c:\Github\biz.dfch.CS.Appclusive.Scheduler\src\biz.dfch.CS.Appclusive.Scheduler.Core\ScheduledJobScheduler.cs:line 86

            try
            {
                var nextSchedule = DateTimeOffset.MinValue;

                if (IsCrontabExpression())
                {
                    nextSchedule = GetNextScheduleFromCrontabExpression(withinThisMinute);
                }
                else if(IsQuartzExpression())
                {
                    nextSchedule = GetNextScheduleFromQuartzExpression(withinThisMinute);
                }
                else
                {
                    Trace.WriteLine("JobId '{0}': invalid Crontab or Quartz expression '{1}'", this.job.Id, job.Crontab);
                }

                return nextSchedule;
            }
            catch (Exception ex)
            {
                var message = string.Format("JobId '{0}': {1}", this.job.Id, ex.Message);
                Trace.WriteException(message, ex);

                throw;
            }
        }
Example #6
0
        public void CanAddMillisecondsAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dto = new DateTimeOffset(2015, 3, 8, 1, 59, 59, 999, TimeSpan.FromHours(-8));
            var result = dto.AddMilliseconds(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);
        }
        public void AppendToExistingHDF5()
        {
            if (File.Exists("AppendToExistingHDF5.h5"))
                File.Delete("AppendToExistingHDF5.h5");

            Epoch e1;
            Epoch e2;

            using (var persistor = H5EpochPersistor.Create("AppendToExistingHDF5.h5"))
            {
                var time = new DateTimeOffset(2011, 8, 22, 11, 12, 0, 0, TimeSpan.FromHours(-6));

                var src = persistor.AddSource("source1", null);
                persistor.BeginEpochGroup("label1", src, time);

                e1 = RunSingleEpoch(5000, 2, persistor);
                persistor.EndEpochGroup(time.AddMilliseconds(100));

                persistor.Close();
            }

            using (var persistor = new H5EpochPersistor("AppendToExistingHDF5.h5"))
            {
                var time = new DateTimeOffset(2011, 8, 22, 11, 12, 0, 0, TimeSpan.FromHours(-6));

                var src = persistor.AddSource("source2", null);
                persistor.BeginEpochGroup("label2", src, time);

                e2 = RunSingleEpoch(5000, 2, persistor);
                persistor.EndEpochGroup(time.AddMilliseconds(100));

                persistor.Close();
            }

            using (var persistor = new H5EpochPersistor("AppendToExistingHDF5.h5"))
            {
                Assert.AreEqual(2, persistor.Experiment.EpochGroups.Count());

                var eg1 = persistor.Experiment.EpochGroups.First(g => g.Label == "label1");

                Assert.AreEqual(1, eg1.EpochBlocks.Count());
                Assert.AreEqual(1, eg1.EpochBlocks.First().Epochs.Count());
                PersistentEpochAssert.AssertEpochsEqual(e1, eg1.EpochBlocks.First().Epochs.First());

                var eg2 = persistor.Experiment.EpochGroups.First(g => g.Label == "label2");

                Assert.AreEqual(1, eg2.EpochBlocks.Count());
                Assert.AreEqual(1, eg2.EpochBlocks.First().Epochs.Count());
                PersistentEpochAssert.AssertEpochsEqual(e2, eg2.EpochBlocks.First().Epochs.First());
            }
        }
Example #8
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));
    }
        /// <summary>
        /// Determine the next time that is 'included' by the
        /// Calendar after the given time. Return the original value if timeStamp is
        /// included. Return 0 if all days are excluded.
        /// </summary>
        /// <param name="timeUtc"></param>
        /// <returns></returns>
        public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
        {
            DateTimeOffset nextIncludedTime = timeUtc.AddMilliseconds(1); //plus on millisecond

            while (!IsTimeIncluded(nextIncludedTime))
            {
                //If the time is in a range excluded by this calendar, we can
                // move to the end of the excluded time range and continue testing
                // from there. Otherwise, if nextIncludedTime is excluded by the
                // baseCalendar, ask it the next time it includes and begin testing
                // from there. Failing this, add one millisecond and continue
                // testing.
                if (cronExpression.IsSatisfiedBy(nextIncludedTime))
                {
                    nextIncludedTime = cronExpression.GetNextValidTimeAfter(nextIncludedTime).Value;
                }
                else if ((GetBaseCalendar() != null) &&
                         (!GetBaseCalendar().IsTimeIncluded(nextIncludedTime)))
                {
                    nextIncludedTime =
                        GetBaseCalendar().GetNextIncludedTimeUtc(nextIncludedTime);
                }
                else
                {
                    nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
                }
            }

            return nextIncludedTime;
        }
 /// <summary>
 /// Datetime from an int representing a unix epoch time
 /// </summary>
 /// <param name="msSinceEpoch"></param>
 /// <returns></returns>
 public static DateTimeOffset EpochMillisecondsToDateTime(this long msSinceEpoch)
 {
     var date = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
     return date.AddMilliseconds(msSinceEpoch);
 }
        public async Task Expired_Reference_Token()
        {
            now = DateTimeOffset.UtcNow;

            var store = new InMemoryTokenHandleStore();
            var validator = Factory.CreateTokenValidator(store);

            var token = TokenFactory.CreateAccessToken(new Client { ClientId = "roclient" }, "valid", 2, "read", "write");
            var handle = "123";

            await store.StoreAsync(handle, token);
            
            now = now.AddMilliseconds(2000);

            var result = await validator.ValidateAccessTokenAsync("123");

            result.IsError.Should().BeTrue();
            result.Error.Should().Be(Constants.ProtectedResourceErrors.ExpiredToken);
        }
Example #13
0
 public static void AddMilliseconds(DateTimeOffset dateTimeOffset, double milliseconds, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddMilliseconds(milliseconds));
 }
 public static DateTimeOffset ConvertFromJsTimestamp(long timestamp)
 {
     DateTimeOffset origin = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, DateTimeOffset.Now.Offset);
     return origin.AddMilliseconds(timestamp);
 }
Example #15
0
        public void FindingByMilliseconds()
        {
            var birthday = new DateTimeOffset(1912, 6, 23, 23, 59, 59, 0, TimeSpan.Zero);
            using (var transaction = _realm.BeginWrite())
            {
                foreach (var addMs in new double[] { 0.0, 1.0, -1.0 })
                {
                    _realm.Add(new Person { Birthday = birthday.AddMilliseconds(addMs) });
                }

                transaction.Commit();
            }

            // Assert
            Assert.That(_realm.All<Person>().Count(p => p.Birthday < birthday), Is.EqualTo(1));
            Assert.That(_realm.All<Person>().Count(p => p.Birthday == birthday), Is.EqualTo(1));
            Assert.That(_realm.All<Person>().Count(p => p.Birthday >= birthday), Is.EqualTo(2));
            Assert.That(_realm.All<Person>().Count(p => p.Birthday > birthday), Is.EqualTo(1));
        }
        public DateTimeOffset GetNextScheduleFromQuartzExpression(DateTimeOffset withinThisMinute)
        {
            var expression = new CronExpression(job.Crontab);

            var startMinute = new DateTimeOffset(withinThisMinute.Year, withinThisMinute.Month, withinThisMinute.Day, withinThisMinute.Hour, withinThisMinute.Minute, 0, 0, withinThisMinute.Offset);
            startMinute = startMinute.AddMilliseconds(-1);

            var result = DateTimeOffset.MinValue;

            var nextOccurrence = expression.GetTimeAfter(startMinute.ToUniversalTime());
            if (nextOccurrence.HasValue)
            {
                var isWithinTheNextMinute = 60 > Math.Abs((nextOccurrence.Value.LocalDateTime - startMinute).TotalSeconds);
                Trace.WriteLine("CronExp: Id {0} ('{1}'): '{2}' [{3}].", job.Id, job.Crontab, nextOccurrence.Value.ToString("yyyy-MM-dd HH:mm:sszzz"), isWithinTheNextMinute);
                if (isWithinTheNextMinute)
                {
                    result = nextOccurrence.Value.LocalDateTime;
                }
            }
            else
            {
                Trace.WriteLine("CronExp: Id {0} ('{1}'): '{2}' [{3}].", job.Id, job.Crontab, result.ToString("yyyy-MM-dd HH:mm:sszzz"), false);
            }

            return result;
        }
Example #17
0
        /// <summary>
        /// Determine the next time (in milliseconds) that is 'included' by the
        /// Calendar after the given time. Return the original value if timeStamp is
        /// included. Return 0 if all days are excluded.
        /// </summary>
        /// <param name="timeUtc"></param>
        /// <returns></returns>
        /// <seealso cref="ICalendar.GetNextIncludedTimeUtc"/>
        public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
        {
            DateTimeOffset nextIncludedTime = timeUtc.AddMilliseconds(oneMillis);

            while (!IsTimeIncluded(nextIncludedTime))
            {
                if (!invertTimeRange)
                {
                    //If the time is in a range excluded by this calendar, we can
                    // move to the end of the excluded time range and continue
                    // testing from there. Otherwise, if nextIncludedTime is
                    // excluded by the baseCalendar, ask it the next time it
                    // includes and begin testing from there. Failing this, add one
                    // millisecond and continue testing.
                    if ((nextIncludedTime >=
                         GetTimeRangeStartingTimeUtc(nextIncludedTime)) &&
                        (nextIncludedTime <=
                         GetTimeRangeEndingTimeUtc(nextIncludedTime)))
                    {
                        nextIncludedTime =
                            GetTimeRangeEndingTimeUtc(nextIncludedTime).AddMilliseconds(oneMillis);
                    }
                    else if ((GetBaseCalendar() != null) &&
                             (!GetBaseCalendar().IsTimeIncluded(nextIncludedTime)))
                    {
                        nextIncludedTime =
                            GetBaseCalendar().GetNextIncludedTimeUtc(nextIncludedTime);
                    }
                    else
                    {
                        nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
                    }
                }
                else
                {
                    //If the time is in a range excluded by this calendar, we can
                    // move to the end of the excluded time range and continue
                    // testing from there. Otherwise, if nextIncludedTime is
                    // excluded by the baseCalendar, ask it the next time it
                    // includes and begin testing from there. Failing this, add one
                    // millisecond and continue testing.
                    if (nextIncludedTime <
                        GetTimeRangeStartingTimeUtc(nextIncludedTime))
                    {
                        nextIncludedTime =
                            GetTimeRangeStartingTimeUtc(nextIncludedTime);
                    }
                    else if (nextIncludedTime >
                             GetTimeRangeEndingTimeUtc(nextIncludedTime))
                    {
                        //(move to start of next day)
                        nextIncludedTime = GetEndOfDay(nextIncludedTime);
                        nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
                    }
                    else if ((GetBaseCalendar() != null) &&
                             (!GetBaseCalendar().IsTimeIncluded(nextIncludedTime)))
                    {
                        nextIncludedTime =
                            GetBaseCalendar().GetNextIncludedTimeUtc(nextIncludedTime);
                    }
                    else
                    {
                        nextIncludedTime = nextIncludedTime.AddMilliseconds(1);
                    }
                }
            }

            return nextIncludedTime;
        }
        /// <summary>
        /// Asserts that the current <see cref="DateTimeOffset"/> is within the specified number of milliseconds (default = 20 ms)
        /// from the specified <paramref name="nearbyTime"/> value.
        /// </summary>
        /// <remarks>
        /// Use this assertion when, for example the database truncates datetimes to nearest 20ms. If you want to assert to the exact datetime,
        /// use <see cref="Be(DateTimeOffset, string, object[])"/>.
        /// </remarks>
        /// <param name="nearbyTime">
        /// The expected time to compare the actual value with.
        /// </param>
        /// <param name="precision">
        /// The maximum amount of milliseconds which the two values may differ.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion 
        /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public AndConstraint<DateTimeOffsetAssertions> BeCloseTo(DateTimeOffset nearbyTime, int precision = 20,
            string because = "",
            params object[] becauseArgs)
        {
            long distanceToMinInMs = (long)(nearbyTime - DateTimeOffset.MinValue).TotalMilliseconds;
            DateTimeOffset minimumValue = nearbyTime.AddMilliseconds(-Math.Min(precision, distanceToMinInMs));

            long distanceToMaxInMs = (long)(DateTimeOffset.MaxValue - nearbyTime).TotalMilliseconds;
            DateTimeOffset maximumValue = nearbyTime.AddMilliseconds(Math.Min(precision, distanceToMaxInMs));

            Execute.Assertion
                .ForCondition(Subject.HasValue && (Subject.Value >= minimumValue) && (Subject.Value <= maximumValue))
                .BecauseOf(because, becauseArgs)
                .FailWith("Expected {context:date and time} to be within {0} ms from {1}{reason}, but found {2}.",
                    precision,
                    nearbyTime, Subject.HasValue ? Subject.Value : default(DateTimeOffset?));

            return new AndConstraint<DateTimeOffsetAssertions>(this);
        }
Example #19
0
 private static DateTimeOffset StripMiliseconds(DateTimeOffset date)
 {
     return date.AddMilliseconds(-date.Millisecond);
 }
Example #20
0
        /// <summary>
        /// Convert a unix time in milliseconds into a DateTime
        /// </summary>
        public static DateTimeOffset FromUnixTimeInMilliseconds(long milliseconds)
        {
            var offset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

            return offset.AddMilliseconds(milliseconds);
        }
        public void ShouldAllowLongStringEpochParameters()
        {
            if (File.Exists("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5"))
                File.Delete("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5");

            var gID = new Guid("{2F2719F7-4A8C-4C22-9698-BE999DBC5385}");
            using (
                var exp = new EpochHDF5Persistor("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5", null, () => gID)
                )
            {
                var time = new DateTimeOffset(1000, TimeSpan.Zero);
                var guid = new Guid("053C64D4-ED7A-4128-AA43-ED115716A97D");
                var props = new Dictionary<string, object>();
                props["key1"] =
                    "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
                    //100 elements
                props["key2"] = 2;

                const string protocolID = "Epoch.Fixture";
                Dictionary<string, object> parameters = props;

                dev1 = new UnitConvertingExternalDevice(dev1Name, "DEVICECO", new Measurement(0, "V"));
                dev2 = new UnitConvertingExternalDevice(dev2Name, "DEVICECO", new Measurement(0, "V"));

                var stream1 = new DAQInputStream("Stream1");
                var stream2 = new DAQInputStream("Stream2");

                var stimParameters = new Dictionary<string, object>();
                stimParameters[param1] = value1;
                stimParameters[param2] = value2;

                var srate = new Measurement(1000, "Hz");

                List<Measurement> samples =
                    Enumerable.Range(0, 10000).Select(i => new Measurement((decimal) Math.Sin((double) i/100), "mV")).
                        ToList();
                var stimData = new OutputData(samples, srate, false);

                var stim1 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted
                var stim2 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted

                var e = new Epoch(protocolID, parameters);
                e.Stimuli[dev1] = stim1;
                e.Stimuli[dev2] = stim2;

                DateTimeOffset start = DateTimeOffset.Parse("1/11/2011 6:03:29 PM -08:00");
                // Do this to match the XML stored in the EpochXML.txt resource
                e.StartTime = Maybe<DateTimeOffset>.Yes(start);

                e.Background[dev1] = new Epoch.EpochBackground(new Measurement(0, "V"), new Measurement(1000, "Hz"));
                e.Background[dev2] = new Epoch.EpochBackground(new Measurement(1, "V"), new Measurement(1000, "Hz"));

                e.Responses[dev1] = new Response();
                e.Responses[dev2] = new Response();

                var streamConfig = new Dictionary<string, object>();
                streamConfig[param1] = value1;

                var devConfig = new Dictionary<string, object>();
                devConfig[param2] = value2;

                IInputData responseData1 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream1, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev1, devConfig);
                IInputData responseData2 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream2, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev2, devConfig);

                e.Responses[dev1].AppendData(responseData1);
                e.Responses[dev2].AppendData(responseData2);

                e.Keywords.Add(kw1);
                e.Keywords.Add(kw2);

                exp.BeginEpochGroup("label", "source identifier", new[] {"keyword1", "keyword2"}, props, guid,
                                    time);

                exp.Serialize(e);

                exp.EndEpochGroup(time.AddMilliseconds(100));
                exp.Close();
            }

            H5.Close();

            var startInfo = new ProcessStartInfo(@"..\..\..\..\..\..\externals\HDF5\bin\h5dump",
                                                 @" --xml ..\..\..\ShouldAllowLongStringEpochParameters.h5");
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            Process proc = Process.Start(startInfo);

            Approvals.VerifyXml(proc.StandardOutput.ReadToEnd());
        }
Example #22
0
 /// <summary>
 /// Jenkins expresses all dates in a value typically named timestamp.  This seconds since the
 /// epoch.  This function will convert the Jenkins representation to a <see cref="DateTime"/>
 /// value.
 /// <returns></returns>
 public static DateTimeOffset ConvertTimestampToDateTimeOffset(long timestamp)
 {
     var epoch = new DateTimeOffset(year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0, offset: TimeSpan.Zero);
     return epoch.AddMilliseconds(timestamp);
 }
        /// <summary>
        /// Asserts that the current <see cref="DateTime"/> or <see cref="DateTimeOffset"/> is within the specified number of milliseconds (default = 20 ms)
        /// from the specified <paramref name="nearbyTime"/> value.
        /// </summary>
        /// <remarks>
        /// Use this assertion when, for example the database truncates datetimes to nearest 20ms. If you want to assert to the exact datetime,
        /// use <see cref="Be(DateTimeOffset, string, object[])"/>.
        /// </remarks>
        /// <param name="nearbyTime">
        /// The expected time to compare the actual value with.
        /// </param>
        /// <param name="precision">
        /// The maximum amount of milliseconds which the two values may differ.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion 
        /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
        /// </param>
        /// <param name="reasonArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public AndConstraint<DateTimeOffsetAssertions> BeCloseTo(DateTimeOffset nearbyTime, int precision = 20, string because = "",
            params object[] reasonArgs)
        {
            DateTimeOffset minimumValue = nearbyTime.AddMilliseconds(-precision);
            DateTimeOffset maximumValue = nearbyTime.AddMilliseconds(precision);

            Execute.Assertion
                .ForCondition(Subject.HasValue && (Subject.Value >= minimumValue) && (Subject.Value <= maximumValue))
                .BecauseOf(because, reasonArgs)
                .FailWith("Expected {context:date and time} to be within {0} ms from {1}{reason}, but found {2}.", precision,
                    nearbyTime, Subject.HasValue ? Subject.Value : default(DateTimeOffset?));

            return new AndConstraint<DateTimeOffsetAssertions>(this);
        }
		private static void AssertIsUnixEpocDateTimeOffset( DateTimeOffset actual, long millisecondsOffset )
		{
			Assert.That( actual.Offset, Is.EqualTo( TimeSpan.Zero ) );
			var epoc = new DateTimeOffset( 1970, 1, 1, 0, 0, 0, TimeSpan.Zero );
			Assert.That( actual, Is.EqualTo( epoc.AddMilliseconds( millisecondsOffset ) ) );
		}
Example #25
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");
     }
 }
Example #26
0
        public static void UpdatePrimaryTile(bool isBackgroundCall)
        {
            try
            {
                var updater = TileUpdateManager.CreateTileUpdaterForApplication();
                updater.EnableNotificationQueueForWide310x150(true);
                updater.EnableNotificationQueueForSquare150x150(true);
                updater.EnableNotificationQueueForSquare310x310(true);
                updater.EnableNotificationQueue(true);
                if (!isBackgroundCall)
                {
                    ToastTileManager.CancelUpdatePrimaryTile();
                }

                if (!UserSettings.IsTileOn) return;

                foreach (var card in CreditCardManager.GetInstance().GetAllCards())
                {
                    if (UserSettings.TileDay != UserSettings.All_The_Time && (card.LeftPayDays() < 0 || card.LeftPayDays() > UserSettings.TileDay)) continue;

                    var bank = card.Bank;
                    var dic = BankInfosReader.GetInstance().Dic;
                    var bankInfo = dic[bank.ToString()] as BankInfo;

                    var doc = new XmlDocument();

                    var delayThreeSeconds = DateTimeOffset.Now.AddSeconds(3);
                    var delayThreeSecondsTime = new DateTimeOffset(delayThreeSeconds.Year, delayThreeSeconds.Month, delayThreeSeconds.Day, delayThreeSeconds.Hour, delayThreeSeconds.Minute, delayThreeSeconds.Second, delayThreeSeconds.Offset);
                    var tomorrow = DateTimeOffset.Now.AddDays(1);
                    var delayToTomorrowTime = new DateTimeOffset(tomorrow.Year, tomorrow.Month, tomorrow.Day, 0, 0, 3, tomorrow.Offset);

                    var payDay = "";
                    if (isBackgroundCall)
                    {
                        payDay = card.LeftPayDays() == 1 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                    }
                    else
                    {
                        if (delayThreeSecondsTime.Day == DateTimeOffset.Now.Day)
                        {
                            payDay = card.LeftPayDays() == 0 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                        }
                        else
                        {
                            payDay = card.LeftPayDays() == 1 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                        }
                    }
                    var xml = string.Format(TileTemplateXml, bankInfo.Bank.ToString(), bankInfo.Title, payDay, card.CurrentFreeDays());
                    doc.LoadXml(xml);

                    var noti = isBackgroundCall ? new ScheduledTileNotification(doc, delayToTomorrowTime) : new ScheduledTileNotification(doc, delayThreeSecondsTime);
                    noti.ExpirationTime = isBackgroundCall ? delayToTomorrowTime.AddDays(1).AddMilliseconds(-3) : delayToTomorrowTime.AddMilliseconds(-3);
                    updater.AddToSchedule(noti);

                    //var bank = card.Bank;
                    //var dic = BankInfosReader.GetInstance().Dic;
                    //var bankInfo = dic[bank.ToString()] as BankInfo;

                    //var doc = new XmlDocument();
                    //var payDay = "";
                    //var scheduleTime = new DateTimeOffset();

                    //if (UserSettings.TileDay != UserSettings.All_The_Time && (card.LeftPayDays() < 0 || card.LeftPayDays() > UserSettings.TileDay))
                    //{
                    //    scheduleTime = DateTimeOffset.Now.AddDays(30);
                    //    payDay = card.CurrentPayDate().ToString("MM/dd");
                    //}
                    //else
                    //{
                    //    if (isBackgroundCall)
                    //    {
                    //        var tomorrow = DateTimeOffset.Now.AddDays(1);
                    //        scheduleTime = new DateTimeOffset(tomorrow.Year, tomorrow.Month, tomorrow.Day, 0, 0, 3, tomorrow.Offset);
                    //        payDay = card.LeftPayDays() == 1 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                    //    }
                    //    else
                    //    {
                    //        scheduleTime = DateTimeOffset.Now.AddSeconds(3);
                    //        if (scheduleTime.Day == DateTimeOffset.Now.Day)
                    //        {
                    //            payDay = card.LeftPayDays() == 0 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                    //        }
                    //        else
                    //        {
                    //            payDay = card.LeftPayDays() == 1 ? "今天" : card.CurrentPayDate().ToString("MM/dd");
                    //        }
                    //    }
                    //}

                    //var xml = string.Format(TileTemplateXml, bankInfo.Bank.ToString(), bankInfo.Title, payDay, card.CurrentFreeDays());
                    //doc.LoadXml(xml);

                    //var noti = new ScheduledTileNotification(doc, scheduleTime);
                    //noti.Tag = card.Bank.ToString() + card.NO;
                    //if (!isBackgroundCall)
                    //{
                    //    noti.Tag = "T" + noti.Tag;
                    //    var temp = DateTimeOffset.Now.AddDays(1);
                    //    var tomorrow = new DateTimeOffset(temp.Year, temp.Month, temp.Day, 0, 0, 3, temp.Offset);
                    //    noti.ExpirationTime = tomorrow;
                    //}
                    //updater.AddToSchedule(noti);
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
Example #27
0
 private bool Equal(DateTimeOffset x, DateTimeOffset y)
 {
     return y > x.AddMilliseconds(-10) && y < x.AddMilliseconds(10);
 }
        private static DateTimeOffset DateFromServerBytes(byte[] dateBytes)
        {
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(dateBytes, 0, 8);
            }
#if !DNXCORE50
            var referenceDate = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var unixTimeMilliseconds = BitConverter.ToInt64(dateBytes, 0);
            return referenceDate.AddMilliseconds(unixTimeMilliseconds);
#else
            return DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(dateBytes, 0));
#endif
        }
 public virtual DateTimeOffset GetNextCollectionTimeSlot(DateTimeOffset currentTime)
 {
     return currentTime.Millisecond < 500 ? currentTime.AddMilliseconds(500 - currentTime.Millisecond) : currentTime.AddSeconds(1).AddMilliseconds(500 - currentTime.Millisecond);
 }
Example #30
0
        public void TestReadDateTime()
        {
            var d = new DateTime(2014, 8, 9, 10, 6, 21, 497, DateTimeKind.Local);
            var expected = new DateTimeOffset(d).LocalDateTime;
            long javaTime = NForza.Transit.Java.Convert.ToJavaTime(d);

            string timeString = JsonParser.FormatDateTime(d);
            Assert.AreEqual(expected, Reader("\"~t" + timeString + "\"").Read<DateTime>());

            Assert.AreEqual(expected, Reader("{\"~#m\": " + javaTime + "}").Read<DateTime>());

            timeString = new DateTimeOffset(d).UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'");
            Assert.AreEqual(expected, Reader("\"~t" + timeString + "\"").Read<DateTime>());

            timeString = new DateTimeOffset(d).UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
            Assert.AreEqual(expected.AddMilliseconds(-497D), Reader("\"~t" + timeString + "\"").Read<DateTime>());

            timeString = new DateTimeOffset(d).UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff-00:00");
            Assert.AreEqual(expected, Reader("\"~t" + timeString + "\"").Read<DateTime>());
        }