/// <summary>Reads the JSON representation of the object.</summary>
        /// <param name="reader">The <see cref="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>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // get epoch timestamp
            double timestamp;
            switch (reader.TokenType)
            {
                case JsonToken.Integer:
                case JsonToken.Float:
                    timestamp = (double)reader.Value;
                    break;

                case JsonToken.String:
                    try
                    {
                        timestamp = (double)Convert.ChangeType(reader.Value, typeof(double));
                    }
                    catch (FormatException ex)
                    {
                        throw new FormatException($"Can't parse string value '{reader.Value}' as a Unix timestamp.", ex);
                    }
                    break;

                default:
                    throw new Exception($"Can't parse '{reader.TokenType}' type as a Unix epoch timestamp, must be numeric.");
            }

            // convert to DateTime
            DateTimeOffset epoch = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero);
            return epoch.AddSeconds(timestamp);
        }
Esempio n. 2
0
        /// <summary>
        /// Создание всплывающего уведомления
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool CreateScheduledToast(int timestamp, int id, string message)
        {
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();
            var notifications = toastNotifier.GetScheduledToastNotifications();
            foreach (var notification in notifications)
            {
                if (notification.Id == id.ToString())
                    return false;
            }

            ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);

            XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
            toastTextElements[0].AppendChild(toastXml.CreateTextNode(AppConstants.AppMessages[AppConstants.UsedLanguage]["txtAppName"]));
            toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));

            XmlElement toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast"));
            toastElement.SetAttribute("launch", "note_id=" + id.ToString());

            DateTimeOffset schedule = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan());
            schedule = schedule.AddSeconds(timestamp).ToLocalTime();

            ScheduledToastNotification scheduledToast = new ScheduledToastNotification(toastXml, schedule);
            scheduledToast.Id = id.ToString();

            ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledToast);

            return true;
        }
        public static IEnumerable<Tuple<DateTimeOffset, decimal>> Parse(string data)
        {
            var lines = data.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries);

            var headers = new Dictionary<string, string>();

            int i;
            for (i = 0; i < lines.Length; i++)
            {
                int width = 1;
                var index = lines[i].IndexOf("=");
                if (index == -1)
                {
                    width = 3;
                    index = lines[i].IndexOf("%3D");
                }

                if (index == -1)
                {
                    break;
                }

                headers.Add(lines[i].Substring(0, index), lines[i].Substring(index + width));
            }

            var columns = headers["COLUMNS"]
                .Split(',')
                .Select((col, ix) => new { col, ix })
                .ToDictionary(e => e.col, e => e.ix);

            var interval = int.Parse(headers["INTERVAL"]);
            var tz = int.Parse(headers["TIMEZONE_OFFSET"]);
            var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromMinutes(tz));

            var reference = epoch;
            for (; i < lines.Length; i++)
            {
                var cols = lines[i].Split(',');

                var dateStr = cols[columns["DATE"]];
                var closeStr = cols[columns["CLOSE"]];

                int offset;
                if (dateStr.StartsWith("a"))
                {
                    reference = epoch.AddSeconds(int.Parse(dateStr.Substring(1)));
                    offset = 0;
                }
                else
                {
                    offset = int.Parse(dateStr);
                }

                var date = reference.AddSeconds(offset * interval);
                var close = decimal.Parse(closeStr);

                yield return Tuple.Create(date, close);
            }
        }
 /// <summary>
 /// A DateTimeOffset value is not tied to a particular time zone, but can originate from any of a variety of time zones. 
 /// Return assigned DateTime.
 /// </summary>
 /// <param name="ipAddress">Object of IPAddress.</param>
 /// <returns>Assigned DateTime</returns>
 public static DateTimeOffset? AssignedDateTime(this IPAddress ipAddress)
 {
     IPv4Data data = GetIPv4Data(ipAddress);
     if (data == null)
     {
         return null;
     }
     DateTimeOffset offset = new DateTimeOffset(0x7b2, 1, 1, 0, 0, 0, 0, new TimeSpan(0, 0, 0));
     return new DateTimeOffset?(offset.AddSeconds((double)data.Assigned));
 }
        public void QuickPulseCollectionTimeSlotManagerHandlesSecondHalfOfSecond()
        {
            // ARRANGE
            var manager = new QuickPulseCollectionTimeSlotManager();

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

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

            // ASSERT
            Assert.AreEqual(now.AddSeconds(1).AddMilliseconds(-1), slot);
        }
Esempio n. 6
0
        private static RateLimit ParseRateLimit(HttpResponseHeaders headers)
        {
            // Determine reset
            long resetInUnixTime = GetHeaderValue(headers, "x-ratelimit-reset");
            DateTimeOffset epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            DateTimeOffset reset = epoch.AddSeconds(resetInUnixTime);

            return new RateLimit
            {
                Limit = GetHeaderValue(headers, "x-ratelimit-limit"),
                Remaining = GetHeaderValue(headers, "x-ratelimit-remaining"),
                Reset = reset
            };
        }
Esempio n. 7
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));
    }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long ticks;

            if (!long.TryParse(reader.Value.ToString(), out ticks))
            {
                throw new Exception(
                    String.Format("Unexpected token parsing date. Expected Integer, got {0}.",
                    reader.TokenType));
            }

            var date = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            date = date.AddSeconds(ticks);

            return date;
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
        private List<Scrobble> GetTestScrobbles()
        {
            var counter = 0;
            var now = new DateTimeOffset(2012, 02, 29, 15, 40, 03, TimeSpan.Zero);
            Func<DateTimeOffset> getTimePlayed = () => now.AddSeconds(-360 * counter++);

            var testScrobbles = new List<Scrobble>
            {
                new Scrobble("65daysofstatic", "The Fall of Math", "Hole", getTimePlayed())
                {
                    ChosenByUser = true
                },
                new Scrobble("やくしまるえつこ", "X次元へようこそ", "X次元へようこそ", getTimePlayed())
                {
                    AlbumArtist = "やくしまるえつこ",
                    ChosenByUser = false
                },
                new Scrobble("Björk", "Hyperballad", "Post", getTimePlayed())
                {
                    AlbumArtist = "Björk",
                    ChosenByUser = false
                },
                new Scrobble("Broken Social Scene", "Sentimental X's", "Forgiveness Rock Record", getTimePlayed())
                {
                    AlbumArtist = "Broken Social Scene",
                    ChosenByUser = false
                },
                new Scrobble("Rubies", "Stand in a Line", "Teppan-Yaki (A Collection of Remixes)", getTimePlayed())
                {
                    AlbumArtist = "Schinichi Osawa",
                    ChosenByUser = false
                }
            };

            return testScrobbles;
        }
Esempio n. 12
0
 /// <summary>
 /// Datetime from an int representing a unix epoch time
 /// </summary>
 /// <param name="secondsSinceEpoch"></param>
 /// <returns></returns>
 public static DateTimeOffset EpochSecondsToDateTime(this int secondsSinceEpoch)
 {
     var date = new DateTimeOffset(1970, 1, 1,0,0,0,TimeSpan.Zero);
     return date.AddSeconds(secondsSinceEpoch);
 }
