/// <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;
        }
        /// <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);
        }
        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));
 }
Example #5
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
            };
        }
        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);
        }
    public void From_FromFixedDateTime_Tests(int value)
    {
        var originalPointInTime = new DateTimeOffset(1976, 12, 31, 17, 0, 0, 0, TimeSpan.Zero);

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

        Assert.AreEqual(value.Hours().From(originalPointInTime), originalPointInTime.AddHours(value));
        Assert.AreEqual(value.Minutes().From(originalPointInTime), originalPointInTime.AddMinutes(value));
        Assert.AreEqual(value.Seconds().From(originalPointInTime), originalPointInTime.AddSeconds(value));
        Assert.AreEqual(value.Milliseconds().From(originalPointInTime), originalPointInTime.AddMilliseconds(value));
        Assert.AreEqual(value.Ticks().From(originalPointInTime), originalPointInTime.AddTicks(value));
    }
Example #8
0
    public static void TestAddition()
    {
        DateTimeOffset dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70));
        Assert.Equal(17, dt.AddDays(2).Day);
        Assert.Equal(13, dt.AddDays(-2).Day);

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

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

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

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

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

        Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
        Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
    }
        public 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;
        }
Example #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);
        }
Example #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;
        }
		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;
		}
Example #13
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();
        }
Example #14
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);
        }
 /// <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);
 }
        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.");
        }
Example #17
0
		public static DateTimeOffset UnixToDateTimeOffset(this long unixTime)
		{
			var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
			return epoch.AddSeconds(unixTime);
		}
Example #18
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);
 }
Example #19
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;
		}
			static bool IsAlive(long connectionLifeTime, DateTimeOffset created, DateTimeOffset now)
			{
				if (connectionLifeTime == 0)
					return true;
				return created.AddSeconds(connectionLifeTime) > now;
			}
 public virtual DateTimeOffset GetNextCollectionTimeSlot(DateTimeOffset currentTime)
 {
     return currentTime.Millisecond < 500 ? currentTime.AddMilliseconds(500 - currentTime.Millisecond) : currentTime.AddSeconds(1).AddMilliseconds(500 - currentTime.Millisecond);
 }
        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);
        }
Example #23
0
 private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd)
 {
     switch (unit)
     {
         case IntervalUnit.Day:
             return date.AddDays(amountToAdd);
         case IntervalUnit.Hour:
             return date.AddHours(amountToAdd);
         case IntervalUnit.Minute:
             return date.AddMinutes(amountToAdd);
         case IntervalUnit.Month:
             return date.AddMonths(amountToAdd);
         case IntervalUnit.Second:
             return date.AddSeconds(amountToAdd);
         case IntervalUnit.Millisecond:
             return date.AddMilliseconds(amountToAdd);
         case IntervalUnit.Week:
             return date.AddDays(amountToAdd*7);
         case IntervalUnit.Year:
             return date.AddYears(amountToAdd);
         default:
             throw new ArgumentException("Unknown IntervalUnit");
     }
 }
Example #24
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);
        }
Example #26
0
 public static void AddSeconds(DateTimeOffset dateTimeOffset, double seconds, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddSeconds(seconds));
 }
 public static DateTimeOffset ConvertFromUnixTimestamp(long timestamp)
 {
     DateTimeOffset origin = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, DateTimeOffset.Now.Offset);
     return origin.AddSeconds(timestamp);
 }
        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());
        }
        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)));
        }
        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));
        }