Esempio n. 1
0
        public void ExpectedNextRun_ShouldBeLastRunDatePlusIntervalAfterItRuns()
        {
            var clock    = new FakeClock();
            var interval = FiveMinutes;
            var timer    = new FakeTimerFactory();

            var policy = new RecurringRunPolicy(interval, timer, clock);

            clock.AddToCurrentInstant(FiveMinutes);
            var timeAtTimerAction = clock.CurrentInstant;

            timer.FireTimerAction();
            clock.AddToCurrentInstant(Duration.FromMinutes(1));


            policy.ExpectedNextRun.Should().Be(timeAtTimerAction.Plus(interval));
        }
 public ScheduleProcessor(ILogger <ScheduleProcessor> logger,
                          ILogger <VenmoApi> venmoApiLogger,
                          ILogger <MongoDatabase> mongoDatabaseLogger,
                          HttpClient httpClient,
                          IClock clock,
                          HelperMethods helperMethods)
 {
     this.logger              = logger;
     this.venmoApiLogger      = venmoApiLogger;
     this.mongoDatabaseLogger = mongoDatabaseLogger;
     this.httpClient          = httpClient;
     this.clock         = clock;
     this.helperMethods = helperMethods;
     CheckDuration      = Duration.FromMinutes(15);
     checkTask          = CheckSchedules();
     _ = CheckCheckSchedulesTask();
 }
        internal void GivenCompetitorsAreBeingAddedAndRemovedFromTheSpotsByDuration_TheAlreadyPlacedCompetitorsWillContainsAllCompetitorsValuesInTheSpots()
        {
            var runningTotal = new SmoothSponsorshipRunningTotals();

            runningTotal.AddCompetitorToSpotByDuration("p1", Duration.FromMinutes(1));
            runningTotal.AddCompetitorToSpotByDuration("p2", Duration.FromMinutes(2));
            runningTotal.AddCompetitorToSpotByDuration("p3", Duration.FromMinutes(5));
            runningTotal.AddCompetitorToSpotByDuration("p1", Duration.FromMinutes(3));
            runningTotal.AddCompetitorToSpotByDuration("p2", Duration.FromMinutes(1));
            runningTotal.RemoveCompetitorToSpotByDuration("p1", Duration.FromMinutes(2));
            runningTotal.RemoveCompetitorToSpotByDuration("p3", Duration.FromMinutes(5));
            runningTotal.RemoveCompetitorToSpotByDuration("p4", Duration.FromMinutes(5));

            Assert.Equal(new ProductExternalReference[] { "p1", "p2" }, runningTotal.AlreadyPlacedCompetitors.Keys.ToArray());
            Assert.Equal(120, runningTotal.AlreadyPlacedCompetitors["p1"]);
            Assert.Equal(180, runningTotal.AlreadyPlacedCompetitors["p2"]);
        }
        internal void Instantiation_WhenOptionLoadCacheFalse_ReturnsNull()
        {
            // Arrange
            // Act
            var redisConnection2 = ConnectionMultiplexer.Connect("localhost:6379,allowAdmin=true");
            var database2        = new RedisExecutionDatabase(
                this.container,
                redisConnection2,
                new MsgPackEventSerializer(),
                false);

            // Assert
            Assert.Equal(Duration.FromMinutes(1), database2.OrderStatusCheckInterval);
            Assert.Empty(database2.GetAccountIds());
            Assert.Empty(database2.GetOrders());
            Assert.Empty(database2.GetPositions());
        }
Esempio n. 5
0
        internal void EndDateTime_WithStubBars_ReturnsExpectedResult()
        {
            // Arrange
            var bar1 = StubBarData.Create();
            var bar2 = StubBarData.Create(1);
            var bars = new[] { bar1, bar2 };

            var barDataFrame = new BarDataFrame(
                this.stubBarType,
                bars);

            // Act
            var result = barDataFrame.EndDateTime;

            // Assert
            Assert.Equal(StubZonedDateTime.UnixEpoch() + Duration.FromMinutes(1), result);
        }
