Esempio n. 1
0
        private void CreateStreamSessions(ScheduledStream stream, DateTimeZone timeZone)
        {
            ZonedClock zonedClock = _clock.InZone(timeZone);

            LocalDate nextOfDay = zonedClock.GetCurrentDate()
                                  .With(DateAdjusters.Next(stream.DayOfWeek));

            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = nextOfDay + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime   = nextOfDay + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = DateTimeZoneProviders.Tzdb.VersionId,
                    UtcStartTime  = nextLocalStartDateTime
                                    .InZoneLeniently(timeZone)
                                    .ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(timeZone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                nextOfDay = nextOfDay.PlusWeeks(1);
            }
        }
Esempio n. 2
0
 public GeoCoder(TelemetryClient telemetryClient, IOptions <GeoCoderConfiguration> geoCoderOptions, YandexMapsClient yandexMapsClient, ZonedClock clock, IDateTimeZoneProvider dateTimeZoneProvider)
 {
     myTelemetryClient      = telemetryClient;
     myYandexMapsClient     = yandexMapsClient;
     myClock                = clock;
     myDateTimeZoneProvider = dateTimeZoneProvider;
     myGeoCoderOptions      = geoCoderOptions.Value ?? throw new ArgumentNullException(nameof(geoCoderOptions));
 }
Esempio n. 3
0
 protected UrlLikeMessageEntityHandler(TelemetryClient telemetryClient, IHttpClientFactory httpClientFactory, Func <MessageEntityEx, StringSegment> getUrl, ZonedClock clock, DateTimeZone timeZoneInfo, PokemonInfo pokemons, GymHelper gymHelper, IOptions <BotConfiguration> botConfiguration)
 {
     myGetUrl            = getUrl;
     myClock             = clock;
     myTimeZoneInfo      = timeZoneInfo;
     myPokemons          = pokemons;
     myGymHelper         = gymHelper;
     myTelemetryClient   = telemetryClient;
     myHttpClientFactory = httpClientFactory;
     myBotConfiguration  = botConfiguration.Value;
 }
Esempio n. 4
0
        private void Birthday()
        {
            LocalDate    birthDate = new LocalDate(1976, 6, 19);
            DateTimeZone zone      = DateTimeZoneProviders.Tzdb["Europe/London"];
            ZonedClock   clock     = SystemClock.Instance.InZone(zone);
            LocalDate    today     = clock.GetCurrentDate();

            Console.WriteLine($"Today's date: {today:yyyy-MM-dd}");
            Period age = Period.Between(birthDate, today);

            Console.WriteLine(
                $"Jon is: {age.Years} years, {age.Months} months, {age.Days} days old.");
        }
Esempio n. 5
0
        /// <summary>
        /// Get the start or end date time in UTC for the specified date range type in the specified time zone.
        /// </summary>
        /// <param name="dateRangeType">The date range type (today, current week etc.)</param>
        /// <param name="ianaTimeZoneName">The IANA time zone name</param>
        /// <param name="isStart">True for start and false for end of date range</param>
        /// <param name="useEndOfCurrentDay">Flag to indicate if end of current periods are now or the end of the current day</param>
        /// <returns>The start or end UTC for the range in the time zone</returns>
        public static DateTime?UtcForDateRangeType(this DateRangeType dateRangeType, string ianaTimeZoneName, bool isStart, bool useEndOfCurrentDay = false)
        {
            if (dateRangeType == DateRangeType.Custom || dateRangeType == DateRangeType.ProjectExtents || string.IsNullOrEmpty(ianaTimeZoneName))
            {
                return(null);
            }

            DateTimeZone  timeZone = DateTimeZoneProviders.Tzdb[ianaTimeZoneName];
            ZonedClock    clock    = SystemClock.Instance.InZone(timeZone);
            LocalDateTime localNow = clock.GetCurrentLocalDateTime();
            var           local    = localNow.LocalDateTimeForDateRangeType(dateRangeType, isStart);
            var           zoned    = timeZone.AtLeniently(local);

            return(zoned.ToDateTimeUtc());
        }
