Example #1
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);
    }
Example #2
0
        public void time_offset_excludes_values_of_exact_offset()
        {
            var stats = new StatsObserver <IList <int> >();

            var valueScheduler  = new ManualScheduler();
            var bufferScheduler = new ManualScheduler();

            DateTimeOffset startTime = DateTimeOffset.UtcNow;

            Observable.Range(0, 5, valueScheduler)
            .BufferWithTime(TimeSpan.FromMilliseconds(30), TimeSpan.FromMilliseconds(20), bufferScheduler)
            .Subscribe(stats);

            Assert.IsFalse(stats.NextCalled);

            bufferScheduler.Now = startTime.AddMilliseconds(10);
            valueScheduler.RunNext();

            bufferScheduler.Now = startTime.AddMilliseconds(20); // exact offset value
            valueScheduler.RunNext();

            bufferScheduler.Now = startTime.AddMilliseconds(30);
            valueScheduler.RunNext();

            bufferScheduler.RunNext();
            bufferScheduler.RunNext();

            Assert.AreEqual(2, stats.NextCount);
            Assert.AreEqual(1, stats.NextValues[1].Count);
        }
Example #3
0
        /// <summary>
        /// From long with 6 millisecond digits(YYYY-MM-DD HH:MM:SS[.uuuuuu].)
        /// </summary>
        public static DateTimeOffset FromBigQueryTimestamp(this long timestamp)
        {
            var seconds = Math.Round(((double)timestamp / 1000));
            var date    = unixEpochOffset.AddMilliseconds(seconds);

            return(date);
        }
Example #4
0
        private List <Tuple <QueuedTask, QueuedTaskResult> > GenerateUnprocessedTasks()
        {
            List <Tuple <QueuedTask, QueuedTaskResult> > unprocessedTasks =
                new List <Tuple <QueuedTask, QueuedTaskResult> >();

            for (int i = 0; i < mNumUnProcessedTasks; i++)
            {
                mLastPostedAt = mLastPostedAt.AddMilliseconds(100);
                QueuedTask task = new QueuedTask()
                {
                    Id            = Guid.NewGuid(),
                    Type          = typeof(SampleTaskPayload).FullName,
                    Payload       = new SampleTaskPayload(mNumUnProcessedTasks),
                    PostedAtTs    = mLastPostedAt,
                    Source        = GetType().FullName,
                    LockedUntilTs = mLastPostedAt,
                    Priority      = 0
                };

                unprocessedTasks.Add(new Tuple <QueuedTask, QueuedTaskResult>(
                                         task,
                                         new QueuedTaskResult(task)
                                         ));
            }

            return(unprocessedTasks);
        }
        public void ShouldMapSpanWithParentIntoValidJson()
        {
            var json = @"
                [
                  {
                    ""traceId"": ""6bebc46d026c79765d147587ca919c35"",
                    ""name"": ""op1"",
                    ""id"": ""9d346bce4bda362c"",
                    ""parentId"" : ""0000000000ab0d11"",
                    ""kind"": ""CLIENT"",
                    ""timestamp"": 1515784334000000,
                    ""duration"": 10000,
                    ""debug"": true,
                    ""localEndpoint"": {
                      ""serviceName"": ""actorsystem"",
                      ""ipv4"": ""127.0.0.1"",
                      ""ipv6"": ""127.0.0.1"",
                      ""port"": 8008
                    },
                    ""remoteEndpoint"": {
                      ""serviceName"": ""actorsystem"",
                      ""ipv4"": ""127.0.0.1"",
                      ""ipv6"": ""127.0.0.1"",
                      ""port"": 8009
                    },
                    ""annotations"": [
                      {
                        ""timestamp"": 1515784334001000,
                        ""value"": ""foo""
                      }
                    ],
                    ""tags"": {
                      ""foo1"": ""bar"",
                      ""numberOfPets"": ""2"",
                      ""timeInChair"": ""long""
                    }
                  }
                ]";

            var startTime     = new DateTimeOffset(new DateTime(2018, 1, 12, 13, 12, 14));
            var endTime       = startTime.AddMilliseconds(10);
            var expectedBytes = Encoding.UTF8.GetBytes(json);

            var parentId = 11210001.ToString("x16");

            var span = new Span(Tracer, "op1",
                                new SpanContext(new TraceId(7776525154056436086, 6707114971141086261),
                                                (-7118946577185884628).ToString("x16"),
                                                parentId,
                                                true),
                                startTime, SpanKind.CLIENT)
                       .SetRemoteEndpoint(new Endpoint("actorsystem", "127.0.0.1", 8009)).SetTag("foo1", "bar")
                       .SetTag("numberOfPets", 2)
                       .SetTag("timeInChair", "long").Log(startTime.AddMilliseconds(1), "foo");

            span.Finish(endTime);

            VerifySerialization(new JsonSpanSerializer(), expectedBytes, (Span)span, Assert);
        }
