/// <summary>
        /// Creates an account with specified, or random values.
        /// </summary>
        /// <param name="context">The database context.</param>
        /// <param name="type">The account type.</param>
        /// <param name="description">The description.</param>
        /// <param name="isDefault">A value indicating if the account is the default account.</param>
        /// <param name="isObsolete">A value indicating if the account is obsolete..</param>
        /// <param name="firstBalanceDate">The date on which the first balance entry should be added.</param>
        /// <param name="iconPack">The icon pack.</param>
        /// <param name="iconName">The icon name.</param>
        /// <param name="iconColor">The icon color.</param>
        /// <returns>The created account.</returns>
        public static (AccountEntity, DailyBalanceEntity) GenerateAccount(
            this Context context,
            AccountType type           = AccountType.Normal,
            string description         = null,
            bool isDefault             = false,
            bool isObsolete            = false,
            LocalDate?firstBalanceDate = null,
            string iconPack            = null,
            string iconName            = null,
            string iconColor           = null)
        {
            var account = context.Accounts.Add(new AccountEntity
            {
                Description = description ?? GetRandomString(),
                Type        = type,
                IsDefault   = isDefault,
                IsObsolete  = isObsolete,
                Icon        = new IconEntity
                {
                    Pack  = iconPack ?? GetRandomString(3),
                    Name  = iconName ?? GetRandomString(6),
                    Color = iconColor ?? GetRandomString(7),
                },
            }).Entity;

            var dailyBalance = context.DailyBalances.Add(new DailyBalanceEntity
            {
                Account = account,
                Balance = 0,
                Date    = firstBalanceDate ?? DateTime.Now.ToLocalDate(),
            }).Entity;

            return(account, dailyBalance);
        }
        /// <summary>
        /// Creates an expense with specified, or random values.
        /// </summary>
        /// <param name="splitwiseContext">The Splitwise context.</param>
        /// <param name="id">The identifier.</param>
        /// <param name="description">The description.</param>
        /// <param name="date">The date.</param>
        /// <param name="isDeleted">A value indicating if the expense is deleted.</param>
        /// <param name="updatedAt">The updated at timestamp.</param>
        /// <param name="paidAmount">The paid amount.</param>
        /// <param name="personalAmount">The personal amount.</param>
        /// <param name="splits">The splits.</param>
        /// <returns>The created expense.</returns>
        public static Expense GenerateExpense(
            this SplitwiseContextMock splitwiseContext,
            int id                 = 0,
            string description     = null,
            LocalDate?date         = null,
            bool isDeleted         = false,
            DateTime?updatedAt     = null,
            decimal paidAmount     = 10,
            decimal personalAmount = 5,
            List <Split> splits    = null)
        {
            var expense = new Expense
            {
                Id             = id,
                Description    = description ?? GetRandomString(),
                Date           = date ?? DateTime.Today.ToLocalDate(),
                IsDeleted      = isDeleted,
                UpdatedAt      = updatedAt ?? DateTime.Now,
                PaidAmount     = paidAmount,
                PersonalAmount = personalAmount,
                Splits         = splits ?? new List <Split>(),
            };

            splitwiseContext.Expenses.Add(expense);

            return(expense);
        }
        public async Task <ActionResult <double> > ArticlesSold(
            [FromQuery]
            [Description("Filters the day the articles were bought. " +
                         "When not specified no filter will be applied.")]
            LocalDate?day)
        {
            var from = DateTime.MinValue;
            var to   = DateTime.MaxValue;

            if (day != null)
            {
                from = new DateTime(day.Value.Year, day.Value.Month, day.Value.Day);
                to   = from.AddDays(1);
            }
            try
            {
                var numberOfSoldArticles = await _repository.GetNumberOfSoldArticles(from, to);

                _logger.LogInformation($"Successfully read the number of sold articles from the repository.");
                return(Ok(numberOfSoldArticles));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error while reading the number of sold articles from the repository.");
                throw;
            }
        }
 public MasterGameRequest(Guid requestID, FantasyCriticUser user, Instant requestTimestamp, string requestNote,
                          string gameName, int?steamID, int?openCriticID, LocalDate?releaseDate, string estimatedReleaseDate, EligibilityLevel eligibilityLevel,
                          bool yearlyInstallment, bool earlyAccess, bool freeToPlay, bool releasedInternationally, bool expansionPack, bool unannouncedGame,
                          bool answered, Instant?responseTimestamp, string responseNote, Maybe <MasterGame> masterGame, bool hidden)
 {
     RequestID               = requestID;
     User                    = user;
     RequestTimestamp        = requestTimestamp;
     RequestNote             = requestNote;
     GameName                = gameName;
     SteamID                 = steamID;
     OpenCriticID            = openCriticID;
     ReleaseDate             = releaseDate;
     EstimatedReleaseDate    = estimatedReleaseDate;
     EligibilityLevel        = eligibilityLevel;
     YearlyInstallment       = yearlyInstallment;
     EarlyAccess             = earlyAccess;
     FreeToPlay              = freeToPlay;
     ReleasedInternationally = releasedInternationally;
     ExpansionPack           = expansionPack;
     UnannouncedGame         = unannouncedGame;
     Answered                = answered;
     ResponseTimestamp       = responseTimestamp;
     ResponseNote            = responseNote;
     MasterGame              = masterGame;
     Hidden                  = hidden;
 }