Esempio n. 13
0
        public async Task ProcessAsync_UsesExpiresSliding_ToExpireCacheEntryWithSlidingExpiration()
        {
            // Arrange - 1
            var currentTime = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var clock = new Mock<ISystemClock>();
            clock.SetupGet(p => p.UtcNow)
                 .Returns(() => currentTime);
            var cache = new MemoryCache(new MemoryCacheOptions { Clock = clock.Object });
            var tagHelperContext1 = GetTagHelperContext(id, childContent1);
            var tagHelperOutput1 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput1.PreContent.SetContent("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            currentTime = currentTime.AddSeconds(35);
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id, childContent2);
            var tagHelperOutput2 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
Esempio n. 14
0
        private static string SerializeEndOfDayMidnight(DateTimeOffset dateTimeOffset)
        {
            var previousDayJustBeforeMidnight = dateTimeOffset.AddSeconds(-1);

            return(previousDayJustBeforeMidnight.ToString(EndOfDayMidnightRoundtripFormat, CultureInfo.InvariantCulture));
        }
			static bool IsAlive(long connectionLifeTime, DateTimeOffset created, DateTimeOffset now)
			{
				if (connectionLifeTime == 0)
					return true;
				return created.AddSeconds(connectionLifeTime) > now;
			}
Esempio n. 16
0
        protected DateTimeOffset?GetFireTimeAfter(DateTimeOffset?afterTime, bool ignoreEndTime)
        {
            if (complete)
            {
                return(null);
            }

            // increment afterTme by a second, so that we are
            // comparing against a time after it!
            if (afterTime == null)
            {
                afterTime = SystemTime.UtcNow().AddSeconds(1);
            }
            else
            {
                afterTime = afterTime.Value.AddSeconds(1);
            }

            DateTimeOffset startMillis = StartTimeUtc;
            DateTimeOffset afterMillis = afterTime.Value;
            DateTimeOffset endMillis   = (EndTimeUtc == null) ? DateTimeOffset.MaxValue : EndTimeUtc.Value;

            if (!ignoreEndTime && (endMillis <= afterMillis))
            {
                return(null);
            }

            if (afterMillis < startMillis)
            {
                return(startMillis);
            }

            long secondsAfterStart = (long)(afterMillis - startMillis).TotalSeconds;

            DateTimeOffset?time       = null;
            long           repeatLong = RepeatInterval;

            DateTimeOffset?aTime = afterTime;

            DateTimeOffset sTime = StartTimeUtc;

            if (RepeatIntervalUnit == IntervalUnit.Second)
            {
                long jumpCount = secondsAfterStart / repeatLong;
                if (secondsAfterStart % repeatLong != 0)
                {
                    jumpCount++;
                }
                time = sTime.AddSeconds(RepeatInterval * (int)jumpCount);
            }
            else if (RepeatIntervalUnit == IntervalUnit.Minute)
            {
                long jumpCount = secondsAfterStart / (repeatLong * 60L);
                if (secondsAfterStart % (repeatLong * 60L) != 0)
                {
                    jumpCount++;
                }
                time = sTime.AddMinutes(RepeatInterval * (int)jumpCount);
            }
            else if (RepeatIntervalUnit == IntervalUnit.Hour)
            {
                long jumpCount = secondsAfterStart / (repeatLong * 60L * 60L);
                if (secondsAfterStart % (repeatLong * 60L * 60L) != 0)
                {
                    jumpCount++;
                }
                time = sTime.AddHours(RepeatInterval * (int)jumpCount);
            }
            else if (RepeatIntervalUnit == IntervalUnit.Day)
            {
                // Because intervals greater than an hour have an non-fixed number
                // of seconds in them (due to daylight savings, variation number of
                // days in each month, leap year, etc. ) we can't jump forward an
                // exact number of seconds to calculate the fire time as we can
                // with the second, minute and hour intervals.   But, rather
                // than slowly crawling our way there by iteratively adding the
                // increment to the start time until we reach the "after time",
                // we can first make a big leap most of the way there...

                long jumpCount = secondsAfterStart / (repeatLong * 24L * 60L * 60L);
                // if we need to make a big jump, jump most of the way there,
                // but not all the way because in some cases we may over-shoot or under-shoot
                if (jumpCount > 20)
                {
                    if (jumpCount < 50)
                    {
                        jumpCount = (long)(jumpCount * 0.80);
                    }
                    else if (jumpCount < 500)
                    {
                        jumpCount = (long)(jumpCount * 0.90);
                    }
                    else
                    {
                        jumpCount = (long)(jumpCount * 0.95);
                    }
                    sTime = sTime.AddDays(RepeatInterval * jumpCount);
                }

                // now baby-step the rest of the way there...
                while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt)
                {
                    sTime = sTime.AddDays(RepeatInterval);
                }
                time = sTime;
            }
            else if (RepeatIntervalUnit == IntervalUnit.Week)
            {
                // Because intervals greater than an hour have an non-fixed number
                // of seconds in them (due to daylight savings, variation number of
                // days in each month, leap year, etc. ) we can't jump forward an
                // exact number of seconds to calculate the fire time as we can
                // with the second, minute and hour intervals.   But, rather
                // than slowly crawling our way there by iteratively adding the
                // increment to the start time until we reach the "after time",
                // we can first make a big leap most of the way there...

                long jumpCount = secondsAfterStart / (repeatLong * 7L * 24L * 60L * 60L);
                // if we need to make a big jump, jump most of the way there,
                // but not all the way because in some cases we may over-shoot or under-shoot
                if (jumpCount > 20)
                {
                    if (jumpCount < 50)
                    {
                        jumpCount = (long)(jumpCount * 0.80);
                    }
                    else if (jumpCount < 500)
                    {
                        jumpCount = (long)(jumpCount * 0.90);
                    }
                    else
                    {
                        jumpCount = (long)(jumpCount * 0.95);
                    }
                    sTime = sTime.AddDays((int)(RepeatInterval * jumpCount * 7));
                }

                while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt)
                {
                    sTime = sTime.AddDays(RepeatInterval * 7);
                }
                time = sTime;
            }
            else if (RepeatIntervalUnit == IntervalUnit.Month)
            {
                // because of the large variation in size of months, and
                // because months are already large blocks of time, we will
                // just advance via brute-force iteration.
                while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt)
                {
                    sTime = sTime.AddMonths(RepeatInterval);
                }
                time = sTime;
            }
            else if (RepeatIntervalUnit == IntervalUnit.Year)
            {
                while (sTime < afterTime && sTime.Year < YearToGiveupSchedulingAt)
                {
                    sTime = sTime.AddYears(RepeatInterval);
                }
                time = sTime;
            }

            if (!ignoreEndTime && endMillis <= time)
            {
                return(null);
            }

            return(time);
        }
Esempio n. 17
0
 /// <summary>
 /// Returns a date that is rounded to the next even second above the given date.
 /// </summary>
 /// <param name="date"></param>
 /// the Date to round, if <see langword="null" /> the current time will
 /// be used
 /// <returns>the new rounded date</returns>
 public static DateTimeOffset EvenSecondDate(DateTimeOffset date)
 {
     date = date.AddSeconds(1);
     return new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0, date.Offset);
 }