Example #6
0
        public static DateTimeOffset RoundToNearestSecond(this DateTimeOffset dt)
        {
            var ms = dt.Millisecond;

            return(ms < 500
                ? dt.AddMilliseconds(-ms)
                : dt.AddMilliseconds(1000 - ms));
        }
Example #7
0
        /// <summary>
        /// Calculates the offset date from the provided baseline for the specified interval
        /// </summary>
        /// <remarks>
        /// To calculate a backwards offset (the date that is the specified interval before the baseline) use a negative
        /// number of invervals. For example, -1 intervals will give you one interval before the baseline.
        /// </remarks>
        /// <param name="baseline">The date and time to calculate an offset date and time from</param>
        /// <param name="interval">The interval to add or subtract from the baseline</param>
        /// <param name="intervals">The number of intervals to go forward or (if negative) backwards</param>
        /// <returns></returns>
        private DateTimeOffset CalculateOffset(DateTimeOffset baseline, MetricSampleInterval interval, int intervals)
        {
            DateTimeOffset returnVal;  //just so we're initialized with SOMETHING.
            int            intervalCount = intervals;

            //since they aren't using shortest, we are going to use the intervals input option which better not be zero or negative.
            if ((intervals == 0) && (interval != MetricSampleInterval.Shortest))
            {
                throw new ArgumentOutOfRangeException(nameof(intervals), intervals, "The number of intervals can't be zero if the interval isn't set to Shortest.");
            }

            switch (interval)
            {
            case MetricSampleInterval.Default:     //use how the data was recorded
                //default and ours is default - use second.
                returnVal = CalculateOffset(baseline, MetricSampleInterval.Second, intervalCount);
                break;

            case MetricSampleInterval.Shortest:
                //exlicitly use the shortest value available, 16 milliseconds
                returnVal = baseline.AddMilliseconds(16);     //interval is ignored in the case of the "shortest" configuration
                break;

            case MetricSampleInterval.Millisecond:
                returnVal = baseline.AddMilliseconds(intervalCount);
                break;

            case MetricSampleInterval.Second:
                returnVal = baseline.AddSeconds(intervalCount);
                break;

            case MetricSampleInterval.Minute:
                returnVal = baseline.AddMinutes(intervalCount);
                break;

            case MetricSampleInterval.Hour:
                returnVal = baseline.AddHours(intervalCount);
                break;

            case MetricSampleInterval.Day:
                returnVal = baseline.AddDays(intervalCount);
                break;

            case MetricSampleInterval.Week:
                returnVal = baseline.AddDays(intervalCount * 7);
                break;

            case MetricSampleInterval.Month:
                returnVal = baseline.AddMonths(intervalCount);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(interval));
            }

            return(returnVal);
        }
Example #8
0
        protected void AssertAccessTime(DateTimeOffset?actual, DateTimeOffset expected)
        {
            Assert.That(actual, Is.Not.Null, "no time recorded");
            Assert.That(actual, Is.Not.EqualTo(DateTime.MinValue), "no time recorded");

            Assert.That(actual,
                        Is.GreaterThanOrEqualTo(expected.AddMilliseconds(-30)).And
                        .LessThanOrEqualTo(expected.AddMilliseconds(+30)),
                        "incorrect recording");
        }
        public void SetExpiration()
        {
            DateTimeOffset expiration = UnixEpoch.AddMilliseconds(35);
            Table          table      = new Table();

            Table modified = table.SetExpirationTime(expiration);

            Assert.Same(table, modified);
            Assert.Equal(35, modified.ExpirationTime);
        }