Ejemplo n.º 5
0
 private static MasterGame CreateComplexMasterGame(string name, LocalDate minimumReleaseDate, LocalDate?maximumReleaseDate,
                                                   LocalDate?earlyAccessReleaseDate, LocalDate?internationalReleaseDate, LocalDate?announcementDate, IEnumerable <MasterGameTag> tags)
 {
     return(new MasterGame(Guid.NewGuid(), name, "TBA", minimumReleaseDate, maximumReleaseDate,
                           earlyAccessReleaseDate, internationalReleaseDate, announcementDate, null, null, null, null, "", null, null, null, false, false, false, false,
                           Instant.MinValue, new List <MasterSubGame>(), tags));
 }
Ejemplo n.º 6
0
        public void GuessZoneIdByTransitionsUncached(NamedWrapper <TimeZoneInfo> bclZoneWrapper)
        {
            var bclZone = bclZoneWrapper.Value;

            // As of November 21st 2019, the Windows time zone database hasn't caught up
            // with the Morocco change in TZDB 2019a. Skip it for now.
            if (bclZone.Id == "Morocco Standard Time")
            {
                return;
            }

            string?id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone,
                                                                                        TzdbDefaultZonesForIdGuessZoneIdByTransitionsUncached);

            // Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
            // We don't mind either way.
            if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
            {
                return;
            }

            Assert.IsNotNull(id, $"Unable to guess time zone for {bclZone.Id}");
            var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id !);

            var       thisYear                = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
            LocalDate?lastIncorrectDate       = null;
            Offset?   lastIncorrectBclOffset  = null;
            Offset?   lastIncorrectTzdbOffset = null;

            int total   = 0;
            int correct = 0;

            // From the start of this year to the end of next year, we should have an 80% hit rate or better.
            // That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
            // should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
            // so it's not quite equivalent anyway.)
            for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
            {
                Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
                Offset  tzdbOffset    = tzdbZone.GetUtcOffset(startOfUtcDay);
                Offset  bclOffset     = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
                if (tzdbOffset == bclOffset)
                {
                    correct++;
                }
                else
                {
                    // Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
                    lastIncorrectDate       = date;
                    lastIncorrectBclOffset  = bclOffset;
                    lastIncorrectTzdbOffset = tzdbOffset;
                }
                total++;
            }
            Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
                        "Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
                        bclZone.Id,
                        id,
                        lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
        }
Ejemplo n.º 7
0
 public PastMatch(LocalDate?date, string homeTeamName, string awayTeamName, Score score)
 {
     this.Date         = date;
     this.HomeTeamName = homeTeamName;
     this.AwayTeamName = awayTeamName;
     this.Score        = score;
 }
Ejemplo n.º 8
0
 public WorkPattern(DateTimeZone timezone, LocalDate start, LocalDate?end = null) : base(timezone)
 {
     Timezone = timezone;
     Start    = start;
     End      = end;
     Shifts   = new Dictionary <int, DayPattern>();
 }