Esempio n. 18
0
        public async Task TestAcquireNextTriggerBatch()
        {
            DateTimeOffset d = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromSeconds(1));

            IOperableTrigger early     = new SimpleTriggerImpl("early", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d, d.AddMilliseconds(5), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger1  = new SimpleTriggerImpl("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(200000), d.AddMilliseconds(200005), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger2  = new SimpleTriggerImpl("trigger2", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(210000), d.AddMilliseconds(210005), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger3  = new SimpleTriggerImpl("trigger3", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(220000), d.AddMilliseconds(220005), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger4  = new SimpleTriggerImpl("trigger4", "triggerGroup1", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(230000), d.AddMilliseconds(230005), 2, TimeSpan.FromSeconds(2));
            IOperableTrigger trigger10 = new SimpleTriggerImpl("trigger10", "triggerGroup2", fJobDetail.Name, fJobDetail.Group, d.AddMilliseconds(500000), d.AddMilliseconds(700000), 2, TimeSpan.FromSeconds(2));

            early.ComputeFirstFireTimeUtc(null);
            early.MisfireInstruction = MisfireInstruction.IgnoreMisfirePolicy;

            trigger1.ComputeFirstFireTimeUtc(null);
            trigger2.ComputeFirstFireTimeUtc(null);
            trigger3.ComputeFirstFireTimeUtc(null);
            trigger4.ComputeFirstFireTimeUtc(null);
            trigger10.ComputeFirstFireTimeUtc(null);
            await fJobStore.StoreTrigger(early, false);

            await fJobStore.StoreTrigger(trigger1, false);

            await fJobStore.StoreTrigger(trigger2, false);

            await fJobStore.StoreTrigger(trigger3, false);

            await fJobStore.StoreTrigger(trigger4, false);

            await fJobStore.StoreTrigger(trigger10, false);

            DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value;

            var acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 4, TimeSpan.FromSeconds(1));

            Assert.AreEqual(1, acquiredTriggers.Count);
            Assert.AreEqual(early.Key, acquiredTriggers[0].Key);
            await fJobStore.ReleaseAcquiredTrigger(early);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 4, TimeSpan.FromMilliseconds(205000));

            Assert.AreEqual(2, acquiredTriggers.Count);
            Assert.AreEqual(early.Key, acquiredTriggers[0].Key);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[1].Key);
            await fJobStore.ReleaseAcquiredTrigger(early);

            await fJobStore.ReleaseAcquiredTrigger(trigger1);

            await fJobStore.RemoveTrigger(early.Key);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 5, TimeSpan.FromMilliseconds(100000));

            Assert.AreEqual(4, acquiredTriggers.Count);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[0].Key);
            Assert.AreEqual(trigger2.Key, acquiredTriggers[1].Key);
            Assert.AreEqual(trigger3.Key, acquiredTriggers[2].Key);
            Assert.AreEqual(trigger4.Key, acquiredTriggers[3].Key);
            await fJobStore.ReleaseAcquiredTrigger(trigger1);

            await fJobStore.ReleaseAcquiredTrigger(trigger2);

            await fJobStore.ReleaseAcquiredTrigger(trigger3);

            await fJobStore.ReleaseAcquiredTrigger(trigger4);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 6, TimeSpan.FromMilliseconds(100000));

            Assert.AreEqual(4, acquiredTriggers.Count);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[0].Key);
            Assert.AreEqual(trigger2.Key, acquiredTriggers[1].Key);
            Assert.AreEqual(trigger3.Key, acquiredTriggers[2].Key);
            Assert.AreEqual(trigger4.Key, acquiredTriggers[3].Key);

            await fJobStore.ReleaseAcquiredTrigger(trigger1);

            await fJobStore.ReleaseAcquiredTrigger(trigger2);

            await fJobStore.ReleaseAcquiredTrigger(trigger3);

            await fJobStore.ReleaseAcquiredTrigger(trigger4);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(1), 5, TimeSpan.Zero);

            Assert.AreEqual(1, acquiredTriggers.Count);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[0].Key);

            await fJobStore.ReleaseAcquiredTrigger(trigger1);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(250), 5, TimeSpan.FromMilliseconds(19999L));

            Assert.AreEqual(2, acquiredTriggers.Count);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[0].Key);
            Assert.AreEqual(trigger2.Key, acquiredTriggers[1].Key);

            await fJobStore.ReleaseAcquiredTrigger(early);

            await fJobStore.ReleaseAcquiredTrigger(trigger1);

            await fJobStore.ReleaseAcquiredTrigger(trigger2);

            await fJobStore.ReleaseAcquiredTrigger(trigger3);

            acquiredTriggers = await fJobStore.AcquireNextTriggers(firstFireTime.AddMilliseconds(150), 5, TimeSpan.FromMilliseconds(5000L));

            Assert.AreEqual(1, acquiredTriggers.Count);
            Assert.AreEqual(trigger1.Key, acquiredTriggers[0].Key);
            await fJobStore.ReleaseAcquiredTrigger(trigger1);
        }
        public static void CheckTimeNested()
        {
            HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256;

            using (RSA rsa = RSA.Create(TestData.RsaBigExponentParams))
            {
                CertificateRequest request = new CertificateRequest("CN=Issuer", rsa, hashAlgorithm, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(true, false, 0, true));

                DateTimeOffset now       = DateTimeOffset.UtcNow;
                DateTimeOffset notBefore = now.AddMinutes(-10);
                DateTimeOffset notAfter  = now.AddMinutes(10);

                if (notAfter.Millisecond > 900)
                {
                    // We're only going to add 1, but let's be defensive.
                    notAfter -= TimeSpan.FromMilliseconds(200);
                }

                using (X509Certificate2 issuer = request.CreateSelfSigned(notBefore, notAfter))
                {
                    request = new CertificateRequest("CN=Leaf", rsa, hashAlgorithm, RSASignaturePadding.Pkcs1);
                    byte[] serial = { 3, 1, 4, 1, 5, 9 };

                    // Boundary case, exact match: Issue+Dispose
                    request.Create(issuer, notBefore, notAfter, serial).Dispose();

                    DateTimeOffset truncatedNotBefore = new DateTimeOffset(
                        notBefore.Year,
                        notBefore.Month,
                        notBefore.Day,
                        notBefore.Hour,
                        notBefore.Minute,
                        notBefore.Second,
                        notBefore.Offset);

                    // Boundary case, the notBefore rounded down: Issue+Dispose
                    request.Create(issuer, truncatedNotBefore, notAfter, serial).Dispose();

                    // Boundary case, the notAfter plus a millisecond, same second rounded down.
                    request.Create(issuer, notBefore, notAfter.AddMilliseconds(1), serial).Dispose();//);

                    // The notBefore value a whole second earlier:
                    AssertExtensions.Throws <ArgumentException>("notBefore", () =>
                    {
                        request.Create(issuer, notBefore.AddSeconds(-1), notAfter, serial).Dispose();
                    });

                    // The notAfter value bumped past the second mark:
                    DateTimeOffset tooLate = notAfter.AddMilliseconds(1000 - notAfter.Millisecond);
                    AssertExtensions.Throws <ArgumentException>("notAfter", () =>
                    {
                        request.Create(issuer, notBefore, tooLate, serial).Dispose();
                    });

                    // And ensure that both out of range isn't magically valid again
                    AssertExtensions.Throws <ArgumentException>("notBefore", () =>
                    {
                        request.Create(issuer, notBefore.AddDays(-1), notAfter.AddDays(1), serial).Dispose();
                    });
                }
            }
        }
        private void SetUserDetails(K8SConfiguration k8SConfig, Context activeContext)
        {
            if (string.IsNullOrWhiteSpace(activeContext.ContextDetails.User))
            {
                return;
            }

            var userDetails = k8SConfig.Users.FirstOrDefault(c => c.Name.Equals(activeContext.ContextDetails.User,
                                                                                StringComparison.OrdinalIgnoreCase));

            if (userDetails == null)
            {
                throw new KubeConfigException($"User not found for context {activeContext.Name} in kubeconfig");
            }

            if (userDetails.UserCredentials == null)
            {
                throw new KubeConfigException($"User credentials not found for user: {userDetails.Name} in kubeconfig");
            }

            var userCredentialsFound = false;

            // Basic and bearer tokens are mutually exclusive
            if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.Token))
            {
                AccessToken          = userDetails.UserCredentials.Token;
                userCredentialsFound = true;
            }
            else if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.UserName) &&
                     !string.IsNullOrWhiteSpace(userDetails.UserCredentials.Password))
            {
                Username             = userDetails.UserCredentials.UserName;
                Password             = userDetails.UserCredentials.Password;
                userCredentialsFound = true;
            }

            // Token and cert based auth can co-exist
            if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientCertificateData) &&
                !string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientKeyData))
            {
                ClientCertificateData    = userDetails.UserCredentials.ClientCertificateData;
                ClientCertificateKeyData = userDetails.UserCredentials.ClientKeyData;
                userCredentialsFound     = true;
            }

            if (!string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientCertificate) &&
                !string.IsNullOrWhiteSpace(userDetails.UserCredentials.ClientKey))
            {
                ClientCertificateFilePath = GetFullPath(k8SConfig, userDetails.UserCredentials.ClientCertificate);
                ClientKeyFilePath         = GetFullPath(k8SConfig, userDetails.UserCredentials.ClientKey);
                userCredentialsFound      = true;
            }

            if (userDetails.UserCredentials.AuthProvider != null)
            {
                if (userDetails.UserCredentials.AuthProvider.Config != null &&
                    userDetails.UserCredentials.AuthProvider.Config.ContainsKey("access-token"))
                {
                    switch (userDetails.UserCredentials.AuthProvider.Name)
                    {
                    case "azure":
                    {
                        var config = userDetails.UserCredentials.AuthProvider.Config;
                        if (config.ContainsKey("expires-on"))
                        {
                            var            expiresOn = Int32.Parse(config["expires-on"]);
                            DateTimeOffset expires;
#if NET452
                            var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
                            expires
                                = epoch.AddSeconds(expiresOn);
#else
                            expires = DateTimeOffset.FromUnixTimeSeconds(expiresOn);
#endif

                            if (DateTimeOffset.Compare(expires
                                                       , DateTimeOffset.Now)
                                <= 0)
                            {
                                var tenantId    = config["tenant-id"];
                                var clientId    = config["client-id"];
                                var apiServerId = config["apiserver-id"];
                                var refresh     = config["refresh-token"];
                                var newToken    = RenewAzureToken(tenantId
                                                                  , clientId
                                                                  , apiServerId
                                                                  , refresh);
                                config["access-token"] = newToken;
                            }
                        }

                        AccessToken          = config["access-token"];
                        userCredentialsFound = true;
                        break;
                    }

                    case "gcp":
                    {
                        var          config    = userDetails.UserCredentials.AuthProvider.Config;
                        const string keyExpire = "expiry";
                        if (config.ContainsKey(keyExpire))
                        {
                            if (DateTimeOffset.TryParse(config[keyExpire]
                                                        , out DateTimeOffset expires))
                            {
                                if (DateTimeOffset.Compare(expires
                                                           , DateTimeOffset.Now)
                                    <= 0)
                                {
                                    throw new KubeConfigException("Refresh not supported.");
                                }
                            }
                        }

                        AccessToken          = config["access-token"];
                        userCredentialsFound = true;
                        break;
                    }
                    }
                }
            }