Example #10
0
        private static DateTimeOffset AddMilliseconds(DateTimeOffset dateTimeOffset, int milliseconds)
        {
            if (milliseconds < 0)
            {
                return(dateTimeOffset == DateTimeOffset.MinValue
                    ? dateTimeOffset
                    : dateTimeOffset.AddMilliseconds(milliseconds));
            }

            return(dateTimeOffset == DateTimeOffset.MaxValue
                ? dateTimeOffset
                : dateTimeOffset.AddMilliseconds(milliseconds));
        }
Example #11
0
        /// <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));
        }
        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 #13
0
        private IEnumerable <(DateTimeOffset From, DateTimeOffset To, double Value)> ExecuteFrames
            (DateTimeOffset from, DateTimeOffset to, double deposit)
        {
            var t      = (to - from).TotalMinutes;
            var d      = (int)t;
            var offset = (to - from).TotalMilliseconds / d;

            while (from < to)
            {
                yield return(ExecuteFrame(from, from.AddMilliseconds(offset), deposit / d));

                from = from.AddMilliseconds(offset);
            }
        }
Example #14
0
        public void TestGetFireTimeAfter()
        {
            SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();

            DateTimeOffset startTime = DateBuilder.EvenSecondDate(DateTime.UtcNow);

            simpleTrigger.StartTimeUtc   = startTime;
            simpleTrigger.RepeatInterval = TimeSpan.FromMilliseconds(10);
            simpleTrigger.RepeatCount    = 4;

            DateTimeOffset?fireTimeAfter;

            fireTimeAfter = simpleTrigger.GetFireTimeAfter(startTime.AddMilliseconds(34));
            Assert.AreEqual(startTime.AddMilliseconds(40), fireTimeAfter.Value);
        }
        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);
        }
        public void DateTimeOffset_MaxDateTimeOffset__Adding_MilliSeconds()
        {
            var list = new List <DateTimeOffset>();
            var baseTimeTwoMilliSecondsLater = BaseTime.AddMilliseconds(2);

            for (var i = 0; i < Assertion.Amount; i++)
            {
                list.Add(_dateTimeOffsetProvider.DateTimeOffset(baseTimeTwoMilliSecondsLater));
            }

            Assert.IsTrue(
                list.All(time => time < baseTimeTwoMilliSecondsLater),
                "list.All(time => time < baseTimeTwoMilliSecondsLater)"
                );
        }
Example #17
0
        /// <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>
        ///     Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        ///     The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = reader.Value.ToString();
            var t     = long.Parse(value);

            return(_epoch.AddMilliseconds(t));
        }
Example #19
0
        /// <summary>
        /// Adds using field to indicate which datetime field to add to.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        /// <param name="field">The field.</param>
        /// <param name="amount">The amount.</param>
        /// <returns></returns>
        public static DateTimeOffset AddUsingField(this DateTimeOffset dateTime, int field, int amount)
        {
            switch (field)
            {
            case DateTimeFieldEnum.MILLISEC:
                return(dateTime.AddMilliseconds(amount));

            case DateTimeFieldEnum.SECOND:
                return(dateTime.AddSeconds(amount));

            case DateTimeFieldEnum.MINUTE:
                return(dateTime.AddMinutes(amount));

            case DateTimeFieldEnum.HOUR_OF_DAY:
                return(dateTime.AddHours(amount));

            case DateTimeFieldEnum.DATE:
            case DateTimeFieldEnum.DAY_OF_MONTH:
                return(dateTime.AddDays(amount));

            case DateTimeFieldEnum.MONTH:
                return(dateTime.AddMonthsLikeJava(amount));

            case DateTimeFieldEnum.YEAR:
                return(dateTime.AddYears(amount));

            default:
                throw new ArgumentException("invalid datetime");
            }
        }
Example #20
0
        public void DateTimeOffsetAddMilliseconds()
        {
            DateTimeOffset offset = stored.AddMilliseconds(-1);

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddMilliseconds(x.Offset, -1) == offset);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddMilliseconds(x.Offset, -1) == offset);
#endif

            q.Should().NotBeEmpty();
        }
Example #21
0
        public List <Gyroscope> GatherGyroscopeData()
        {
            DateTimeOffset lastUpload = TimeKeeper.GetPreviousDone(UploadType.Gyroscope);

            // TODO use after
            return(_repoManager.GyroscopeRepository.GetRange(lastUpload.AddMilliseconds(1), DateTimeOffset.MaxValue).ToList());
        }