Esempio n. 6
0
        public void ConversionRoundTrip()
        {
            Duration second = Duration.FromSeconds(1);

            AssertEx.EqualTolerance(1, Duration.FromDays(second.Days).Seconds, DaysTolerance);
            AssertEx.EqualTolerance(1, Duration.FromHours(second.Hours).Seconds, HoursTolerance);
            AssertEx.EqualTolerance(1, Duration.FromMicroseconds(second.Microseconds).Seconds, MicrosecondsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromMilliseconds(second.Milliseconds).Seconds, MillisecondsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromMinutes(second.Minutes).Seconds, MinutesTolerance);
            AssertEx.EqualTolerance(1, Duration.FromMonths(second.Months).Seconds, MonthsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromMonths30(second.Months30).Seconds, Months30Tolerance);
            AssertEx.EqualTolerance(1, Duration.FromNanoseconds(second.Nanoseconds).Seconds, NanosecondsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromSeconds(second.Seconds).Seconds, SecondsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromWeeks(second.Weeks).Seconds, WeeksTolerance);
            AssertEx.EqualTolerance(1, Duration.FromYears(second.Years).Seconds, YearsTolerance);
            AssertEx.EqualTolerance(1, Duration.FromYears365(second.Years365).Seconds, Years365Tolerance);
        }
        public void Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence()
        {
            var     systemDateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
            Instant now = TestClock.Now;
            var     zonedDateTimeStart  = new ZonedDateTime(now, systemDateTimeZone);
            var     zonedDateTimeFinish = zonedDateTimeStart.Plus(Duration.FromMinutes(60));

            var testLocation = new LocationTestEntity
            {
                Description          = "Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence",
                LocationDateTimeZone = systemDateTimeZone
            };

            var testEvent = new DateTimeOffsetTestEntity
            {
                Description          = "Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence",
                EventLocation        = testLocation,
                StartDateTimeOffset  = zonedDateTimeStart.ToDateTimeOffset(),
                FinishDateTimeOffset = zonedDateTimeFinish.ToDateTimeOffset()
            };

            using (ISession session = SessionFactory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(testLocation);
                    session.Save(testEvent);
                    transaction.Commit();
                }

            ZonedDateTime retrievedZonedDateStart;
            ZonedDateTime retrievedZonedDateFinish;

            using (ISession session = SessionFactory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    var retrievedEvent = session.Get <DateTimeOffsetTestEntity>(testEvent.Id);
                    retrievedZonedDateStart =
                        retrievedEvent.StartDateTimeOffset.ToZonedDateTime(retrievedEvent.EventLocation.LocationDateTimeZone);
                    retrievedZonedDateFinish =
                        retrievedEvent.FinishDateTimeOffset.ToZonedDateTime(retrievedEvent.EventLocation.LocationDateTimeZone);
                    transaction.Commit();
                }

            Assert.That(zonedDateTimeStart, Is.EqualTo(retrievedZonedDateStart));
            Assert.That(zonedDateTimeFinish, Is.EqualTo(retrievedZonedDateFinish));
        }