#if NETSTANDARD2_0
            if (userDetails.UserCredentials.ExternalExecution != null)
            {
                if (string.IsNullOrWhiteSpace(userDetails.UserCredentials.ExternalExecution.Command))
                {
                    throw new KubeConfigException(
                              "External command execution to receive user credentials must include a command to execute");
                }

                if (string.IsNullOrWhiteSpace(userDetails.UserCredentials.ExternalExecution.ApiVersion))
                {
                    throw new KubeConfigException("External command execution missing ApiVersion key");
                }

                var token = ExecuteExternalCommand(userDetails.UserCredentials.ExternalExecution);
                AccessToken = token;

                userCredentialsFound = true;
            }
#endif

            if (!userCredentialsFound)
            {
                throw new KubeConfigException(
                          $"User: {userDetails.Name} does not have appropriate auth credentials in kubeconfig");
            }
        }
Esempio n. 21
0
 public static DateTime DateTimeFromUnix(UInt64 unix_seconds)
 {
     return(UnixEpoch.AddSeconds(unix_seconds).ToLocalTime().DateTime);
 }
Esempio n. 22
0
 public DateTimeOffset GetTime()
 {
     _prev = _prev?.AddSeconds(1) ?? DateTimeOffset.UtcNow;
     return(_prev.Value);
 }
        private Span CreateTestSpan()
        {
            var startTimestamp = new DateTimeOffset(2019, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var endTimestamp   = startTimestamp.AddSeconds(60);
            var eventTimestamp = new DateTimeOffset(2019, 1, 1, 0, 0, 0, TimeSpan.Zero);

            var traceId      = ActivityTraceId.CreateFromString("e8ea7e9ac72de94e91fabc613f9686b2".AsSpan());
            var spanId       = "6a69db47429ea340";
            var parentSpanId = ActivitySpanId.CreateFromBytes(new byte[] { 12, 23, 34, 45, 56, 67, 78, 89 });
            var attributes   = new Dictionary <string, object>
            {
                { "stringKey", "value" },
                { "longKey", 1L },
                { "longKey2", 1 },
                { "doubleKey", 1D },
                { "doubleKey2", 1F },
                { "boolKey", true },
            };
            var events = new List <Event>
            {
                new Event(
                    "Event1",
                    eventTimestamp,
                    new Dictionary <string, object>
                {
                    { "key", "value" },
                }
                    ),
                new Event(
                    "Event2",
                    eventTimestamp,
                    new Dictionary <string, object>
                {
                    { "key", "value" },
                }
                    ),
            };

            var linkedSpanId = ActivitySpanId.CreateFromString("888915b6286b9c41".AsSpan());

            var link = new Link(new SpanContext(
                                    traceId,
                                    linkedSpanId,
                                    ActivityTraceFlags.Recorded));

            var span = (Span)tracer
                       .StartSpan("Name", new SpanContext(traceId, parentSpanId, ActivityTraceFlags.Recorded), SpanKind.Client,
                                  new SpanCreationOptions
            {
                StartTimestamp = startTimestamp,
                Links          = new[] { link },
            });

            var spanContextSetter = typeof(Span).GetMethod("set_Context", BindingFlags.Instance | BindingFlags.NonPublic);

            spanContextSetter.Invoke(span, new [] { new SpanContext(traceId, ActivitySpanId.CreateFromString(spanId.AsSpan()), ActivityTraceFlags.Recorded) });

            foreach (var attribute in attributes)
            {
                span.SetAttribute(attribute);
            }

            foreach (var evnt in events)
            {
                span.AddEvent(evnt);
            }

            span.Status = Status.Ok;

            span.End(endTimestamp);
            return(span);
        }
Esempio n. 24
0
 /// <summary>
 /// Converts a UNIX timestamp to a DateTimeOffset.
 /// </summary>
 static public DateTimeOffset UnixToDateTime(int unix)
 {
     return(Epoch.AddSeconds(unix));
 }
Esempio n. 25
0
 /// <summary>
 /// Returns a date that is rounded to the next even second above the given date.
 /// </summary>
 /// <param name="date"></param>
 /// the Date to round, if <see langword="null" /> the current time will
 /// be used
 /// <returns>the new rounded date</returns>
 public static DateTimeOffset EvenSecondDate(DateTimeOffset date)
 {
     date = date.AddSeconds(1);
     return(new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0, date.Offset));
 }