Ejemplo n.º 9
0
        [TestMethod] // ReSharper disable once InconsistentNaming
        public void GetEnumerator_Iterating_DifferenceBetweenIterationsMatchesStepSize()
        {
            Period    length = RandomPeriod(MinPeriod, MaxPeriod, true, false);
            LocalDate start  = RandomLocalDate(MinLocalDate, MaxLocalDate - length);
            LocalDate end    = start + length;
            // note that the number of steps is limited to 100 or fewer
            Period step = PeriodDivideApprox(length, Random.Next(4, 100), false);

            LocalDateRange localRange = new LocalDateRange(start, end, step);

            LocalDate?previous = null;

            foreach (LocalDate d in localRange)
            {
                if (previous.HasValue)
                {
                    IComparer <Period> comparer = Period.CreateComparer(previous.Value.At(new LocalTime()));

                    Assert.AreEqual(
                        0,
                        comparer.Compare(Period.Between(previous.Value, d), step),
                        "Difference between iteration values should match the step value supplied");
                }
                previous = d;
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Get a date in the past between <paramref name="reference"/> and years past that date.
        /// </summary>
        /// <param name="daysToGoBack">Days to go back from <paramref name="reference"/>. Default is 100.</param>
        /// <param name="reference">The date to start calculations. Default is SystemClock.Instance.GetCurrentInstant().</param>
        public LocalDate Past(int daysToGoBack = 100, LocalDate?reference = null)
        {
            var max    = ValueOrNull(reference);
            var random = Random.Int(0, daysToGoBack);

            return(max.PlusDays(-random));
        }
Ejemplo n.º 11
0
 public MasterGame(Guid masterGameID, string gameName, string estimatedReleaseDate, LocalDate minimumReleaseDate, LocalDate?maximumReleaseDate,
                   LocalDate?earlyAccessReleaseDate, LocalDate?internationalReleaseDate, LocalDate?announcementDate, LocalDate?releaseDate, int?openCriticID, string?ggToken, decimal?criticScore,
                   string?notes, string?boxartFileName, string?ggCoverArtFileName, Instant?firstCriticScoreTimestamp, bool doNotRefreshDate,
                   bool doNotRefreshAnything, bool eligibilityChanged, bool delayContention, Instant addedTimestamp, IEnumerable <MasterSubGame> subGames, IEnumerable <MasterGameTag> tags)
 {
     MasterGameID             = masterGameID;
     GameName                 = gameName;
     EstimatedReleaseDate     = estimatedReleaseDate;
     MinimumReleaseDate       = minimumReleaseDate;
     MaximumReleaseDate       = maximumReleaseDate;
     EarlyAccessReleaseDate   = earlyAccessReleaseDate;
     InternationalReleaseDate = internationalReleaseDate;
     AnnouncementDate         = announcementDate;
     ReleaseDate              = releaseDate;
     OpenCriticID             = openCriticID;
     GGToken                   = ggToken;
     RawCriticScore            = criticScore;
     Notes                     = notes;
     BoxartFileName            = boxartFileName;
     GGCoverArtFileName        = ggCoverArtFileName;
     FirstCriticScoreTimestamp = firstCriticScoreTimestamp;
     DoNotRefreshDate          = doNotRefreshDate;
     DelayContention           = delayContention;
     DoNotRefreshAnything      = doNotRefreshAnything;
     EligibilityChanged        = eligibilityChanged;
     AddedTimestamp            = addedTimestamp;
     SubGames                  = subGames.ToList();
     Tags = tags.ToList();
 }
Ejemplo n.º 12
0
        public async Task MemberBirthday(Context ctx, PKMember target)
        {
            if (ctx.System == null)
            {
                throw Errors.NoSystemError;
            }
            if (target.System != ctx.System.Id)
            {
                throw Errors.NotOwnMemberError;
            }

            LocalDate?date     = null;
            var       birthday = ctx.RemainderOrNull();

            if (birthday != null)
            {
                date = PluralKit.Utils.ParseDate(birthday, true);
                if (date == null)
                {
                    throw Errors.BirthdayParseError(birthday);
                }
            }

            target.Birthday = date;
            await _data.SaveMember(target);

            await ctx.Reply($"{Emojis.Success} Member birthdate {(date == null ? "cleared" : $"changed to {target.BirthdayString}")}.");
Ejemplo n.º 13
0
        private Request AddRequest(
            ApplicationUser user,
            LocalDate?date = null,
            bool allocated = false,
            bool reserved  = false)
        {
            var request = new Request {
                ApplicationUser = user, Date = date ?? AllocationDate
            };

            this.requests.Add(request);

            if (allocated)
            {
                this.allocations.Add(new Allocation {
                    ApplicationUser = user, Date = date ?? AllocationDate
                });
            }

            if (reserved)
            {
                this.reservations.Add(new Reservation {
                    ApplicationUser = user, Date = date ?? AllocationDate
                });
            }

            return(request);
        }
 public LocalInterval(LocalDate?start, LocalDate?end, TimePayloadBase payload = null, string name = null)
 {
     Name    = name;
     Start   = start.HasValue ? start.Value + new LocalTime(0, 0) : (LocalDateTime?)null;
     End     = end.HasValue ? end.Value + new LocalTime(0, 0) : (LocalDateTime?)null;
     Payload = payload;
 }
Ejemplo n.º 15
0
        public MasterGame ToDomain(IEnumerable <MasterSubGame> subGames, EligibilityLevel eligibilityLevel)
        {
            LocalDate?releaseDate = null;

            if (ReleaseDate.HasValue)
            {
                releaseDate = LocalDate.FromDateTime(ReleaseDate.Value);
            }

            LocalDate?sortableEstimatedReleaseDate = null;

            if (SortableEstimatedReleaseDate.HasValue)
            {
                sortableEstimatedReleaseDate = LocalDate.FromDateTime(SortableEstimatedReleaseDate.Value);
            }

            Instant?firstCriticScoreTimestamp = null;

            if (FirstCriticScoreTimestamp.HasValue)
            {
                firstCriticScoreTimestamp = Instant.FromDateTimeUtc(FirstCriticScoreTimestamp.Value);
            }

            var addedTimestamp      = LocalDateTime.FromDateTime(AddedTimestamp).InZoneStrictly(DateTimeZone.Utc).ToInstant();
            var eligibilitySettings = new EligibilitySettings(eligibilityLevel, YearlyInstallment, EarlyAccess, FreeToPlay, ReleasedInternationally, ExpansionPack, UnannouncedGame);

            return(new MasterGame(MasterGameID, GameName, EstimatedReleaseDate, sortableEstimatedReleaseDate, releaseDate, OpenCriticID, CriticScore, LocalDate.FromDateTime(MinimumReleaseDate),
                                  eligibilitySettings, subGames.ToList(), BoxartFileName, firstCriticScoreTimestamp, DoNotRefreshDate, DoNotRefreshAnything, EligibilityChanged, addedTimestamp));
        }
Ejemplo n.º 16
0
        public MasterGameYear ToDomain(IEnumerable <MasterSubGame> subGames, EligibilityLevel eligibilityLevel, int year)
        {
            LocalDate?releaseDate = null;

            if (ReleaseDate.HasValue)
            {
                releaseDate = LocalDate.FromDateTime(ReleaseDate.Value);
            }

            LocalDate?sortableEstimatedReleaseDate = null;

            if (SortableEstimatedReleaseDate.HasValue)
            {
                sortableEstimatedReleaseDate = LocalDate.FromDateTime(SortableEstimatedReleaseDate.Value);
            }

            Instant?firstCriticScoreTimestamp = null;

            if (FirstCriticScoreTimestamp.HasValue)
            {
                firstCriticScoreTimestamp = Instant.FromDateTimeUtc(FirstCriticScoreTimestamp.Value);
            }

            var addedTimestamp      = LocalDateTime.FromDateTime(AddedTimestamp).InZoneStrictly(DateTimeZone.Utc).ToInstant();
            var eligibilitySettings = new EligibilitySettings(eligibilityLevel, YearlyInstallment, EarlyAccess, FreeToPlay, ReleasedInternationally, ExpansionPack, UnannouncedGame);

            var masterGame = new MasterGame(MasterGameID, GameName, EstimatedReleaseDate, sortableEstimatedReleaseDate, releaseDate,
                                            OpenCriticID, CriticScore, LocalDate.FromDateTime(MinimumReleaseDate), eligibilitySettings, subGames.ToList(), BoxartFileName, firstCriticScoreTimestamp,
                                            false, false, EligibilityChanged, addedTimestamp);

            return(new MasterGameYear(masterGame, year, PercentStandardGame, PercentCounterPick, EligiblePercentStandardGame, EligiblePercentCounterPick,
                                      NumberOfBids, TotalBidAmount, BidPercentile, AverageDraftPosition, AverageWinningBid, HypeFactor, DateAdjustedHypeFactor, LinearRegressionHypeFactor));
        }
Ejemplo n.º 17
0
 public OpenCriticGame(int id, string name, decimal?score, LocalDate?releaseDate)
 {
     ID          = id;
     Name        = name;
     Score       = score;
     ReleaseDate = releaseDate;
 }
        /// <summary>
        /// Creates a Splitwise transaction with specified, or random values.
        /// </summary>
        /// <param name="context">The database context.</param>
        /// <param name="id">The identifier.</param>
        /// <param name="description">The description.</param>
        /// <param name="date">The date.</param>
        /// <param name="isDeleted">A value indicating if the expense is deleted.</param>
        /// <param name="updatedAt">The updated at timestamp.</param>
        /// <param name="paidAmount">The paid amount.</param>
        /// <param name="personalAmount">The personal amount.</param>
        /// <param name="imported">The imported value.</param>
        /// <param name="splits">The splits.</param>
        /// <returns>The created expense.</returns>
        public static SplitwiseTransactionEntity GenerateSplitwiseTransaction(
            this Context context,
            int id                          = 0,
            string description              = null,
            LocalDate?date                  = null,
            bool isDeleted                  = false,
            DateTime?updatedAt              = null,
            decimal paidAmount              = 10,
            decimal personalAmount          = 5,
            bool imported                   = false,
            List <SplitDetailEntity> splits = null)
        {
            var expense = new SplitwiseTransactionEntity
            {
                Id             = id,
                Description    = description ?? GetRandomString(),
                Date           = date ?? DateTime.Today.ToLocalDate(),
                IsDeleted      = isDeleted,
                UpdatedAt      = updatedAt ?? DateTime.Now,
                PaidAmount     = paidAmount,
                PersonalAmount = personalAmount,
                Imported       = imported,
                SplitDetails   = splits ?? new List <SplitDetailEntity>(),
            };

            context.SplitwiseTransactions.Add(expense);

            return(expense);
        }
Ejemplo n.º 19
0
        public void GuessZoneIdByTransitionsUncached(TimeZoneInfo bclZone)
        {
            // As of April 8th 2016, the Windows time zone database hasn't noticed that
            // Azerbaijan is no longer observing DST.
            // As of April 21st 2016, the Windows time zone database hasn't caught up to
            // 2016d which includes: "America/Caracas switches from -0430 to -04 on 2016-05-01 at 02:30"
            if (bclZone.Id == "Azerbaijan Standard Time" || bclZone.Id == "Venezuela Standard Time")
            {
                return;
            }

            string id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone);

            // Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
            // We don't mind either way.
            if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
            {
                return;
            }

            Assert.IsNotNull(id, $"Unable to guess time zone for {bclZone.Id}");
            var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id);

            var       thisYear                = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
            LocalDate?lastIncorrectDate       = null;
            Offset?   lastIncorrectBclOffset  = null;
            Offset?   lastIncorrectTzdbOffset = null;

            int total   = 0;
            int correct = 0;

            // From the start of this year to the end of next year, we should have an 80% hit rate or better.
            // That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
            // should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
            // so it's not quite equivalent anyway.)
            for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
            {
                Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
                Offset  tzdbOffset    = tzdbZone.GetUtcOffset(startOfUtcDay);
                Offset  bclOffset     = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
                if (tzdbOffset == bclOffset)
                {
                    correct++;
                }
                else
                {
                    // Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
                    lastIncorrectDate       = date;
                    lastIncorrectBclOffset  = bclOffset;
                    lastIncorrectTzdbOffset = tzdbOffset;
                }
                total++;
            }
            Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
                        "Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
                        bclZone.Id,
                        id,
                        lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
        }
Ejemplo n.º 20
0
        public void GuessZoneIdByTransitionsUncached(TimeZoneInfo bclZone)
        {
            // As of October 17th 2013, the Windows time zone database hasn't noticed that
            // Morocco delayed the DST transition in 2013, so we end up with UTC. It's
            // annoying, but it's not actually a code issue. Just ignore it for now. We
            // should check this periodically and remove the hack when it works again.
            // Likewise Libya has somewhat odd representation in the BCL. Worth looking at more closely later.
            if (bclZone.Id == "Morocco Standard Time" || bclZone.Id == "Libya Standard Time")
            {
                return;
            }
            string id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone);

            // Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
            // We don't mind either way.
            if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
            {
                return;
            }

            Assert.IsNotNull(id);
            var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id);

            var       thisYear                = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
            LocalDate?lastIncorrectDate       = null;
            Offset?   lastIncorrectBclOffset  = null;
            Offset?   lastIncorrectTzdbOffset = null;

            int total   = 0;
            int correct = 0;

            // From the start of this year to the end of next year, we should have an 80% hit rate or better.
            // That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
            // should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
            // so it's not quite equivalent anyway.)
            for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
            {
                Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
                Offset  tzdbOffset    = tzdbZone.GetUtcOffset(startOfUtcDay);
                Offset  bclOffset     = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
                if (tzdbOffset == bclOffset)
                {
                    correct++;
                }
                else
                {
                    // Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
                    lastIncorrectDate       = date;
                    lastIncorrectBclOffset  = bclOffset;
                    lastIncorrectTzdbOffset = tzdbOffset;
                }
                total++;
            }
            Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
                        "Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
                        bclZone.Id,
                        id,
                        lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
        }