Esempio n. 6
0
        public void GetCurrent()
        {
            var        julian          = CalendarSystem.Julian;
            FakeClock  underlyingClock = new FakeClock(NodaConstants.UnixEpoch);
            ZonedClock zonedClock      = underlyingClock.InZone(SampleZone, julian);

            Assert.AreEqual(NodaConstants.UnixEpoch, zonedClock.GetCurrentInstant());
            Assert.AreEqual(new ZonedDateTime(underlyingClock.GetCurrentInstant(), SampleZone, julian),
                            zonedClock.GetCurrentZonedDateTime());
            Assert.AreEqual(new LocalDateTime(1969, 12, 19, 2, 0, julian), zonedClock.GetCurrentLocalDateTime());
            Assert.AreEqual(new LocalDateTime(1969, 12, 19, 2, 0, julian).WithOffset(Offset.FromHours(2)),
                            zonedClock.GetCurrentOffsetDateTime());
            Assert.AreEqual(new LocalDate(1969, 12, 19, julian), zonedClock.GetCurrentDate());
            Assert.AreEqual(new LocalTime(2, 0, 0), zonedClock.GetCurrentTimeOfDay());
        }
        public static Duration TimeUntilTomorrow(this ZonedClock clock)
        {
            ZonedDateTime zonedNow = clock.GetCurrentZonedDateTime();
            LocalDate     date     = zonedNow.Date;
            LocalTime     time     = zonedNow.TimeOfDay;
            LocalTime     threeAM  = new LocalTime(03, 00);

            if (time > threeAM)
            {
                date = date.PlusDays(1);
            }
            LocalDateTime next3AM      = date + threeAM;
            ZonedDateTime zonedNext3AM = zonedNow.Zone.AtLeniently(next3AM);

            return(zonedNext3AM - zonedNow);
        }
Esempio n. 8
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            List <string> errors           = new List <string>();
            var           dbClient         = new AmazonDynamoDBClient();
            var           logger           = new ConsoleLogger();
            var           spotClient       = new DatabaseClient <Spot>(dbClient, logger);
            var           vendorDataClient = new DatabaseClient <Vendor>(dbClient, logger);
            var           databaseClient   = new DatabaseClient <QuickBooksOnlineConnection>(dbClient, logger);
            var           qboClient        = new QuickBooksOnlineClient(PrivateAccounting.Constants.LakelandMiPuebloRealmId, databaseClient, logger);
            var           vendorUpdates    = JsonConvert.DeserializeObject <Vendor>(request.Body);

            if (vendorUpdates.Memo != null && vendorUpdates.Memo.Length > 4000)
            {
                errors.Add("Memo can't exceed 4,000 characters");
            }
            var spotReservationDbClient = new DatabaseClient <SpotReservation>(dbClient, logger);
            var allActiveCustomers      = qboClient
                                          .QueryAll <Customer>("select * from customer")
                                          .ToDictionary(x => x.Id);
            var allActiveVendors = new ActiveVendorSearch()
                                   .GetActiveVendors(allActiveCustomers, vendorDataClient)
                                   .ToList();
            var        spotReservationCheck = new SpotReservationCheck(spotClient, spotReservationDbClient, allActiveVendors, allActiveCustomers);
            ZonedClock easternClock         = SystemClock.Instance.InZone(Configuration.LakeLandMiPuebloTimeZone);
            LocalDate  easternToday         = easternClock.GetCurrentDate();

            while (easternToday.DayOfWeek != IsoDayOfWeek.Sunday)
            {
                easternToday = easternToday.PlusDays(1);
            }
            string easternRentalDate = easternToday.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

            errors.AddRange(spotReservationCheck.GetSpotConflicts(vendorUpdates.Spots, easternRentalDate, vendorUpdates.Id).Result);

            if (errors.Any())
            {
                response.StatusCode = 400;
                response.Body       = new JObject {
                    { "error", JArray.FromObject(errors) }
                }.ToString();
                return;
            }

            var updated = vendorDataClient.Update(vendorUpdates);

            response.Body = JsonConvert.SerializeObject(updated);
        }