Esempio n. 26
0
        /// <summary>
        /// Gets the next fire time after the given time.
        /// </summary>
        /// <param name="afterTimeUtc">The UTC time to start searching from.</param>
        /// <returns></returns>
        public virtual DateTimeOffset? GetTimeAfter(DateTimeOffset afterTimeUtc)
        {
            // move ahead one second, since we're computing the time *after* the
            // given time
            afterTimeUtc = afterTimeUtc.AddSeconds(1);

            // CronTrigger does not deal with milliseconds
            DateTimeOffset d = CreateDateTimeWithoutMillis(afterTimeUtc);

            // change to specified time zone
            d = TimeZoneUtil.ConvertTime(d, TimeZone);

            bool gotOne = false;
            // loop until we've computed the next time, or we've past the endTime
            while (!gotOne)
            {
                ISortedSet<int> st;
                int t;
                int sec = d.Second;

                // get second.................................................
                st = seconds.TailSet(sec);
                if (st != null && st.Count != 0)
                {
                    sec = st.First();
                }
                else
                {
                    sec = seconds.First();
                    d = d.AddMinutes(1);
                }
                d = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, sec, d.Millisecond, d.Offset);

                int min = d.Minute;
                int hr = d.Hour;
                t = -1;

                // get minute.................................................
                st = minutes.TailSet(min);
                if (st != null && st.Count != 0)
                {
                    t = min;
                    min = st.First();
                }
                else
                {
                    min = minutes.First();
                    hr++;
                }
                if (min != t)
                {
                    d = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, min, 0, d.Millisecond, d.Offset);
                    d = SetCalendarHour(d, hr);
                    continue;
                }
                d = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, min, d.Second, d.Millisecond, d.Offset);

                hr = d.Hour;
                int day = d.Day;
                t = -1;

                // get hour...................................................
                st = hours.TailSet(hr);
                if (st != null && st.Count != 0)
                {
                    t = hr;
                    hr = st.First();
                }
                else
                {
                    hr = hours.First();
                    day++;
                }
                if (hr != t)
                {
                    int daysInMonth = DateTime.DaysInMonth(d.Year, d.Month);
                    if (day > daysInMonth)
                    {
                        d = new DateTimeOffset(d.Year, d.Month, daysInMonth, d.Hour, 0, 0, d.Millisecond, d.Offset).AddDays(day - daysInMonth);
                    }
                    else
                    {
                        d = new DateTimeOffset(d.Year, d.Month, day, d.Hour, 0, 0, d.Millisecond, d.Offset);
                    }
                    d = SetCalendarHour(d, hr);
                    continue;
                }
                d = new DateTimeOffset(d.Year, d.Month, d.Day, hr, d.Minute, d.Second, d.Millisecond, d.Offset);

                day = d.Day;
                int mon = d.Month;
                t = -1;
                int tmon = mon;

                // get day...................................................
                bool dayOfMSpec = !daysOfMonth.Contains(NoSpec);
                bool dayOfWSpec = !daysOfWeek.Contains(NoSpec);
                if (dayOfMSpec && !dayOfWSpec)
                {
                    // get day by day of month rule
                    st = daysOfMonth.TailSet(day);
                    if (lastdayOfMonth)
                    {
                        if (!nearestWeekday)
                        {
                            t = day;
                            day = GetLastDayOfMonth(mon, d.Year);
                            day -= lastdayOffset;

                            if (t > day)
                            {
                                mon++;
                                if (mon > 12)
                                {
                                    mon = 1;
                                    tmon = 3333; // ensure test of mon != tmon further below fails
                                    d.AddYears(1);
                                }
                                day = 1;
                            }
                        }
                        else
                        {
                            t = day;
                            day = GetLastDayOfMonth(mon, d.Year);
                            day -= lastdayOffset;

                            DateTimeOffset tcal = new DateTimeOffset(d.Year, mon, day, 0, 0, 0, d.Offset);

                            int ldom = GetLastDayOfMonth(mon, d.Year);
                            DayOfWeek dow = tcal.DayOfWeek;

                            if (dow == System.DayOfWeek.Saturday && day == 1)
                            {
                                day += 2;
                            }
                            else if (dow == System.DayOfWeek.Saturday)
                            {
                                day -= 1;
                            }
                            else if (dow == System.DayOfWeek.Sunday && day == ldom)
                            {
                                day -= 2;
                            }
                            else if (dow == System.DayOfWeek.Sunday)
                            {
                                day += 1;
                            }

                            DateTimeOffset nTime = new DateTimeOffset(tcal.Year, mon, day, hr, min, sec, d.Millisecond, d.Offset);
                            if (nTime.ToUniversalTime() < afterTimeUtc)
                            {
                                day = 1;
                                mon++;
                            }
                        }
                    }
                    else if (nearestWeekday)
                    {
                        t = day;
                        day = daysOfMonth.First();

                        DateTimeOffset tcal = new DateTimeOffset(d.Year, mon, day, 0, 0, 0, d.Offset);

                        int ldom = GetLastDayOfMonth(mon, d.Year);
                        DayOfWeek dow = tcal.DayOfWeek;

                        if (dow == System.DayOfWeek.Saturday && day == 1)
                        {
                            day += 2;
                        }
                        else if (dow == System.DayOfWeek.Saturday)
                        {
                            day -= 1;
                        }
                        else if (dow == System.DayOfWeek.Sunday && day == ldom)
                        {
                            day -= 2;
                        }
                        else if (dow == System.DayOfWeek.Sunday)
                        {
                            day += 1;
                        }

                        tcal = new DateTimeOffset(tcal.Year, mon, day, hr, min, sec, d.Offset);
                        if (tcal.ToUniversalTime() < afterTimeUtc)
                        {
                            day = daysOfMonth.First();
                            mon++;
                        }
                    }
                    else if (st != null && st.Count != 0)
                    {
                        t = day;
                        day = st.First();

                        // make sure we don't over-run a short month, such as february
                        int lastDay = GetLastDayOfMonth(mon, d.Year);
                        if (day > lastDay)
                        {
                            day = daysOfMonth.First();
                            mon++;
                        }
                    }
                    else
                    {
                        day = daysOfMonth.First();
                        mon++;
                    }

                    if (day != t || mon != tmon)
                    {
                        if (mon > 12)
                        {
                            d = new DateTimeOffset(d.Year, 12, day, 0, 0, 0, d.Offset).AddMonths(mon - 12);
                        }
                        else
                        {
                            // This is to avoid a bug when moving from a month
                            //with 30 or 31 days to a month with less. Causes an invalid datetime to be instantiated.
                            // ex. 0 29 0 30 1 ? 2009 with clock set to 1/30/2009
                            int lDay = DateTime.DaysInMonth(d.Year, mon);
                            if (day <= lDay)
                            {
                                d = new DateTimeOffset(d.Year, mon, day, 0, 0, 0, d.Offset);
                            }
                            else
                            {
                                d = new DateTimeOffset(d.Year, mon, lDay, 0, 0, 0, d.Offset).AddDays(day - lDay);
                            }
                        }
                        continue;
                    }
                }
                else if (dayOfWSpec && !dayOfMSpec)
                {
                    // get day by day of week rule
                    if (lastdayOfWeek)
                    {
                        // are we looking for the last XXX day of
                        // the month?
                        int dow = daysOfWeek.First(); // desired
                        // d-o-w
                        int cDow = ((int) d.DayOfWeek) + 1; // current d-o-w
                        int daysToAdd = 0;
                        if (cDow < dow)
                        {
                            daysToAdd = dow - cDow;
                        }
                        if (cDow > dow)
                        {
                            daysToAdd = dow + (7 - cDow);
                        }

                        int lDay = GetLastDayOfMonth(mon, d.Year);

                        if (day + daysToAdd > lDay)
                        {
                            // did we already miss the
                            // last one?
                            if (mon == 12)
                            {
                                //will we pass the end of the year?
                                d = new DateTimeOffset(d.Year, mon - 11, 1, 0, 0, 0, d.Offset).AddYears(1);
                            }
                            else
                            {
                                d = new DateTimeOffset(d.Year, mon + 1, 1, 0, 0, 0, d.Offset);
                            }
                            // we are promoting the month
                            continue;
                        }

                        // find date of last occurrence of this day in this month...
                        while ((day + daysToAdd + 7) <= lDay)
                        {
                            daysToAdd += 7;
                        }

                        day += daysToAdd;

                        if (daysToAdd > 0)
                        {
                            d = new DateTimeOffset(d.Year, mon, day, 0, 0, 0, d.Offset);
                            // we are not promoting the month
                            continue;
                        }
                    }
                    else if (nthdayOfWeek != 0)
                    {
                        // are we looking for the Nth XXX day in the month?
                        int dow = daysOfWeek.First(); // desired
                        // d-o-w
                        int cDow = ((int) d.DayOfWeek) + 1; // current d-o-w
                        int daysToAdd = 0;
                        if (cDow < dow)
                        {
                            daysToAdd = dow - cDow;
                        }
                        else if (cDow > dow)
                        {
                            daysToAdd = dow + (7 - cDow);
                        }

                        bool dayShifted = false;
                        if (daysToAdd > 0)
                        {
                            dayShifted = true;
                        }

                        day += daysToAdd;
                        int weekOfMonth = day/7;
                        if (day%7 > 0)
                        {
                            weekOfMonth++;
                        }

                        daysToAdd = (nthdayOfWeek - weekOfMonth)*7;
                        day += daysToAdd;
                        if (daysToAdd < 0 || day > GetLastDayOfMonth(mon, d.Year))
                        {
                            if (mon == 12)
                            {
                                d = new DateTimeOffset(d.Year, mon - 11, 1, 0, 0, 0, d.Offset).AddYears(1);
                            }
                            else
                            {
                                d = new DateTimeOffset(d.Year, mon + 1, 1, 0, 0, 0, d.Offset);
                            }

                            // we are promoting the month
                            continue;
                        }
                        else if (daysToAdd > 0 || dayShifted)
                        {
                            d = new DateTimeOffset(d.Year, mon, day, 0, 0, 0, d.Offset);
                            // we are NOT promoting the month
                            continue;
                        }
                    }
                    else
                    {
                        int cDow = ((int) d.DayOfWeek) + 1; // current d-o-w
                        int dow = daysOfWeek.First(); // desired
                        // d-o-w
                        st = daysOfWeek.TailSet(cDow);
                        if (st != null && st.Count > 0)
                        {
                            dow = st.First();
                        }

                        int daysToAdd = 0;
                        if (cDow < dow)
                        {
                            daysToAdd = dow - cDow;
                        }
                        if (cDow > dow)
                        {
                            daysToAdd = dow + (7 - cDow);
                        }

                        int lDay = GetLastDayOfMonth(mon, d.Year);

                        if (day + daysToAdd > lDay)
                        {
                            // will we pass the end of the month?

                            if (mon == 12)
                            {
                                //will we pass the end of the year?
                                d = new DateTimeOffset(d.Year, mon - 11, 1, 0, 0, 0, d.Offset).AddYears(1);
                            }
                            else
                            {
                                d = new DateTimeOffset(d.Year, mon + 1, 1, 0, 0, 0, d.Offset);
                            }
                            // we are promoting the month
                            continue;
                        }
                        else if (daysToAdd > 0)
                        {
                            // are we swithing days?
                            d = new DateTimeOffset(d.Year, mon, day + daysToAdd, 0, 0, 0, d.Offset);
                            continue;
                        }
                    }
                }
                else
                {
                    // dayOfWSpec && !dayOfMSpec
                    throw new Exception(
                        "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.");
                }

                d = new DateTimeOffset(d.Year, d.Month, day, d.Hour, d.Minute, d.Second, d.Offset);
                mon = d.Month;
                int year = d.Year;
                t = -1;

                // test for expressions that never generate a valid fire date,
                // but keep looping...
                if (year > MaxYear)
                {
                    return null;
                }

                // get month...................................................
                st = months.TailSet((mon));
                if (st != null && st.Count != 0)
                {
                    t = mon;
                    mon = st.First();
                }
                else
                {
                    mon = months.First();
                    year++;
                }
                if (mon != t)
                {
                    d = new DateTimeOffset(year, mon, 1, 0, 0, 0, d.Offset);
                    continue;
                }
                d = new DateTimeOffset(d.Year, mon, d.Day, d.Hour, d.Minute, d.Second, d.Offset);
                year = d.Year;
                t = -1;

                // get year...................................................
                st = years.TailSet((year));
                if (st != null && st.Count != 0)
                {
                    t = year;
                    year = st.First();
                }
                else
                {
                    return null;
                } // ran out of years...

                if (year != t)
                {
                    d = new DateTimeOffset(year, 1, 1, 0, 0, 0, d.Offset);
                    continue;
                }
                d = new DateTimeOffset(year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Offset);

                gotOne = true;
            } // while( !done )

            return d.ToUniversalTime();
        }