Esempio n. 8
0
        internal void ApplyEvents_OrderFilledFromAlreadyShort_ReturnsCorrectMarketPositionAndQuantity()
        {
            // Arrange
            var orderFill11 = new OrderFilled(
                AccountId.FromString("FXCM-02851908-DEMO"),
                new OrderId("O-123456"),
                new ExecutionId("E-123456"),
                new PositionIdBroker("ET-123456"),
                new Symbol("AUD/USD", new Venue("FXCM")),
                OrderSide.Sell,
                Quantity.Create(5000),
                Price.Create(1.00000m, 5),
                Currency.USD,
                StubZonedDateTime.UnixEpoch(),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var position = new Position(new PositionId("P-123456"), orderFill11);

            var orderFill2 = new OrderFilled(
                AccountId.FromString("FXCM-02851908-DEMO"),
                new OrderId("O-123456"),
                new ExecutionId("E-123456"),
                new PositionIdBroker("ET-123456"),
                position.Symbol,
                OrderSide.Buy,
                Quantity.Create(5000),
                Price.Create(1.00000m, 5),
                Currency.USD,
                StubZonedDateTime.UnixEpoch() + Duration.FromMinutes(1),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            position.Apply(orderFill2);

            // Assert
            Assert.Equal(MarketPosition.Flat, position.MarketPosition);
            Assert.Equal(Duration.FromMinutes(1), position.OpenDuration);
            Assert.Equal(Quantity.Create(0), position.Quantity);
            Assert.Equal(orderFill2, position.LastEvent);
            Assert.True(position.IsClosed);
            Assert.False(position.IsOpen);
            Assert.False(position.IsShort);
            Assert.False(position.IsLong);
        }
Esempio n. 9
0
 public void FromMethods_OutOfRange()
 {
     // Not checking the exact values here so much as that the exception is appropriate.
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromDays(int.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromDays(int.MaxValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromHours(int.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromHours(int.MaxValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromMinutes(long.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromMinutes(long.MaxValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromSeconds(long.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromSeconds(long.MaxValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromMilliseconds(long.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromMilliseconds(long.MaxValue));
     // FromTicks never throws.
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(decimal.MinValue));
     Assert.Throws <ArgumentOutOfRangeException>(() => Duration.FromNanoseconds(decimal.MaxValue));
 }
        public async Task Should_set_next_attempt_based_on_num_calls(int calls, int minutes, RuleResult result, RuleJobResult jobResult)
        {
            var actionData = "{}";
            var actionName = "MyAction";

            var @event = CreateEvent(calls, actionName, actionData);

            var requestElapsed = TimeSpan.FromMinutes(1);
            var requestDump    = "Dump";

            A.CallTo(() => ruleService.InvokeAsync(@event.Job.ActionName, @event.Job.ActionData, default))
            .Returns((Result.Create(requestDump, result), requestElapsed));

            var now = clock.GetCurrentInstant();

            Instant?nextCall = null;

            if (minutes > 0)
            {
                nextCall = now.Plus(Duration.FromMinutes(minutes));
            }

            await sut.HandleAsync(@event);

            if (result == RuleResult.Failed)
            {
                A.CallTo(() => log.Log(SemanticLogLevel.Warning, A <Exception?> ._, A <LogFormatter> ._))
                .MustHaveHappened();
            }
            else
            {
                A.CallTo(() => log.Log(SemanticLogLevel.Warning, A <Exception?> ._, A <LogFormatter> ._))
                .MustNotHaveHappened();
            }

            A.CallTo(() => ruleEventRepository.UpdateAsync(@event.Job,
                                                           A <RuleJobUpdate> .That.Matches(x =>
                                                                                           x.Elapsed == requestElapsed &&
                                                                                           x.ExecutionDump == requestDump &&
                                                                                           x.ExecutionResult == result &&
                                                                                           x.Finished == now &&
                                                                                           x.JobNext == nextCall &&
                                                                                           x.JobResult == jobResult),
                                                           A <CancellationToken> ._))
            .MustHaveHappened();
        }
        public void Can_Use_NodaTime_Interval_In_Dynamic_Index()
        {
            var now       = SystemClock.Instance.GetCurrentInstant();
            var start     = now - Duration.FromMinutes(5);
            var end       = now + Duration.FromMinutes(5);
            var interval1 = new Interval(start, end);
            var interval2 = new Interval(end, end + Duration.FromMinutes(5));

            using (var documentStore = NewDocumentStore())
            {
                documentStore.ConfigureForNodaTime();

                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Interval = interval1
                    });
                    session.Store(new Foo {
                        Id = "foos/2", Interval = interval2
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var q1 = session.Query <Foo>()
                             .Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Interval.Start == interval1.Start && x.Interval.End == interval1.End);
                    var results1 = q1.ToList();
                    Assert.Equal(1, results1.Count);

                    var q2 = session.Query <Foo>()
                             .Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Interval.Start <= now && x.Interval.End > now);
                    var results2 = q2.ToList();
                    Assert.Equal(1, results2.Count);

                    var q3 = session.Query <Foo>()
                             .Customize(x => x.WaitForNonStaleResults())
                             .OrderByDescending(x => x.Interval.Start);
                    var results3 = q3.ToList();
                    Assert.Equal(2, results3.Count);
                    Assert.True(results3[0].Interval.Start > results3[1].Interval.Start);
                }
            }
        }
Esempio n. 12
0
        public async Task ExecuteInlineAsync(string key, T job)
        {
            try
            {
                await onSuccess(new List <T> {
                    job
                }, false, default);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Failed to handle job.");

                var nextTime = clock.GetCurrentInstant().Plus(Duration.FromMinutes(5));

                await schedulerStore.EnqueueScheduledAsync(key, job, nextTime, 1);
            }
        }
Esempio n. 13
0
        private async Task MakeRequestAsync(IWebhookEventEntity @event)
        {
            try
            {
                var response = await webhookSender.SendAsync(@event.Job);

                Instant?nextCall = null;

                if (response.Result != WebhookResult.Success)
                {
                    var now = clock.GetCurrentInstant();

                    switch (@event.NumCalls)
                    {
                    case 0:
                        nextCall = now.Plus(Duration.FromMinutes(5));
                        break;

                    case 1:
                        nextCall = now.Plus(Duration.FromHours(1));
                        break;

                    case 2:
                        nextCall = now.Plus(Duration.FromHours(5));
                        break;

                    case 3:
                        nextCall = now.Plus(Duration.FromHours(6));
                        break;
                    }
                }

                await Task.WhenAll(
                    webhookRepository.TraceSentAsync(@event.Job.WebhookId, response.Result, response.Elapsed),
                    webhookEventRepository.TraceSentAsync(@event.Id, response.Dump, response.Result, response.Elapsed, nextCall));
            }
            catch (Exception ex)
            {
                log.LogError(ex, w => w
                             .WriteProperty("action", "SendWebhookEvent")
                             .WriteProperty("status", "Failed"));

                throw;
            }
        }
        public static async Task Does_not_notify_user_when_request_will_appear_on_scheduled_weekly_notification()
        {
            var users = new[] { CreateUser.With(userId: "user1", emailAddress: "*****@*****.**") };

            var mockUserRepository = new Mock <IUserRepository>(MockBehavior.Strict);

            mockUserRepository
            .Setup(r => r.GetUsers())
            .ReturnsAsync(users);

            var requests = new[]
            {
                new Request("user1", 11.January(2021), RequestStatus.Allocated),
                new Request("user1", 12.January(2021), RequestStatus.Allocated)
            };

            var mockDateCalculator = new Mock <IDateCalculator>(MockBehavior.Strict);

            mockDateCalculator
            .Setup(c => c.ScheduleIsDue(
                       It.Is <Schedule>(s => s.ScheduledTaskType == ScheduledTaskType.DailyNotification),
                       Duration.FromMinutes(2)))
            .Returns(false);
            mockDateCalculator
            .Setup(c => c.ScheduleIsDue(
                       It.Is <Schedule>(s => s.ScheduledTaskType == ScheduledTaskType.WeeklyNotification),
                       Duration.FromMinutes(2)))
            .Returns(true);
            mockDateCalculator
            .Setup(c => c.GetWeeklyNotificationDates())
            .Returns(new[] { 11.January(2021), 12.January(2021) });

            var mockEmailRepository = new Mock <IEmailRepository>();

            var allocationNotifier = new AllocationNotifier(
                Mock.Of <ILogger <AllocationNotifier> >(),
                mockDateCalculator.Object,
                mockEmailRepository.Object,
                CreateDummyScheduleRepository(),
                mockUserRepository.Object);

            await allocationNotifier.Notify(requests);

            mockEmailRepository.VerifyNoOtherCalls();
        }
        private void Can_Use_NodaTime_Instant_In_Static_Index2(Instant instant)
        {
            using (var documentStore = NewDocumentStore())
            {
                documentStore.ConfigureForNodaTime();
                documentStore.ExecuteIndex(new TestIndex());

                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Instant = instant
                    });
                    session.Store(new Foo {
                        Id = "foos/2", Instant = instant + Duration.FromMinutes(-1)
                    });
                    session.Store(new Foo {
                        Id = "foos/3", Instant = instant + Duration.FromMinutes(-2)
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var q1 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant == instant);
                    var results1 = q1.ToList();
                    Assert.Equal(1, results1.Count);

                    var q2 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant < instant)
                             .OrderBy(x => x.Instant);
                    var results2 = q2.ToList();
                    Assert.Equal(2, results2.Count);
                    Assert.True(results2[0].Instant < results2[1].Instant);

                    var q3 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant <= instant)
                             .OrderBy(x => x.Instant);
                    var results3 = q3.ToList();
                    Assert.Equal(3, results3.Count);
                    Assert.True(results3[0].Instant < results3[1].Instant);
                    Assert.True(results3[1].Instant < results3[2].Instant);
                }
            }
        }
        private void Can_Use_NodaTime_ZonedDateTime_In_Static_Index(ZonedDateTime zdt)
        {
            using (var documentStore = NewDocumentStore())
            {
                documentStore.ConfigureForNodaTime();
                documentStore.ExecuteIndex(new TestIndex());

                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", ZonedDateTime = zdt
                    });
                    session.Store(new Foo {
                        Id = "foos/2", ZonedDateTime = zdt - Duration.FromMinutes(1)
                    });
                    session.Store(new Foo {
                        Id = "foos/3", ZonedDateTime = zdt - Duration.FromMinutes(2)
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var q1 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.ZonedDateTime == zdt);
                    var results1 = q1.ToList();
                    Assert.Equal(1, results1.Count);

                    var q2 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => ZonedDateTime.Comparer.Local.Compare(x.ZonedDateTime, zdt) < 0)
                             .OrderBy(x => x.ZonedDateTime);
                    var results2 = q2.ToList();
                    Assert.Equal(2, results2.Count);
                    Assert.True(ZonedDateTime.Comparer.Local.Compare(results2[0].ZonedDateTime, results2[1].ZonedDateTime) < 0);

                    var q3 = session.Query <Foo, TestIndex>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => ZonedDateTime.Comparer.Local.Compare(x.ZonedDateTime, zdt) <= 0)
                             .OrderBy(x => x.ZonedDateTime);
                    var results3 = q3.ToList();
                    Assert.Equal(3, results3.Count);
                    Assert.True(ZonedDateTime.Comparer.Local.Compare(results3[0].ZonedDateTime, results3[1].ZonedDateTime) < 0);
                    Assert.True(ZonedDateTime.Comparer.Local.Compare(results3[1].ZonedDateTime, results3[2].ZonedDateTime) < 0);
                }
            }
        }