Example #22
0
        public void TestAcquireNextTrigger()
        {
            DateTimeOffset   d        = DateBuilder.EvenMinuteDateAfterNow();
            IOperableTrigger trigger1 = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(200), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger2 = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(50), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger3 = new SimpleTriggerImpl("trigger1", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddSeconds(100), d.AddSeconds(200), 2, TimeSpan.FromSeconds(2));

            trigger1.ComputeFirstFireTimeUtc(null);
            trigger2.ComputeFirstFireTimeUtc(null);
            trigger3.ComputeFirstFireTimeUtc(null);
            fJobStore.StoreTrigger(trigger1, false);
            fJobStore.StoreTrigger(trigger2, false);
            fJobStore.StoreTrigger(trigger3, false);

            DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value;

            Assert.AreEqual(0, fJobStore.AcquireNextTriggers(d.AddMilliseconds(10), 1, TimeSpan.Zero).Count);
            Assert.AreEqual(trigger2, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]);
            Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]);
            Assert.AreEqual(trigger1, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero)[0]);
            Assert.AreEqual(0, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.Zero).Count);


            // release trigger3
            fJobStore.ReleaseAcquiredTrigger(trigger3);
            Assert.AreEqual(trigger3, fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1))[0]);
        }
        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 #24
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTimeOffset dto;

            if (reader.Value is DateTime)
            {
                dto = new DateTimeOffset((DateTime)reader.Value);
            }
            else
            {
                var timestamp = (long)reader.Value;
                dto = Epoch.AddMilliseconds(timestamp);
            }

            if (objectType == typeof(DateTimeOffset))
            {
                return(dto);
            }

            if (objectType == typeof(DateTime))
            {
                return(dto.DateTime);
            }

            return(null);
        }
Example #25
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;
            }
        }
Example #26
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 #27
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Integer)
            {
                if (objectType == typeof(DateTimeOffset?) || objectType == typeof(DateTime?))
                {
                    return(null);
                }

                if (objectType == typeof(DateTimeOffset))
                {
                    return(default(DateTimeOffset));
                }

                return(default(DateTime));
            }

            var millisecondsSinceEpoch = Convert.ToDouble(reader.Value);
            var dateTimeOffset         = Epoch.AddMilliseconds(millisecondsSinceEpoch);

            if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
            {
                return(dateTimeOffset);
            }

            return(dateTimeOffset.DateTime);
        }
Example #28
0
        public IReadOnlyList <Activity> GetActivities(IObservable <Activity> observable)
        {
            var cancellationToken = new SafeCancellationTokenSource();
            var activityObserver  = new GitHubActivityObserver(_logger, cancellationToken, _lastObservation);

            observable.Subscribe(activityObserver, cancellationToken.Token);

            cancellationToken.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

            var observedActivities = activityObserver.ObservedActivities;

            if (observedActivities.Count > 0)
            {
                foreach (var observedActivity in observedActivities)
                {
                    if (observedActivity.CreatedAt > _lastObservation)
                    {
                        _lastObservation = observedActivity.CreatedAt;
                    }
                }

                _lastObservation = _lastObservation.AddMilliseconds(1);
            }

            return(activityObserver.ObservedActivities);
        }
Example #29
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 void Visit(TimestampType type)
            {
                TimestampArray.Builder resultBuilder = new TimestampArray.Builder().Reserve(_baseDataTotalElementCount);
                DateTimeOffset         basis         = DateTimeOffset.UtcNow;

                for (int i = 0; i < _baseDataListCount; i++)
                {
                    List <int?>            dataList = _baseData[i];
                    TimestampArray.Builder builder  = new TimestampArray.Builder().Reserve(dataList.Count);
                    foreach (int?value in dataList)
                    {
                        if (value.HasValue)
                        {
                            DateTimeOffset dateValue = basis.AddMilliseconds(value.Value);
                            builder.Append(dateValue);
                            resultBuilder.Append(dateValue);
                        }
                        else
                        {
                            builder.AppendNull();
                            resultBuilder.AppendNull();
                        }
                    }
                    TestTargetArrayList.Add(builder.Build());
                }

                ExpectedArray = resultBuilder.Build();
            }