Esempio n. 27
0
        /// <summary>
        /// Converts Unix Time (seconds since January 1, 1970 UTC) to a DateTimeOffset object.
        /// </summary>
        /// <param name="secondsSince">
        /// Seconds since January 1, 1970.
        /// </param>
        /// <returns>
        /// <see cref="DateTime"/> representing the given Unix time.
        /// </returns>
        public static DateTimeOffset ToDateTimeOffset(this int secondsSince)
        {
            var converted = BaseUnixTime.AddSeconds(secondsSince);

            return(converted);
        }
        public ReceivePackCommitSignature ParseSignature(string commitHeaderData)
        {
            // Find the start and end markers of the email address.
            var emailStart = commitHeaderData.IndexOf('<');
            var emailEnd = commitHeaderData.IndexOf('>');

            // Leave out the trailing space.
            var nameLength = emailStart - 1;

            // Leave out the starting bracket.
            var emailLength = emailEnd - emailStart - 1;

            // Parse the name and email values.
            var name = commitHeaderData.Substring(0, nameLength);
            var email = commitHeaderData.Substring(emailStart + 1, emailLength);

            // The rest of the string is the timestamp, it may include a timezone.
            var timestampString = commitHeaderData.Substring(emailEnd + 2);
            var timestampComponents = timestampString.Split(' ');

            // Start with epoch in UTC, add the timestamp seconds.
            var timestamp = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            timestamp = timestamp.AddSeconds(long.Parse(timestampComponents[0]));

            return new ReceivePackCommitSignature(name, email, timestamp);
        }
Esempio n. 29
0
        private static DateTimeOffset FromUnixTime(long unixTime)
        {
            var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan(0000));

            return(epoch.AddSeconds(unixTime));
        }
Esempio n. 30
0
        static DateTimeOffset?ToDateTimeOffset(string value, string format, string timeZone, bool generic = true)
        {
            try
            {
                if (format == Unix)
                {
                    double seconds;
                    if (!double.TryParse(value, out seconds))
                    {
                        return(null);
                    }
                    return(epoch.AddSeconds(seconds));
                }

                if (format == FileTime)
                {
                    long fileTimeLong;
                    if (!long.TryParse(value, out fileTimeLong))
                    {
                        return(null);
                    }
                    return(DateTimeOffset.FromFileTime(fileTimeLong));
                }

                if (format == Excel)
                {
                    double days;
                    if (!double.TryParse(value, out days))
                    {
                        return(null);
                    }
                    return(SetTimeZone(excelBase.AddDays(days + (days < 61 ? 1 : 0) - 2), timeZone));
                }

                if (format == Ticks)
                {
                    long ticks;
                    if (!long.TryParse(value, out ticks))
                    {
                        return(null);
                    }
                    return(SetTimeZone(new DateTimeOffset(ticks, TimeSpan.Zero), timeZone));
                }

                DateTimeOffset dateTime;
                if (DateTimeOffset.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.RoundtripKind, out dateTime))
                {
                    DateTime dateTimeValue;
                    if ((DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.RoundtripKind, out dateTimeValue)) && (dateTimeValue.Kind == DateTimeKind.Unspecified))
                    {
                        dateTime = SetTimeZone(dateTime, timeZone);
                    }

                    return(dateTime);
                }

                if (generic)
                {
                    if (DateTimeOffset.TryParse(value, out dateTime))
                    {
                        DateTime dateTimeValue;
                        if ((DateTime.TryParse(value, out dateTimeValue)) && (dateTimeValue.Kind == DateTimeKind.Unspecified))
                        {
                            dateTime = SetTimeZone(dateTime, timeZone);
                        }

                        return(dateTime);
                    }
                }
            }
            catch { }
            return(null);
        }
Esempio n. 31
0
        // TODO duplicate params similar to GetPoints
        // TODO call other get labels
        public static (List <string> XAxisLabels, List <string> YAxisLabels) GetLabels(Dictionary <DateTime, int> data, int columns, int rows, bool yZeroIndexed = true, DateTime?minDate = null, DateTime?maxDate = null, string suffix = "")
        {
            if (columns < 1)
            {
                columns = 1;
            }

            if (rows < 1)
            {
                rows = 1;
            }

            // dupe code from GetPoints
            DateTime firstDateTime = minDate ?? data.First().Key;
            DateTime lastDateTime  = maxDate ?? data.Last().Key;

            long totalSec = (long)(lastDateTime - firstDateTime).TotalSeconds; // sec granularity
            int  minVal   = int.MaxValue;
            int  maxVal   = int.MinValue;

            foreach (var item in data)
            {
                if (item.Value < minVal)
                {
                    minVal = item.Value;
                }
                if (item.Value > maxVal)
                {
                    maxVal = item.Value;
                }
            }

            if (yZeroIndexed)
            {
                minVal = 0;
            }
            // dupe code end -> add generic class TODO

            // X AXIS
            long intervalColumn = totalSec / columns;

            List <string>  xAxisLabels = new List <string>();
            DateTimeOffset currentDate = firstDateTime;

            xAxisLabels.Add(currentDate.ToString("dd.MM.yy HH:mm"));

            for (int i = 0; i < columns; i++)
            {
                currentDate = currentDate.AddSeconds(intervalColumn);
                xAxisLabels.Add(currentDate.ToString("dd.MM.yy HH:mm"));
            }


            // Y AXIS
            int intervalRow = (maxVal - minVal) / rows;

            int currentValue = minVal;

            List <string> yAxisLabels = new List <string>();

            yAxisLabels.Add(currentValue.ToString());

            for (int i = 0; i < rows; i++)
            {
                currentValue += intervalRow;
                yAxisLabels.Add(currentValue.ToString() + suffix);
            }

            return(xAxisLabels, yAxisLabels);
        }
 public virtual DateTimeOffset GetNextCollectionTimeSlot(DateTimeOffset currentTime)
 {
     return currentTime.Millisecond < 500 ? currentTime.AddMilliseconds(500 - currentTime.Millisecond) : currentTime.AddSeconds(1).AddMilliseconds(500 - currentTime.Millisecond);
 }
