public async Task <ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, IActivity activity, CancellationToken cancellationToken = default) { return(await InvokeAsync(workflowContext, activity, (context, driver) => { workflowContext.Workflow.AddLogEntry(activity.Id, clock.GetCurrentInstant(), "Executing"); var result = driver.ExecuteAsync(context, workflowContext, cancellationToken); workflowContext.Workflow.AddLogEntry(activity.Id, clock.GetCurrentInstant(), "Executed"); return result; })); }
public async Task <ClaimResult> PurchaseGame(RoyalePublisher publisher, MasterGameYear masterGame) { if (publisher.PublisherGames.Count >= MAX_GAMES) { return(new ClaimResult("Roster is full.")); } if (publisher.PublisherGames.Select(x => x.MasterGame).Contains(masterGame)) { return(new ClaimResult("Publisher already has that game.")); } if (!masterGame.WillReleaseInQuarter(publisher.YearQuarter.YearQuarter)) { return(new ClaimResult("Game will not release this quarter.")); } if (masterGame.MasterGame.IsReleased(_clock.GetCurrentInstant())) { return(new ClaimResult("Game has been released.")); } if (masterGame.MasterGame.CriticScore.HasValue) { return(new ClaimResult("Game has a score.")); } var masterGameTags = await _masterGameRepo.GetMasterGameTags(); var eligibilityErrors = LeagueTagExtensions.GetRoyaleEligibilitySettings(masterGameTags).GameIsEligible(masterGame.MasterGame); if (eligibilityErrors.Any()) { return(new ClaimResult("Game is not eligible under Royale rules.")); } var currentBudget = publisher.Budget; var gameCost = masterGame.GetRoyaleGameCost(); if (currentBudget < gameCost) { return(new ClaimResult("Not enough budget.")); } RoyalePublisherGame game = new RoyalePublisherGame(publisher.PublisherID, publisher.YearQuarter, masterGame, _clock.GetCurrentInstant(), gameCost, 0m, null); await _royaleRepo.PurchaseGame(game); return(new ClaimResult()); }
public ScheduleView() { IClock systemClock = SystemClock.Instance; Instant now = systemClock.GetCurrentInstant(); DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); LocalDate today = now.InZone(tz).Date; MonthViewStartDate = tz.AtStartOfDay(today).ToInstant(); }
public async Task <CommandLog> Log(string userId, string command, IImmutableList <string> args, string?response) { var log = new CommandLog( string.Empty, userId, command, args, _clock.GetCurrentInstant(), response); await Collection.InsertOneAsync(log); Debug.Assert(log.Id.Length > 0, "The MongoDB driver injected a generated ID"); return(log); }
/// <summary> /// Creates a new instance of <see cref="BlogPostBuilder"/> using the given <see cref="IClock"/>. /// </summary> /// <param name="clock">The clock used for fetching the current time.</param> /// <returns>A new instance of <see cref="BlogPostBuilder"/>.</returns> public static BlogPostBuilder Create(IClock clock) { if (clock is null) { throw new ArgumentNullException(nameof(clock)); } return(new BlogPostBuilder(clock.GetCurrentInstant())); }
public async Task <IActionResult> CreateMasterGame([FromBody] CreateMasterGameRequest viewModel) { Instant instant = _clock.GetCurrentInstant(); var possibleTags = await _interLeagueService.GetMasterGameTags(); IReadOnlyList <MasterGameTag> tags = possibleTags .Where(x => viewModel.GetRequestedTags().Contains(x.Name)) .ToList(); MasterGame masterGame = viewModel.ToDomain(instant, tags); await _interLeagueService.CreateMasterGame(masterGame); var vm = new MasterGameViewModel(masterGame, _clock); _logger.LogInformation($"Created master game: {masterGame.MasterGameID}"); return(CreatedAtAction("MasterGame", "Game", new { id = masterGame.MasterGameID }, vm)); }
public bool MaybeSkipFiring() { Instant now = clock.GetCurrentInstant(); if (Monitor.TryEnter(@lock)) { try { if (IsRunning && now - lastExecuted > RateLimit) { lastExecuted = now; return(true); } } finally { Monitor.Exit(@lock); } } return(false); }
public Task HandleAsync(CommandContext context, Func <Task> next) { if (context.Command is ITimestampCommand timestampCommand) { timestampCommand.Timestamp = clock.GetCurrentInstant(); } return(next()); }
public Task <bool> HandleAsync(CommandContext context) { if (context.Command is ITimestampCommand timestampCommand) { timestampCommand.Timestamp = clock.GetCurrentInstant(); } return(TaskHelper.False); }
private async void SetBP_OnClick(object sender, RoutedEventArgs e) { PersonInfo personInfo = await _connection.GetPersonInfoAsync(); HealthRecordInfo recordInfo = personInfo.SelectedRecord; IThingClient thingClient = _connection.CreateThingClient(); LocalDateTime nowLocal = _clock.GetCurrentInstant().InZone(_dateTimeZoneProvider.GetSystemDefault()).LocalDateTime; await thingClient.CreateNewThingsAsync( recordInfo.Id, new List <BloodPressure> { new BloodPressure(new HealthServiceDateTime(nowLocal), 117, 70) }); OutputBlock.Text = "Created blood pressure."; }
/// <summary> /// Returns the date of the current <see cref="Instant"/> as a <see cref="LocalDate"/> type in UTC. /// </summary> /// <param name="source"></param> /// <returns></returns> internal static LocalDate Today(this IClock source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return(source.GetCurrentInstant().InUtc().LocalDateTime.Date); }
public async Task PublishAsync() { var now = clock.GetCurrentInstant(); await foreach (var content in contentRepository.QueryScheduledWithoutDataAsync(now)) { await TryPublishAsync(content); } }
private async Task RecoverAfterRestartAsync() { foreach (var job in state.Jobs) { if (!job.Stopped.HasValue) { job.Stopped = clock.GetCurrentInstant(); await Safe.DeleteAsync(backupArchiveLocation, job.Id, log); await Safe.DeleteAsync(assetStore, job.Id, log); job.Status = JobStatus.Failed; await WriteAsync(); } } }
public Task <Payment> CreateAsync(CreatePayment createPayment) { var payment = new Payment(_clock.GetCurrentInstant().ToDateTimeUtc()) { CardNumber = createPayment.CardNumber, Amount = createPayment.Amount, CVV = createPayment.CVV, Currency = createPayment.Currency, ExpiryMonth = (short)createPayment.ExpiryDate.Month, ExpiryYear = createPayment.ExpiryDate.Year, PaymentStatus = PaymentStatus.InProgress }; payment = _paymentData.GetOrAdd(payment.GetKey(), payment); return(Task.FromResult <Payment>(payment)); }
public PublisherViewModel(Publisher publisher, IClock clock, Maybe <Publisher> nextDraftPublisher, bool userIsInLeague, bool outstandingInvite, SystemWideValues systemWideValues, bool yearFinished) { PublisherID = publisher.PublisherID; LeagueID = publisher.LeagueYear.League.LeagueID; PublisherName = publisher.PublisherName; LeagueName = publisher.LeagueYear.League.LeagueName; PlayerName = publisher.User.DisplayName; Year = publisher.LeagueYear.Year; DraftPosition = publisher.DraftPosition; AutoDraft = publisher.AutoDraft; Games = publisher.PublisherGames .OrderBy(x => x.Timestamp) .Select(x => new PublisherGameViewModel(x, clock, publisher.LeagueYear.Options.ScoringSystem, systemWideValues)) .ToList(); AverageCriticScore = publisher.AverageCriticScore; TotalFantasyPoints = publisher.TotalFantasyPoints; TotalProjectedPoints = publisher.GetProjectedFantasyPoints(publisher.LeagueYear.Options, systemWideValues, yearFinished, false, clock); Budget = publisher.Budget; if (nextDraftPublisher.HasValue && nextDraftPublisher.Value.PublisherID == publisher.PublisherID) { NextToDraft = true; } UserIsInLeague = userIsInLeague; PublicLeague = publisher.LeagueYear.Options.PublicLeague; OutstandingInvite = outstandingInvite; var timeToCheck = clock.GetCurrentInstant(); if (yearFinished) { //Just before midnight on New Year's timeToCheck = new LocalDate(Year + 1, 1, 1).AtMidnight().InUtc().Minus(Duration.FromMinutes(1)).ToInstant(); } GamesReleased = publisher.PublisherGames .Where(x => !x.CounterPick) .Where(x => x.MasterGame.HasValue) .Count(x => x.MasterGame.Value.MasterGame.IsReleased(timeToCheck)); var allWillRelease = publisher.PublisherGames .Where(x => !x.CounterPick) .Where(x => x.MasterGame.HasValue) .Count(x => x.WillRelease()); GamesWillRelease = allWillRelease - GamesReleased; FreeGamesDropped = publisher.FreeGamesDropped; WillNotReleaseGamesDropped = publisher.WillNotReleaseGamesDropped; WillReleaseGamesDropped = publisher.WillReleaseGamesDropped; FreeDroppableGames = publisher.LeagueYear.Options.FreeDroppableGames; WillNotReleaseDroppableGames = publisher.LeagueYear.Options.WillNotReleaseDroppableGames; WillReleaseDroppableGames = publisher.LeagueYear.Options.WillReleaseDroppableGames; }
public void Process <TEntity>(TEntity entity, BulkInsertOperation operation, BulkInsertOptions options) where TEntity : class { var timestamp = _clock.GetCurrentInstant().ToDateTimeUtc(); if (entity is IAuditEntity auditEntity) { AuditEntityHelper.SetAudit(auditEntity, GetAuditEntityState(auditEntity, operation), timestamp); } }
private async Task <IEnumerable <ReturnFlightArchive> > FetchUpdatedReturnFlights() { var criteria = Criteria.DefaultCriteria(); var returnFlights = await _flightFinder.FindCheapestReturnFlightsForMultipleTravelDates(criteria).ConfigureAwait(true); var currentInstant = _clock.GetCurrentInstant(); return(returnFlights.Select(x => new ReturnFlightArchive(currentInstant, x))); }
private bool IsLatchExpired(ulong?messageId) { if (messageId == null) { return(true); } var timestamp = DiscordUtils.SnowflakeToInstant(messageId.Value); return(_clock.GetCurrentInstant() - timestamp > LatchExpiryTime); }
public RuleDequeuerTests() { A.CallTo(() => clock.GetCurrentInstant()).Returns(now); sut = new RuleDequeuerGrain( ruleService, ruleEventRepository, log, clock); }
public UsageNotifierGrainTests() { A.CallTo(() => clock.GetCurrentInstant()) .ReturnsLazily(() => time); A.CallTo(() => notificationSender.IsActive) .Returns(true); sut = new UsageNotifierGrain(state, notificationSender, userResolver, clock); }
public RuleServiceTests() { typeNameRegistry.Map(typeof(ContentCreated)); typeNameRegistry.Map(typeof(ValidAction), actionName); A.CallTo(() => clock.GetCurrentInstant()) .Returns(SystemClock.Instance.GetCurrentInstant().WithoutMs()); A.CallTo(() => ruleActionHandler.ActionType) .Returns(typeof(ValidAction)); A.CallTo(() => ruleActionHandler.DataType) .Returns(typeof(ValidData)); A.CallTo(() => ruleTriggerHandler.TriggerType) .Returns(typeof(ContentChangedTriggerV2)); sut = new RuleService(new[] { ruleTriggerHandler }, new[] { ruleActionHandler }, eventEnricher, TestUtils.DefaultSerializer, clock, typeNameRegistry); }
private async Task <List <MobileFoodFacility> > EnsureFacilitiesAreCachedAsync() { return(await _memoryCache.GetOrCreateAsync <List <MobileFoodFacility> >(FacilitiesCacheKey, async entry => { // Cache for 1 hour entry.AbsoluteExpiration = _clock.GetCurrentInstant().PlusTicks(new TimeSpan(1, 00, 00).Ticks).ToDateTimeOffset(); return await this.GetAllMobileFoodFacilities(); })); }
public async Task CleanupOldMessages() { var deleteThresholdInstant = _clock.GetCurrentInstant() - CommandMessageRetention; var deleteThresholdSnowflake = DiscordUtils.InstantToSnowflake(deleteThresholdInstant); var deletedRows = await _db.Execute(conn => _repo.DeleteCommandMessagesBefore(conn, deleteThresholdSnowflake)); _logger.Information("Pruned {DeletedRows} command messages older than retention {Retention} (older than {DeleteThresholdInstant} / {DeleteThresholdSnowflake})", deletedRows, CommandMessageRetention, deleteThresholdInstant, deleteThresholdSnowflake); }
public ShowScrapperScheduledService(ILogger <ShowScrapperScheduledService> logger, IClock clock, IOptions <ScheduleConfig> config, IServiceScopeFactory serviceScopeFactory) : base(logger) { _scheduleConfig = config.Value; _clock = clock; _serviceScopeFactory = serviceScopeFactory; _schedule = CrontabSchedule.Parse(_scheduleConfig.CronExpression); _nextRun = _clock.GetCurrentInstant().ToDateTimeUtc(); }
public void ShortDateTimeTest() { Assert.Equal(_clockTime, _clock.GetCurrentInstant().InZone(_zoneGmt).LocalDateTime); Assert.Equal("en-GB", MxCultureInfo.Instance.GetCultureInfo("en-GB").Name); Assert.Equal("fr-CH", MxCultureInfo.Instance.GetCultureInfo("fr-CH").Name); Assert.Equal("29-03-2020 12:59 AM", _startIsolation.ToString("en-GB", _zoneGmt)); //12:59 AM is 00:59 in 24 hour clock Assert.Equal("29.03.2020 00:59", _startIsolation.ToString("fr-CH", _zoneGmt)); }
public CreatePaymentValidator(IClock clock) { var now = clock.GetCurrentInstant().ToDateTimeUtc(); RuleFor(payment => payment.CardNumber).NotNull(); RuleFor(payment => payment.ExpiryDate).GreaterThan(now); RuleFor(payment => payment.Amount).GreaterThan(0); RuleFor(payment => payment.Currency).NotNull().Length(3); RuleFor(payment => payment.CVV).InclusiveBetween(100, 999); }
public override void BeforeSaveChanges(IDocumentSession session) { if (_context is null) { return; } var now = _clock.GetCurrentInstant().ToDateTimeOffset(); InnerHandleUnitOfWork(session.PendingChanges, now); }
public override async Task DoWorkAsync(CancellationToken cancellationToken) { _now = _clock.GetCurrentInstant().ToDateTimeUtc(); using (var scope = _serviceScopeFactory.CreateScope()) { Logger.LogInformation("Starting Service {0} for scrapping and persisting Shows...", nameof(IShowScrapperService)); var showScrapperService = scope.ServiceProvider.GetRequiredService <IShowScrapperService>(); await showScrapperService.ScrapAsync(cancellationToken); } }
public async Task CreateUserWithPasswordAsync_AssignsLastSeenAt() { const string userName1 = "normal-userName-1"; await _service.CreateUserWithPasswordAsync(userName1, "a-normal-pass123456789"); var user = await _userManager.FindByNameAsync(userName1); Assert.Equal(_clock.GetCurrentInstant(), user.LastSeenAt); }
public async Task <ClaimResult> ClaimGame(ClaimGameDomainRequest request) { PublisherGame playerGame = new PublisherGame(Guid.NewGuid(), request.GameName, _clock.GetCurrentInstant(), request.CounterPick, null, null, new MasterGameYear(request.MasterGame.Value, request.Publisher.Year), request.DraftPosition, request.OverallDraftPosition, request.Publisher.Year); ClaimResult claimResult = await CanClaimGame(request); if (!claimResult.Success) { return(claimResult); } LeagueAction leagueAction = new LeagueAction(request, _clock.GetCurrentInstant()); await _fantasyCriticRepo.AddLeagueAction(leagueAction); await _fantasyCriticRepo.AddPublisherGame(request.Publisher, playerGame); return(claimResult); }