Esempio n. 9
0
        public async Task<IActionResult> OnPostAsync(int channelId)
        {
            ScheduledStream stream = StreamTime.ToModel();

            var channel = await _context.Channels
                .Include(x => x.ScheduledStreams)
                .SingleAsync(x => x.Id == channelId);

            channel.ScheduledStreams.Add(stream);

            var zone = DateTimeZoneProviders.Tzdb[channel.TimeZoneId];
            var version = DateTimeZoneProviders.Tzdb.VersionId;
            ZonedClock zonedClock = _clock.InZone(zone);

            LocalDate today = zonedClock.GetCurrentDate();
            LocalDate next = today.With(DateAdjusters.Next(stream.DayOfWeek));

            
            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = next + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime = next + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = version,
                    UtcStartTime = nextLocalStartDateTime.InZoneLeniently(zone).ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(zone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                next = next.PlusWeeks(1);
            }

            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");

        }
Esempio n. 10
0
 public StatusProvider(IUrlHelper urlHelper, RaidBattlesContext db, ZonedClock clock)
 {
     myUrlHelper = urlHelper;
     myDB        = db;
     myClock     = clock;
 }
Esempio n. 11
0
 public PortalModel(RaidBattlesContext db, ZonedClock clock, IngressClient ingressClient)
 {
     myDb            = db;
     myClock         = clock;
     myIngressClient = ingressClient;
 }
Esempio n. 12
0
 public UrlMessageEntityHandler(TelemetryClient telemetryClient, IHttpClientFactory httpClientFactory, Message message, ZonedClock clock, DateTimeZone timeZoneInfo, ITelegramBotClient bot, PokemonInfo pokemons, GymHelper gymHelper, IOptions <BotConfiguration> botConfiguration)
     : base(telemetryClient, httpClientFactory, entity => entity.Value, clock, timeZoneInfo, pokemons, gymHelper, botConfiguration)
 {
 }