Esempio n. 17
0
        // [START iot_mqtt_jwt]
        public static string CreateJwtRsa(string projectId, string privateKeyFile)
        {
            string privateKey = File.ReadAllText(privateKeyFile);

            RSAParameters rsaParams;

            // Read the private key file.
            using (var tr = new StringReader(privateKey))
            {
                var pemReader    = new PemReader(tr);
                var KeyParameter = (AsymmetricKeyParameter)
                                   pemReader.ReadObject();
                var privateRsaParams = KeyParameter
                                       as RsaPrivateCrtKeyParameters;
                rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);

                pemReader.Reader.Close();
                tr.Close();
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                var jwtIatTime = SystemClock.Instance.GetCurrentInstant();
                // Create a duration
                Duration durationExp = Duration.FromMinutes(120);
                var      jwtExpTime  = SystemClock.Instance.
                                       GetCurrentInstant().Plus(durationExp);

                Dictionary <string, object> payload =
                    new Dictionary <string, object> {
                    { "iat", jwtIatTime.ToUnixTimeSeconds() },
                    // The time that the token was issued at
                    { "aud", projectId },
                    // The audience field should always
                    // be set to the GCP project id.
                    { "exp", jwtExpTime.ToUnixTimeSeconds() }
                    // The time the token expires.
                };
                Console.WriteLine("iat time {0}", jwtIatTime);
                Console.WriteLine("exp time {0}", jwtExpTime);
                Console.WriteLine("Creating JWT using RSA from private key " +
                                  "file {0}", privateKeyFile);
                return(Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256));
            }
        }