Example #31
0
        public void InputDataConcats()
        {
            IDictionary <string, object> config = new Dictionary <string, object>(2);

            config["param1"] = 10;
            config["param2"] = 1;

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

            DateTimeOffset expectedTime = DateTimeOffset.UtcNow;

            IInputData inData1 = new InputData(this.Data,
                                               new Measurement(1000, "Hz"),
                                               expectedTime,
                                               new PipelineNodeConfiguration("test", config));

            IInputData inData2 = new InputData(this.Data,
                                               new Measurement(1000, "Hz"),
                                               expectedTime.AddMilliseconds(2),
                                               new PipelineNodeConfiguration("test", config));

            var concatData = new List <IMeasurement>(this.Data).Concat(this.Data).ToList();

            Assert.AreEqual(2 * this.Data.Count, concatData.Count());

            IInputData expected = new InputData(concatData,
                                                new Measurement(1000, "Hz"),
                                                expectedTime,
                                                new PipelineNodeConfiguration("test", config));

            var actual = inData1.Data.Concat(inData2.Data);

            Assert.AreEqual(expected.Data, actual);
            Assert.AreEqual(expected.SampleRate, inData1.SampleRate);
        }
        private async void StartCodeThrottle()
        {
            if (_codeChangePending)
            {
                return;
            }

            _codeChangePending = true;

            try
            {
                while (true)
                {
                    var now        = DateTimeOffset.Now;
                    var nextupdate = _lastChange.AddMilliseconds(CodeUpdateThrottleDelayMs);
                    if (now < nextupdate)
                    {
                        await Task.Delay(nextupdate - now);

                        continue;
                    }

                    await Update();

                    break;
                }
            }
            finally
            {
                _codeChangePending = false;
            }
        }
Example #33
0
            public bool CanTrigger()
            {
                bool @return;

                // Check if it's the default value.
                if (LastTrigger.Equals(DateTimeOffset.MinValue) || CooldownMilliseconds == 0)
                {   // Default value meaning we can trigger the bot.
                    @return = true;
                }
                else
                {   // It's something else, so let's check if we can trigger it.
                    DateTimeOffset dtoNow          = DateTimeOffset.Now;
                    DateTimeOffset dtoCooldownTime = LastTrigger.AddMilliseconds(CooldownMilliseconds);

                    // Check if we've gone beyond the cooldown time.
                    if (dtoNow.ToUnixTimeMilliseconds() >= dtoCooldownTime.ToUnixTimeMilliseconds())
                    {
                        @return = true;

                        LastTrigger = DateTimeOffset.MinValue;
                    }
                    else
                    {
                        @return = false;
                    }
                }

                return(@return);
            }
Example #34
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|ArgumentOutOfRangeException@mscorlib: '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 #36
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 #38
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));
    }
Example #40
0
 private static DateTimeOffset StripMiliseconds(DateTimeOffset date)
 {
     return date.AddMilliseconds(-date.Millisecond);
 }
Example #41
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");
     }
 }
        /// <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);
        }
        /// <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);
        }
        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 #45
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 #46
0
 private bool Equal(DateTimeOffset x, DateTimeOffset y)
 {
     return y > x.AddMilliseconds(-10) && y < x.AddMilliseconds(10);
 }
Example #47
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>());
        }
Example #48
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);
 }
        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());
        }
 public virtual DateTimeOffset GetNextCollectionTimeSlot(DateTimeOffset currentTime)
 {
     return currentTime.Millisecond < 500 ? currentTime.AddMilliseconds(500 - currentTime.Millisecond) : currentTime.AddSeconds(1).AddMilliseconds(500 - currentTime.Millisecond);
 }
        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;
        }
        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
        }
        /// <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;
        }
Example #54
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;
        }
		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 #56
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 static DateTimeOffset ConvertFromJsTimestamp(long timestamp)
 {
     DateTimeOffset origin = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, DateTimeOffset.Now.Offset);
     return origin.AddMilliseconds(timestamp);
 }
 /// <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);
 }
Example #59
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);
        }
Example #60
0
 public static void AddMilliseconds(DateTimeOffset dateTimeOffset, double milliseconds, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddMilliseconds(milliseconds));
 }