Esempio n. 13
0
 internal SomeClass(ZonedClock clock)
 {
     this.clock = clock;
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Clock"/> class.
 /// </summary>
 /// <param name="dateTimeZone">The date time zone.</param>
 public Clock(DateTimeZone dateTimeZone)
 {
     this.clock        = new ZonedClock(SystemClock.Instance, dateTimeZone, CalendarSystem.Iso);
     this.dateTimeZone = dateTimeZone;
 }
Esempio n. 15
0
        private void SaveReceiptCore(
            Receipt receipt,
            string customerId,
            string firstName,
            string lastName,
            string email,
            Vendor vendor,
            string userIp,
            out ReceiptSaveResult result)
        {
            var existing = ReceiptDbClient.Get(new ReceiptSaveResult {
                Id = receipt.Id
            }, true).Result;

            if (existing != null)
            {
                throw new Exception($"A receipt with id {receipt.Id} has already been sent for processing.");
            }
            var receiptCopyToSave = JsonConvert.DeserializeObject <Receipt>(JsonConvert.SerializeObject(receipt));

            receiptCopyToSave.CardPayment = null;
            result = new ReceiptSaveResult
            {
                Id        = receipt.Id,
                Timestamp = DateTime.UtcNow.ToString("O"),
                Receipt   = receiptCopyToSave,
                Vendor    = vendor,
                CreatedBy = new ReceiptSaveResultUser
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Email     = email,
                    Ip        = userIp
                }
            };
            ReceiptDbClient.Create(result);
            var memo = receipt.Memo;

            if (receipt.MakeCardPayment.GetValueOrDefault())
            {
                var last4 = receipt.CardPayment.CardNumber.Substring(receipt.CardPayment.CardNumber.Length - 4);
                Logger.Log($"{firstName} {lastName} {email} is charging card ending in {last4} ${receipt.ThisPayment:C} on {DateTime.UtcNow:O} for receipt {result.Id}.");
                var chargeResult = CardPayment.Authorize(
                    receipt.ThisPayment * 100,
                    receipt.CardPayment.CardNumber,
                    receipt.CardPayment.ExpirationMonth,
                    receipt.CardPayment.ExpirationYear,
                    receipt.CardPayment.Cvv,
                    receipt.IsCardPresent);
                result.CardAuthorizationResult = chargeResult;
                ReceiptDbClient.Create(result);
                if (chargeResult["error"] != null)
                {
                    return;
                }
            }

            if (receipt.Spots != null && receipt.Spots.Any())
            {
                memo += Environment.NewLine + "Spots: " + string.Join(", ", receipt.Spots.Select(x => $"{x.Section?.Name} - {x.Name}"));
            }

            if (receipt.RentalAmount > 0)
            {
                result.Invoice = QuickBooksClient.Create(CreateInvoice(customerId, receipt.RentalAmount, receipt.RentalDate, memo));
                ReceiptDbClient.Create(result);
            }

            result.Payments = new List <Payment>();
            if (receipt.ThisPayment > 0)
            {
                ZonedClock easternClock = SystemClock.Instance.InZone(DateTimeZoneProviders.Tzdb["America/New_York"]);
                var        paymentMemo  = $"True Payment Date: {easternClock.GetCurrentDate():yyyy-MM-dd}. " +
                                          $"Payment entered by {firstName} {lastName} from IP {userIp}." +
                                          Environment.NewLine + Environment.NewLine + memo;
                var     unpaidInvoices    = QuickBooksClient.QueryAll <Invoice>($"select * from Invoice where Balance != '0' and CustomerRef = '{customerId}' ORDERBY TxnDate");
                decimal payment           = receipt.ThisPayment.GetValueOrDefault();
                var     paymentApplicator = new PaymentApplicator(QuickBooksClient);
                foreach (var unpaidInvoice in unpaidInvoices)
                {
                    var paymentAppliedToInvoice = paymentApplicator.CreatePayment(
                        unpaidInvoice,
                        customerId,
                        payment,
                        $"{easternClock.GetCurrentDate():yyyy-MM-dd}",
                        paymentMemo);
                    result.Payments.Add(paymentAppliedToInvoice);
                    payment -= paymentAppliedToInvoice.TotalAmount.GetValueOrDefault();
                    if (payment <= 0)
                    {
                        break;
                    }
                }
                if (payment > 0)
                {
                    var unappliedPayment = paymentApplicator.CreatePayment(
                        null,
                        customerId,
                        payment,
                        $"{easternClock.GetCurrentDate():yyyy-MM-dd}",
                        paymentMemo
                        );
                    result.Payments.Add(unappliedPayment);
                }
            }
            ReceiptDbClient.Create(result);

            if (receipt.Spots != null)
            {
                result.SpotReservations = new List <SpotReservation>();
                foreach (var spot in receipt.Spots)
                {
                    var spotReservation = new SpotReservation
                    {
                        SpotId             = spot.Id,
                        RentalDate         = receipt.RentalDate,
                        QuickBooksOnlineId = int.Parse(customerId),
                        VendorId           = vendor.Id
                    };
                    SpotReservationDbClient.Create(spotReservation);
                    result.SpotReservations.Add(spotReservation);
                }
            }

            if (receipt.MakeCardPayment.GetValueOrDefault())
            {
                result.CardCaptureResult = CardPayment.Capture(result.CardAuthorizationResult["id"].Value <string>());
                for (var ct = 0; ct < result.Payments.Count; ct++)
                {
                    result.Payments[ct].PrivateNote += Environment.NewLine + Environment.NewLine + $"Card payment confirmation {result.CardAuthorizationResult.ToString(Formatting.Indented)}";
                    result.Payments[ct]              = QuickBooksClient.SparseUpdate(result.Payments[ct]);
                }
            }
            ReceiptDbClient.Create(result);
        }