Esempio n. 18
0
        public async Task CanSaveASimpleRecipe()
        {
            var recipe = new Recipe(name: "Chocolate Milk")
            {
                PrepTime = Duration.FromMinutes(3),
                CookTime = Duration.Zero
            };

            var milk           = new Ingredient("Milk");
            var chocolateSauce = new Ingredient("Chocolate Sauce");

            recipe.AddIngredient(milk, UnitOfMeasure.Cup, 1M);
            recipe.AddIngredient(chocolateSauce, UnitOfMeasure.Tablespoon, 2M);

            await AppFixture.InsertAsync(recipe);

            var saved = await AppFixture.ExecuteDbContextAsync(db =>
                                                               db.Recipes
                                                               .Include(r => r.RecipeIngredients)
                                                               .ThenInclude(ri => ri.Ingredient)
                                                               .Where(r => r.Key == recipe.Key)
                                                               .FirstOrDefaultAsync());

            saved.Name.Should().Be("Chocolate Milk");
            saved.PrepTime.Should().Be(Duration.FromMinutes(3));
            saved.CookTime.Should().Be(Duration.Zero);
            saved.RecipeIngredients.Should().HaveCount(2)
            .And.SatisfyRespectively(
                first =>
            {
                first.Id.Should().BeGreaterThan(0);
                first.Key.Should().NotBe(Guid.Empty);
                first.Quantity.Should().Be(1M);
                first.UnitOfMeasure.Should().Be(UnitOfMeasure.Cup);
                first.Ingredient.Should().Be(milk);
            },
                second =>
            {
                second.Id.Should().BeGreaterThan(0);
                second.Key.Should().NotBe(Guid.Empty);
                second.Quantity.Should().Be(2M);
                second.UnitOfMeasure.Should().Be(UnitOfMeasure.Tablespoon);
                second.Ingredient.Should().Be(chocolateSauce);
            });
        }
Esempio n. 19
0
        private List <Break> CreateBreaks(DateTime breakOneStart, DateTime breakTwoStart)
        {
            var breaks = _fixture.Build <Break>()
                         .With(p => p.SalesArea, _salesAreaName)
                         .With(p => p.Duration, Duration.FromMinutes(3))
                         .CreateMany(2)
                         .ToList();

            breaks[0].ScheduledDate  = breakOneStart;
            breaks[0].Avail          = Duration.FromMinutes(1);
            breaks[0].OptimizerAvail = Duration.FromMinutes(1);

            breaks[1].ScheduledDate  = breakTwoStart;
            breaks[1].Avail          = Duration.FromMinutes(1);
            breaks[1].OptimizerAvail = Duration.FromMinutes(1);

            return(breaks);
        }