Esempio n. 33
0
        public static DateTimeOffset ConvertFromUnixTimestamp(long timestamp)
        {
            var origin = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, DateTimeOffset.Now.Offset);

            return(origin.AddSeconds(timestamp));
        }
Esempio n. 34
0
		public static ImgurInfo ParseResponse(string response) {
			LOG.Debug(response);
			// This is actually a hack for BUG-1695
			// The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back 
			// Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
			response = response.Replace("&cent;", "&#162;");
			response = response.Replace("&pound;", "&#163;");
			response = response.Replace("&yen;", "&#165;");
			response = response.Replace("&euro;", "&#8364;");
			response = response.Replace("&copy;", "&#169;");
			response = response.Replace("&reg;", "&#174;");

			ImgurInfo imgurInfo = new ImgurInfo();
			try {
				XmlDocument doc = new XmlDocument();
				doc.LoadXml(response);
				XmlNodeList nodes = doc.GetElementsByTagName("id");
				if(nodes.Count > 0) {
					imgurInfo.Hash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("hash");
				if (nodes.Count > 0)
				{
					imgurInfo.Hash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("deletehash");
				if(nodes.Count > 0) {
					imgurInfo.DeleteHash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("type");
				if(nodes.Count > 0) {
					imgurInfo.ImageType = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("title");
				if(nodes.Count > 0) {
					imgurInfo.Title = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("datetime");
				if(nodes.Count > 0) {
					// Version 3 has seconds since Epoch
					double secondsSince;
					if (double.TryParse(nodes.Item(0).InnerText, out secondsSince))
					{
						var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
						imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
					}
				}
				nodes = doc.GetElementsByTagName("original");
				if (nodes.Count > 0)
				{
					imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				// Version 3 API only has Link
				nodes = doc.GetElementsByTagName("link");
				if (nodes.Count > 0)
				{
					imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				nodes = doc.GetElementsByTagName("imgur_page");
				if (nodes.Count > 0)
				{
					imgurInfo.Page = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				else
				{
					// Version 3 doesn't have a page link in the response
					imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash);
				}
				nodes = doc.GetElementsByTagName("small_square");
				if(nodes.Count > 0) {
					imgurInfo.SmallSquare = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("large_thumbnail");
				if(nodes.Count > 0)
				{
                    imgurInfo.LargeThumbnail = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
			} catch(Exception e) {
				LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
			}
			return imgurInfo;
		}
Esempio n. 35
0
 public static DateTimeOffset Round_(this DateTimeOffset dt)
 {
     return(dt.AddSeconds(-dt.Second).AddMilliseconds(-dt.Millisecond));
 }
Esempio n. 36
0
 public static void AddSeconds(DateTimeOffset dateTimeOffset, double seconds, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddSeconds(seconds));
 }
Esempio n. 37
0
        public static DateTimeOffset Round(this DateTimeOffset d, RoundTo rt)
        {
            DateTimeOffset dtRounded = new DateTimeOffset();

            switch (rt)
            {
            case RoundTo.Second:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Offset);
                if (d.Millisecond >= 500)
                {
                    dtRounded = dtRounded.AddSeconds(1);
                }
                break;

            case RoundTo.Minute:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0, d.Offset);
                if (d.Second >= 30)
                {
                    dtRounded = dtRounded.AddMinutes(1);
                }
                break;

            case RoundTo.MinuteFloor:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0, d.Offset);
                break;

            case RoundTo.MinuteCieling:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0, d.Offset);
                if (d.Second > 0)
                {
                    dtRounded = dtRounded.AddMinutes(1);
                }
                break;

            case RoundTo.Hour:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, 0, 0, d.Offset);
                if (d.Minute >= 30)
                {
                    dtRounded = dtRounded.AddHours(1);
                }
                break;

            case RoundTo.HourFloor:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, 0, 0, d.Offset);
                break;

            case RoundTo.DayFloor:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, 0, 0, 0, d.Offset);
                break;

            case RoundTo.Day:
                dtRounded = new DateTimeOffset(d.Year, d.Month, d.Day, 0, 0, 0, d.Offset);
                if (d.Hour >= 12)
                {
                    dtRounded = dtRounded.AddDays(1);
                }
                break;

            case RoundTo.Month:
                dtRounded = new DateTimeOffset(d.Year, d.Month, 1, 0, 0, 0, d.Offset);
                break;

            case RoundTo.MonthEnd:
                dtRounded = new DateTimeOffset(d.Year, d.Month, 1, 0, 0, 0, d.Offset).AddMonths(1).AddDays(-1);
                break;

            case RoundTo.Week:
                dtRounded = d.AddDays(-(int)d.DayOfWeek).Date;
                break;
            }
            return(dtRounded);
        }
        public void ToRelativeTimeTest()
        {
            var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero);
            var now = DateTimeOffset.Now;

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

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

            Assert.AreEqual("1 second from now", date.AddSeconds(1).ToRelativeTimeString(date));
            Assert.AreEqual("10 seconds from now", date.AddSeconds(10).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(90).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(100).ToRelativeTimeString(date));
            Assert.AreEqual("2 minutes from now", date.AddSeconds(120).ToRelativeTimeString(date));
            Assert.AreEqual("7 minutes from now", date.AddMinutes(7).ToRelativeTimeString(date));
            Assert.AreEqual("59 minutes from now", date.AddMinutes(59).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddMinutes(60).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddHours(1).ToRelativeTimeString(date));
            Assert.AreEqual("9 hours from now", date.AddHours(9).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddDays(1).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddHours(24).ToRelativeTimeString(date));
            Assert.AreEqual("12 days from now", date.AddDays(12).ToRelativeTimeString(date));
            Assert.AreEqual("29 days from now", date.AddDays(29).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddDays(30).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddMonths(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 months from now", date.AddMonths(3).ToRelativeTimeString(date));
            Assert.AreEqual("11 months from now", date.AddMonths(11).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddMonths(12).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddYears(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 years from now", date.AddYears(3).ToRelativeTimeString(date));
        }
Esempio n. 39
0
 string SetCacheItemFormat(DateTimeOffset utcNow, TimeSpan?slidingExpirationInSeconds, DateTimeOffset?absoluteExpiration, out DateTimeOffset expiresAtTime)
 {
     expiresAtTime = slidingExpirationInSeconds == null ? absoluteExpiration ?? DateTime.MaxValue : utcNow.AddSeconds(slidingExpirationInSeconds.Value.TotalSeconds);
     return("UPDATE {0} SET Value = @Value, ExpiresAtTime = datetime(@ExpiresAtTime)," +
            "SlidingExpirationInSeconds = @SlidingExpirationInSeconds, AbsoluteExpiration = datetime(@AbsoluteExpiration) " +
            "WHERE Id = @Id; " +
            "INSERT INTO {0} " +
            "(Id, Value, ExpiresAtTime, SlidingExpirationInSeconds, AbsoluteExpiration) " +
            "SELECT @Id, @Value, datetime(@ExpiresAtTime), @SlidingExpirationInSeconds, datetime(@AbsoluteExpiration) " +
            "WHERE changes() = 0;");
 }
Esempio n. 40
0
        public void TestSecondlyIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero);

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

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

            targetCalendar = targetCalendar.AddSeconds(400); // jump 400 seconds (4 intervals)

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

            Assert.AreEqual(targetCalendar, fifthTime, "Seconds increment result not as expected.");
        }
Esempio n. 41
0
 public static bool HasExceeded(this DateTimeOffset creationTime, int seconds)
 {
     return(DateTimeOffsetHelper.UtcNow > creationTime.AddSeconds(seconds));
 }
Esempio n. 42
0
        /// <summary>
        /// Returns the next date/time <i>after</i> the given date/time which does
        /// <i>not</i> satisfy the expression.
        /// </summary>
        /// <param name="date">the date/time at which to begin the search for the next invalid date/time</param>
        /// <returns>the next valid date/time</returns>
        public virtual DateTimeOffset? GetNextInvalidTimeAfter(DateTimeOffset date)
        {
            long difference = 1000;

            //move back to the nearest second so differences will be accurate
            DateTimeOffset lastDate =
                new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Offset).AddSeconds(-1);

            //TODO: IMPROVE THIS! The following is a BAD solution to this problem. Performance will be very bad here, depending on the cron expression. It is, however A solution.

            //keep getting the next included time until it's farther than one second
            // apart. At that point, lastDate is the last valid fire time. We return
            // the second immediately following it.
            while (difference == 1000)
            {
                DateTimeOffset? newDate = GetTimeAfter(lastDate);

                if (newDate == null)
                {
                    break;
                }

                difference = (long) (newDate.Value - lastDate).TotalMilliseconds;

                if (difference == 1000)
                {
                    lastDate = newDate.Value;
                }
            }

            return lastDate.AddSeconds(1);
        }
Esempio n. 43
0
        public async Task ProcessAsync_UsesExpiresSliding_ToExpireCacheEntryWithSlidingExpiration()
        {
            // Arrange - 1
            var currentTime   = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var id            = "unique-id";
            var childContent1 = "original-child-content";
            var clock         = new Mock <ISystemClock>();

            clock.SetupGet(p => p.UtcNow)
            .Returns(() => currentTime);
            var cache = new MemoryCache(new MemoryCacheOptions {
                Clock = clock.Object
            });
            var tagHelperContext1 = GetTagHelperContext(id, childContent1);
            var tagHelperOutput1  = new TagHelperOutput("cache",
                                                        new Dictionary <string, object> {
                { "attr", "value" }
            });

            tagHelperOutput1.PreContent.SetContent("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper
            {
                ViewContext    = GetViewContext(),
                MemoryCache    = cache,
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            currentTime = currentTime.AddSeconds(35);
            var childContent2     = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id, childContent2);
            var tagHelperOutput2  = new TagHelperOutput("cache",
                                                        new Dictionary <string, object> {
                { "attr", "value" }
            });

            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper
            {
                ViewContext    = GetViewContext(),
                MemoryCache    = cache,
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
		public static DateTimeOffset Round(this DateTimeOffset dateTime, RoundTo rt)
		{
			DateTimeOffset rounded;

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

			return rounded;
		}
Esempio n. 45
0
 /// <summary>
 /// 转换微信DateTimeOffset时间到C#时间
 /// </summary>
 /// <param name="dateTimeFromXml">微信DateTime</param>
 /// <returns></returns>
 public static DateTimeOffset GetDateTimeOffsetFromXml(long dateTimeFromXml)
 {
     return(BaseTime.AddSeconds(dateTimeFromXml).ToLocalTime());
 }
Esempio n. 46
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");
     }
 }
Esempio n. 47
0
        public void CanAddSecondsAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dto = new DateTimeOffset(2015, 3, 8, 1, 59, 59, TimeSpan.FromHours(-8));
            var result = dto.AddSeconds(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 async Task Sliding_Expiration_within_absolute_Expiration()
        {
            now = DateTimeOffset.UtcNow;

            var client = roclient_sliding_refresh_expiration_one_time_only;
            var token = CreateAccessToken(client, "valid", 60, "read", "write");

            var handle = await service.CreateRefreshTokenAsync(user, token, client);
            var refreshToken = await refreshTokenStore.GetAsync(handle);
            var lifetime = refreshToken.LifeTime;

            now = now.AddSeconds(1);

            var newHandle = await service.UpdateRefreshTokenAsync(handle, refreshToken, client);
            var newRefreshToken = await refreshTokenStore.GetAsync(newHandle);
            var newLifetime = newRefreshToken.LifeTime;

            (client.SlidingRefreshTokenLifetime + 1).Should().Be(newLifetime);
        }
Esempio n. 49
0
		public static DateTimeOffset UnixToDateTimeOffset(this long unixTime)
		{
			var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
			return epoch.AddSeconds(unixTime);
		}
 public static DateTimeOffset ConvertFromUnixTimestamp(long timestamp)
 {
     DateTimeOffset origin = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, DateTimeOffset.Now.Offset);
     return origin.AddSeconds(timestamp);
 }
Esempio n. 51
0
        public async Task 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);
            await fJobStore.StoreTrigger(trigger1, false);

            await fJobStore.StoreTrigger(trigger2, false);

            await fJobStore.StoreTrigger(trigger3, false);

            DateTimeOffset firstFireTime = trigger1.GetNextFireTimeUtc().Value;

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

            // release trigger3
            await fJobStore.ReleaseAcquiredTrigger(trigger3);

            Assert.AreEqual(trigger3, (await fJobStore.AcquireNextTriggers(firstFireTime.AddSeconds(10), 1, TimeSpan.FromMilliseconds(1)))[0]);
        }
        public void TestSchedulingWhenUpdatingScheduleBasedOnExistingTrigger()
        {
            DateTimeOffset startTime = new DateTimeOffset(2012, 12, 30, 1, 0, 0, TimeSpan.Zero);
            DateTimeOffset previousFireTime = new DateTimeOffset(2013, 2, 15, 15, 0, 0, TimeSpan.Zero);
            SimpleTriggerImpl existing = new SimpleTriggerImpl("triggerToReplace", "groupToReplace", startTime, null, SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromHours(1));
            existing.JobKey = new JobKey("jobName1", "jobGroup1");
            existing.SetPreviousFireTimeUtc(previousFireTime);
            existing.GetNextFireTimeUtc();

            mockScheduler.Stub(x => x.GetTrigger(existing.Key)).Return(existing);

            Stream s = ReadJobXmlFromEmbeddedResource("ScheduleRelativeToOldTrigger.xml");
            processor.ProcessStream(s, null);
            processor.ScheduleJobs(mockScheduler);

            // check that last fire time was taken from existing trigger
            mockScheduler.Stub(x => x.RescheduleJob(null, null)).IgnoreArguments();
            var args = mockScheduler.GetArgumentsForCallsMadeOn(x => x.RescheduleJob(null, null));
            ITrigger argumentTrigger = (ITrigger) args[0][1];

            // replacement trigger should have same start time and next fire relative to old trigger's last fire time 
            Assert.That(argumentTrigger, Is.Not.Null);
            Assert.That(argumentTrigger.StartTimeUtc, Is.EqualTo(startTime));
            Assert.That(argumentTrigger.GetNextFireTimeUtc(), Is.EqualTo(previousFireTime.AddSeconds(10)));
        }
Esempio n. 53
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 intervals. 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>
        public 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
                if (Definition.Interval != MetricSampleInterval.Default)
                {
                    returnVal = CalculateOffset(baseline, Definition.Interval, intervalCount);
                }
                else
                {
                    //default and ours is default - use second.
                    returnVal = CalculateOffset(baseline, MetricSampleInterval.Second, intervalCount);
                }
                break;

            case MetricSampleInterval.Shortest:
                //explicitly 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);
        }