Ejemplo n.º 21
0
 public OpenCriticGame(OpenCriticScoreResponse scoreResponse, LocalDate?releaseDate)
 {
     ID          = scoreResponse.ID;
     Name        = scoreResponse.Name;
     Score       = scoreResponse.Score;
     ReviewCount = scoreResponse.ReviewCount;
     ReleaseDate = releaseDate;
 }
 public static LocalDateAssertions Should(this LocalDate?value)
 {
     if (value == null)
     {
         throw new ArgumentNullException(nameof(value));
     }
     return(new LocalDateAssertions(value));
 }
 private static string?FormatDate(LocalDate?localDate)
 {
     if (localDate.HasValue)
     {
         return(LocalDatePattern.Iso.Format(localDate.Value));
     }
     return(null);
 }
Ejemplo n.º 24
0
 public static LocalDate?Max(LocalDate?val1, LocalDate?val2)
 {
     if (val1 == null || val2 == null)
     {
         return(null);
     }
     return(val1 > val2 ? val1 : val2);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Get a date in the future between <paramref name="reference"/> and years forward of that date.
        /// </summary>
        /// <param name="daysToGoForward">Days to go forward from <paramref name="reference"/>. Default is 100.</param>
        /// <param name="reference">The date to start calculations. Default is SystemClock.Instance.GetCurrentInstant().</param>
        public LocalDate Future(int daysToGoForward = 100, LocalDate?reference = null)
        {
            var min = ValueOrNull(reference);

            var random = Random.Int(0, daysToGoForward);

            return(min.PlusDays(random));
        }
Ejemplo n.º 26
0
        public async Task <Maybe <OpenCriticGame> > GetOpenCriticGame(int openCriticGameID)
        {
            try
            {
                var gameResponse = await _client.GetStringAsync($"game/{openCriticGameID}");

                if (string.IsNullOrWhiteSpace(gameResponse))
                {
                    return(Maybe <OpenCriticGame> .None);
                }
                JObject parsedGameResponse = JObject.Parse(gameResponse);

                var       gameName               = parsedGameResponse.GetValue("name").Value <string>();
                LocalDate?earliestReleaseDate    = null;
                var       releaseDateToken       = parsedGameResponse.GetValue("firstReleaseDate");
                var       firstReleaseDateString = releaseDateToken.Value <string>();
                if (!string.IsNullOrWhiteSpace(firstReleaseDateString))
                {
                    var earliestDateTime = releaseDateToken.Value <DateTime>();
                    earliestReleaseDate = LocalDate.FromDateTime(earliestDateTime);
                    if (earliestReleaseDate == DefaultOpenCriticReleaseDate)
                    {
                        earliestReleaseDate = null;
                    }
                }

                var score = parsedGameResponse.GetValue("topCriticScore").Value <decimal?>();
                if (score == -1m)
                {
                    score = parsedGameResponse.GetValue("averageScore").Value <decimal?>();
                    if (score != -1m)
                    {
                        _logger.LogWarning($"Using averageScore for game: {openCriticGameID}");
                    }
                    else
                    {
                        score = null;
                    }
                }

                var openCriticGame = new OpenCriticGame(openCriticGameID, gameName, score, earliestReleaseDate);
                return(openCriticGame);
            }
            catch (HttpRequestException httpEx)
            {
                if (httpEx.Message == "Response status code does not indicate success: 404 (Not Found).")
                {
                    return(Maybe <OpenCriticGame> .None);
                }
                _logger.LogError(httpEx, $"Getting an open critic game failed: {openCriticGameID}");
                throw;
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Getting an open critic game failed: {openCriticGameID}");
                throw;
            }
        }
Ejemplo n.º 27
0
        public JournalFrontMatter(string yamlFrontMatter, LocalDate?journalEntryDate)
        {
            yamlFrontMatter = yamlFrontMatter.Trim();
            var yamlLines         = yamlFrontMatter.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var originalLineCount = yamlLines.Count;

            if (yamlLines[0] == BlockIndicator)
            {
                yamlLines.RemoveAt(0);
            }

            var lastIndex = yamlLines.Count - 1;

            if (yamlLines[lastIndex] == BlockIndicator)
            {
                yamlLines.RemoveAt(lastIndex);
            }

            if (originalLineCount != yamlLines.Count)
            {
                yamlFrontMatter = string.Join(Environment.NewLine, yamlLines);
            }

            using (var reader = new System.IO.StringReader(yamlFrontMatter))
            {
                var yamlStream = new YamlStream();
                yamlStream.Load(reader);

                var keys = yamlStream.Documents[0].RootNode.AllNodes
                           .Where(x => x.NodeType == YamlNodeType.Mapping)
                           .Cast <YamlMappingNode>()
                           .SelectMany(x => x.Children.Keys)
                           .Cast <YamlScalarNode>()
                           .ToList();

                var tagsKey   = keys.FirstOrDefault(k => k.Value.ToLowerInvariant() == "tags");
                var readMeKey = keys.FirstOrDefault(k => k.Value.ToLowerInvariant() == "readme");

                if (tagsKey != null)
                {
                    var node = yamlStream.Documents[0].RootNode[tagsKey];
                    if (node.NodeType == YamlNodeType.Sequence)
                    {
                        var tags = (YamlSequenceNode)node;
                        Tags = tags.Select(x => x.ToString()).Distinct().OrderBy(x => x).ToList();
                    }
                }

                if (readMeKey != null && journalEntryDate != null)
                {
                    var readme = (YamlScalarNode)yamlStream.Documents[0].RootNode[readMeKey];
                    var parser = new ReadmeParser(readme.Value, journalEntryDate.Value);
                    Readme     = parser.FrontMatterValue;
                    ReadmeDate = parser.ExpirationDate;
                }
            }
        }
Ejemplo n.º 28
0
        public Contract(int templateId, int customerId, int tenementId, LocalDate start, LocalDate?end)
        {
            _templateId = templateId;

            this.CustomerId = customerId;
            this.TenementId = tenementId;
            this.StartDate  = start;
            this.EndDate    = end;
        }
Ejemplo n.º 29
0
 private void ResetAggregateState()
 {
     HasAgreedInitially           = false;
     HasSignedPermanentAgreement  = false;
     _hasSignedFixedTermAgreement = false;
     AgreementEndDate             = null;
     HasResignedPermanently       = _hasResignedTemporarily = false;
     ResignationEndDate           = null;
 }
Ejemplo n.º 30
0
        LocalDate ValueOrNull(LocalDate?reference)
        {
            if (reference == null)
            {
                return(Now());
            }

            return(reference.Value);
        }