Esempio n. 20
0
        public void Should_not_wakeup_if_already_scheduled()
        {
            var now = SystemClock.Instance.GetCurrentInstant();

            var simulatedClock = A.Fake <IClock>();

            A.CallTo(() => simulatedClock.GetCurrentInstant())
            .Returns(now);

            var token = new MobilePushToken
            {
                LastWakeup = now.Plus(Duration.FromMinutes(25))
            };

            var result = token.GetNextWakeupTime(simulatedClock);

            Assert.Null(result);
        }
Esempio n. 21
0
        public void Should_wakeup_as_soon_as_possible()
        {
            var now = SystemClock.Instance.GetCurrentInstant();

            var simulatedClock = A.Fake <IClock>();

            A.CallTo(() => simulatedClock.GetCurrentInstant())
            .Returns(now);

            var token = new MobilePushToken
            {
                LastWakeup = now.Minus(Duration.FromMinutes(25))
            };

            var result = token.GetNextWakeupTime(simulatedClock);

            Assert.Equal(now.Plus(Duration.FromMinutes(5)), result);
        }
Esempio n. 22
0
        public async Task RefreshToken_Should_Refresh_Token()
        {
            var token = new
            {
                access_token  = "2YotnFZFEjr1zCsicMWpAA",
                expires_in    = 10800,
                refresh_token = "tGzv3JOkF0XG5Qx2TlKWIA"
            };

            var expectedToken = new
            {
                access_token  = "dGVzdGNsaWVudDpzZWNyZXQ",
                expires_in    = 10800,
                refresh_token = "fdb8fdbecf1d03ce5e6125c067733c0d51de209c"
            };

            httpTest.RespondWithJson(token);
            httpTest.RespondWithJson(expectedToken);

            var fakeClock = new FakeClock(SystemClock.Instance.GetCurrentInstant(), Duration.FromMinutes(-2));

            var sut = new Netatmo.CredentialManager("https://api.netatmo.com/", "clientId", "clientSecret", fakeClock);

            await sut.GenerateToken("*****@*****.**", "p@$$W0rd");

            var oldToken = sut.CredentialToken;
            await sut.RefreshToken();

            var refreshedToken = sut.CredentialToken;

            httpTest
            .ShouldHaveCalled("https://api.netatmo.com/oauth2/token")
            .WithVerb(HttpMethod.Post)
            .WithContentType("application/x-www-form-urlencoded")
            .WithRequestBody(
                $"grant_type=refresh_token&client_id=clientId&client_secret=clientSecret&refresh_token={oldToken.RefreshToken}")
            .Times(1);

            refreshedToken.Should().BeOfType <CredentialToken>();
            refreshedToken.AccessToken.Should().Be(expectedToken.access_token);
            refreshedToken.RefreshToken.Should().Be(expectedToken.refresh_token);
            refreshedToken.ExpiresAt.Should().Be(refreshedToken.ReceivedAt.Plus(Duration.FromSeconds(expectedToken.expires_in)));
            refreshedToken.Should().NotBe(oldToken);
        }
Esempio n. 23
0
        private async Task <ServiceResponse> AddSaveAsync(Type textResource, ZonedDateTime requestStartInUtc, DateTimeZone userZone, IGym gym, byte level, IPokemon pokemon, IRaidboss raidboss, TimeSpan timeSpan)
        {
            var utcNowAfterProcessing   = SystemClock.Instance.GetCurrentInstant().InUtc();
            var processingTime          = utcNowAfterProcessing.Minus(requestStartInUtc);
            var durationMinusProcessing = Duration.FromTimeSpan(timeSpan).Minus(processingTime);

            var expiry = utcNowAfterProcessing.Plus(durationMinusProcessing).ToInstant();

            // Create the raid entry
            var beforeSpawnTime = utcNowAfterProcessing.Minus(Duration.FromMinutes(105)).ToInstant().ToUnixTimeSeconds();
            var raid            = await RaidRepository.FindAsync(e => e.FortId == gym.Id && e.TimeSpawn > beforeSpawnTime);

            if (raid == null)
            {
                raid            = RaidRepository.CreateInstance();
                raid.ExternalId = ThreadLocalRandom.NextLong();
                raid.FortId     = gym.Id;
                RaidRepository.Add(raid);
            }

            string message;

            if (raidboss == null)
            {
                raid.Level      = level;
                raid.TimeSpawn  = (int)expiry.Minus(_eggDuration).ToUnixTimeSeconds();
                raid.TimeBattle = (int)expiry.ToUnixTimeSeconds();
                raid.TimeEnd    = (int)expiry.Plus(_raidDuration).ToUnixTimeSeconds();
                message         = LocalizationService.Get(textResource, "Raids_Messages_EggAdded", level, gym.Name, FormatExpiry(expiry, userZone));
            }
            else
            {
                raid.PokemonId  = (short)raidboss.Id;
                raid.Level      = level;
                raid.TimeSpawn  = (int)expiry.Minus(Duration.FromMinutes(105)).ToUnixTimeSeconds();
                raid.TimeBattle = (int)expiry.Minus(Duration.FromMinutes(45)).ToUnixTimeSeconds();
                raid.TimeEnd    = (int)expiry.ToUnixTimeSeconds();
                message         = LocalizationService.Get(textResource, "Raids_Messages_BossAdded", pokemon.Name, gym.Name, FormatExpiry(expiry, userZone));
            }

            await RaidRepository.SaveAsync();

            return(new ServiceResponse(true, message));
        }
Esempio n. 24
0
        public IActionResult Get()
        {
            var timezone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("US/Pacific");

            var clock           = new ClockService(timezone, null);
            var timeTravelClock = new ClockService(timezone, new LocalDate(1999, 12, 31).AtMidnight());

            var user = new User()
            {
                Name                 = "John Doe",
                Birthday             = new LocalDate(1987, 5, 2),
                ShiftStartTime       = new LocalTime(6, 0),
                TimezoneString       = "US/Pacific",
                CreatedDateTime      = clock.Now.Minus(Duration.FromDays(54)),
                LastModifiedDateTime = clock.Now.Minus(Duration.FromMinutes(10))
            };

            return(Ok(new { user, Now = clock.Now, LocalNow = clock.LocalNow, TimeTravelNow = timeTravelClock.Now, TimeTravelLocalNow = timeTravelClock.LocalNow }));
        }
Esempio n. 25
0
        public void Test_ZoneIntervalTransition()
        {
            Dio.TestZoneIntervalTransition(null, Instant.MinValue);
            Dio.TestZoneIntervalTransition(null, Instant.MaxValue);
            Dio.TestZoneIntervalTransition(null, Instant.MinValue.PlusTicks(1));
            Dio.TestZoneIntervalTransition(null, Instant.MaxValue.PlusTicks(-1));

            // Encoding as hours-since-previous.
            Instant previous = Instant.FromUtc(1990, 1, 1, 11, 30);  // arbitrary

            Dio.TestZoneIntervalTransition(previous, previous);
            Dio.TestZoneIntervalTransition(previous, previous + Duration.FromHours(
                                               DateTimeZoneWriter.ZoneIntervalConstants.MinValueForHoursSincePrevious));
            Dio.TestZoneIntervalTransition(previous, previous + Duration.FromHours(
                                               DateTimeZoneWriter.ZoneIntervalConstants.MinValueForHoursSincePrevious - 1)); // too soon
            Dio.TestZoneIntervalTransition(previous, previous + Duration.FromHours(1));                                      // too soon
            Dio.TestZoneIntervalTransition(previous, previous + Duration.FromHours(
                                               DateTimeZoneWriter.ZoneIntervalConstants.MinValueForMinutesSinceEpoch - 1));  // maximum hours
            Dio.TestZoneIntervalTransition(previous, previous + Duration.FromHours(
                                               DateTimeZoneWriter.ZoneIntervalConstants.MinValueForMinutesSinceEpoch));      // out of range
            // A large difference from the previous transition.
            Dio.TestZoneIntervalTransition(Instant.MinValue.PlusTicks(1), Instant.MaxValue.PlusTicks(-1));

            // Encoding as minutes-since-epoch.
            Instant epoch = DateTimeZoneWriter.ZoneIntervalConstants.EpochForMinutesSinceEpoch;

            Dio.TestZoneIntervalTransition(null, epoch);
            Dio.TestZoneIntervalTransition(null, epoch +
                                           Duration.FromMinutes(DateTimeZoneWriter.ZoneIntervalConstants.MinValueForMinutesSinceEpoch));
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromMinutes(int.MaxValue));  // maximum minutes

            // Out of range cases, or not a multiple of minutes since the epoch.
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromHours(1));   // too soon
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromMinutes(1)); // too soon
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromSeconds(1));
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromMilliseconds(1));
            Dio.TestZoneIntervalTransition(null, epoch - Duration.FromHours(1));
            Dio.TestZoneIntervalTransition(null, epoch + Duration.FromMinutes((long)int.MaxValue + 1));

            // Example from Pacific/Auckland which failed at one time, and a similar one with seconds.
            Dio.TestZoneIntervalTransition(null, Instant.FromUtc(1927, 11, 5, 14, 30));
            Dio.TestZoneIntervalTransition(null, Instant.FromUtc(1927, 11, 5, 14, 30, 5));
        }
Esempio n. 26
0
        /// <summary>
        /// Returns default AutoBookSettings for the system.
        /// Auto-provisioning is disabled so that the setting can be reviewed before we turn it on.
        /// </summary>
        /// <returns></returns>
        public static AutoBookSettings GetDefaultAutoBookSettings()
        {
            AutoBookSettings autoBookSettings = new AutoBookSettings()
            {
                AutoProvisioning   = false,                                                                // Disabled so that we don't start re-provisioning with the version below
                MinInstances       = 0,                                                                    // We only want instances when we need them, reduces costs
                MaxInstances       = 5,
                SystemMaxInstances = 10,                                                                   // Low limit to start with
                CreationTimeout    = Duration.FromMinutes(15),                                             // Takes about 5 mins usually
                MinLifetime        = Duration.FromMinutes(65),                                             // At least 1 hr
                MaxLifetime        = Duration.FromMilliseconds(0),                                         // No need to recycle
                ProvisioningAPIURL = "http://xg-autobook-provider-api-dev.eu-west-2.elasticbeanstalk.com", // Same API for all systems
                ApplicationVersion = null,                                                                 // "v1.53.0-dev"
                BinariesVersion    = null,
                Locked             = false
            };

            return(autoBookSettings);
        }
        private void Can_Use_NodaTime_Instant_In_Dynamic_Index1(Instant instant)
        {
            using (var documentStore = NewDocumentStore())
            {
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "foos/1", Instant = instant
                    });
                    session.Store(new Foo {
                        Id = "foos/2", Instant = instant + Duration.FromMinutes(1)
                    });
                    session.Store(new Foo {
                        Id = "foos/3", Instant = instant + Duration.FromMinutes(2)
                    });
                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var q1 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant == instant);
                    var results1 = q1.ToList();
                    Assert.Single(results1);

                    var q2 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant > instant)
                             .OrderByDescending(x => x.Instant);
                    var results2 = q2.ToList();
                    Assert.Equal(2, results2.Count);
                    Assert.True(results2[0].Instant > results2[1].Instant);

                    var q3 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults())
                             .Where(x => x.Instant >= instant)
                             .OrderByDescending(x => x.Instant);
                    var results3 = q3.ToList();
                    Assert.Equal(3, results3.Count);
                    Assert.True(results3[0].Instant > results3[1].Instant);
                    Assert.True(results3[1].Instant > results3[2].Instant);
                }
            }
        }
Esempio n. 28
0
        public void Should_wakeup_now_when_not_waked_up_for_a_while()
        {
            var now = SystemClock.Instance.GetCurrentInstant();

            var simulatedClock = A.Fake <IClock>();

            A.CallTo(() => simulatedClock.GetCurrentInstant())
            .Returns(now);

            var token = new MobilePushToken
            {
                LastWakeup = now.Minus(Duration.FromMinutes(35))
            };

            var result = token.GetNextWakeupTime(simulatedClock);

            var expected = now.Plus(MobilePushExtensions.WakeupDelay);

            Assert.Equal(expected, result);
        }
Esempio n. 29
0
        public async Task <string> GenerateRefreshToken(string sub)
        {
            //Save new refresh token in db
            var refreshKey = Guid.NewGuid().ToString();
            var expires    = Clock.InUtc()
                             .GetCurrentInstant()
                             .Plus(Duration.FromMinutes(_refreshTimeout));

            var refreshToken = await _refreshTokenRepository.CreateNewToken(refreshKey, sub, expires);

            //refresh claims
            var claims = new List <Claim>
            {
                new Claim("sub", refreshToken.Sub),
                new Claim("refresh_key", refreshKey)
            };

            //generate jwt
            return(CreateToken(claims, Clock.InUtc().GetCurrentInstant(), expires, _refreshSecret));
        }
Esempio n. 30
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var userClaimed = await _userManager.GetUserAsync(context.HttpContext.User);

            if (userClaimed != null)
            {
                var user = await _dbContext.Users.FindAsync(userClaimed.Id);

                if (user != null)
                {
                    var now = _clock.GetCurrentInstant();
                    _logger.LogDebug($"checking last_seen_at timestamp {user.LastSeenAt} (now {now}) for user {user.Id}");
                    if (user.LastSeenAt + Duration.FromMinutes(2) < now)
                    {
                        BackgroundJob.Enqueue <IUpdateUserLastSeenAtTimestampJob>(service => service.UpdateAsync(user.Id, now.ToDateTimeUtc()));
                    }
                }
            }
            await next();
        }