示例#1
0
 public Reminder(ZonedDateTime due, string message, ulong userId)
 {
     this.DueDateUser = due;
     this.DueDateUTC  = due.ToDateTimeUtc();
     this.Message     = message;
     this.UserId      = userId;
 }
示例#2
0
        /// <summary>
        /// Creates and returns a new <see cref="NewOrderSingle"/> FIX message.
        /// </summary>
        /// <param name="accountNumber">The account number.</param>
        /// <param name="order">The order to submit.</param>
        /// <param name="positionIdBroker">The optional broker position identifier.</param>
        /// <param name="timeNow">The time now.</param>
        /// <returns>The FIX message.</returns>
        public static NewOrderSingle Create(
            AccountNumber accountNumber,
            Order order,
            PositionIdBroker?positionIdBroker,
            ZonedDateTime timeNow)
        {
            Debug.NotDefault(timeNow, nameof(timeNow));

            var message = new NewOrderSingle();

            message.SetField(new ClOrdID(order.Id.Value));
            message.SetField(new Account(accountNumber.Value));
            message.SetField(new Symbol(order.Symbol.Code));
            message.SetField(FxcmMessageHelper.GetFixOrderSide(order.OrderSide));
            message.SetField(FxcmMessageHelper.GetFixOrderType(order.OrderType));
            message.SetField(FxcmMessageHelper.GetFixTimeInForce(order.TimeInForce));
            message.SetField(new OrderQty(order.Quantity.Value));
            message.SetField(new TransactTime(timeNow.ToDateTimeUtc()));

            if (!(positionIdBroker is null))
            {
                message.SetField(new StringField(FxcmTags.PosID, positionIdBroker.Value));
            }

            if (order.ExpireTime.HasValue)
            {
                var expireTime = FxcmMessageHelper.ToExpireTimeFormat(order.ExpireTime.Value);
                message.SetField(new StringField(126, expireTime));
            }

            // Add price
            if (order.Price?.Value != null)
            {
                switch (order.OrderType)
                {
                case OrderType.Limit:
                    message.SetField(new Price(order.Price.Value));
                    break;

                case OrderType.Stop:
                    message.SetField(new StopPx(order.Price.Value));
                    break;

                case OrderType.StopLimit:
                    message.SetField(new StopPx(order.Price.Value));
                    break;

                case OrderType.Market:
                case OrderType.Undefined:
                    goto default;

                default:
                    throw ExceptionFactory.InvalidSwitchArgument(order.OrderType, nameof(order.OrderType));
                }
            }

            return(message);
        }
示例#3
0
    public void Past_with_custom_options()
    {
        var starting = new ZonedDateTime(Instant.FromUtc(2015, 6, 6, 4, 17, 41), DateTimeZone.Utc);

        dataSet.Past(reference: starting, daysToGoBack: 500).ToDateTimeUtc().Should()
        .BeOnOrBefore(starting.ToDateTimeUtc())
        .And
        .BeOnOrAfter(starting.Minus(Duration.FromDays(500)).ToDateTimeUtc());
    }
示例#4
0
    public void Past()
    {
        var starting = new ZonedDateTime(Instant.FromUtc(2015, 6, 6, 4, 17, 41), DateTimeZone.Utc);

        dataSet.Past(reference: starting).ToDateTimeUtc().Should()
        .BeOnOrBefore(starting.ToDateTimeUtc())
        .And
        .BeOnOrAfter(starting.Minus(Duration.FromDays(100)).ToDateTimeUtc());
    }
示例#5
0
    public void Future_with_options()
    {
        var starting = new ZonedDateTime(Instant.FromUtc(2015, 6, 6, 4, 17, 41), DateTimeZone.Utc);

        dataSet.Future(reference: starting, daysToGoForward: 500).ToDateTimeUtc().Should()
        .BeOnOrBefore(starting.Plus(Duration.FromDays(500)).ToDateTimeUtc())
        .And
        .BeOnOrAfter(starting.ToDateTimeUtc());
    }
示例#6
0
    public void Random_time_between_two_dates()
    {
        var start = new ZonedDateTime(Instant.FromUtc(2015, 6, 6, 4, 17, 41), DateTimeZone.Utc);
        var end   = new ZonedDateTime(Instant.FromUtc(2015, 7, 6, 4, 17, 41), DateTimeZone.Utc);

        dataSet.Between(start, end).ToDateTimeUtc()
        .Should()
        .BeOnOrAfter(start.ToDateTimeUtc())
        .And
        .BeOnOrBefore(end.ToDateTimeUtc());

        //and reverse...
        dataSet.Between(end, start).ToDateTimeUtc()
        .Should()
        .BeOnOrAfter(start.ToDateTimeUtc())
        .And
        .BeOnOrBefore(end.ToDateTimeUtc());
    }
示例#7
0
    public void Future()
    {
        var starting = new ZonedDateTime(Instant.FromUtc(2015, 6, 6, 4, 17, 41), DateTimeZone.Utc);

        var zonedDateTime = dataSet.Future(reference: starting).ToDateTimeUtc();

        zonedDateTime.Should()
        .BeOnOrBefore(starting.Plus(Duration.FromDays(100)).ToDateTimeUtc())
        .And
        .BeOnOrAfter(starting.ToDateTimeUtc());
    }
        public long GetDateTimeNano()
        {
            long nano = 0;

            lock (LockObj)
            {
                nano = UCDT.DateTimeToNanoUnix(Time.ToDateTimeUtc());
            }

            return(nano);
        }
示例#9
0
        public void ToDateTimeUtc()
        {
            ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0));
            // Note that this is 10pm the previous day, UTC - so 1am local time
            DateTime expected = new DateTime(2011, 3, 4, 22, 0, 0, DateTimeKind.Utc);
            DateTime actual   = zoned.ToDateTimeUtc();

            Assert.AreEqual(expected, actual);
            // Kind isn't checked by Equals...
            Assert.AreEqual(DateTimeKind.Utc, actual.Kind);
        }
        /// <summary>
        /// Converts the given value object to the specified type, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/>. If null is passed, the current culture is assumed. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <param name="destinationType">The <see cref="T:System.Type"/> to convert the <paramref name="value"/> parameter to. </param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="destinationType"/> parameter is null. </exception>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture,
            [NotNull] object value,
            Type destinationType)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            ZonedDateTime zonedDateTime = (ZonedDateTime)value;

            if (destinationType == typeof(string))
            {
                // ReSharper disable PossibleNullReferenceException
                return(ZonedDateTimePattern.ExtendedFormatOnlyIsoPattern
                       .WithZoneProvider(TimeHelpers.DateTimeZoneProvider)
                       .Format(zonedDateTime));
            }
            // ReSharper restore PossibleNullReferenceException

            if (destinationType == typeof(DateTime))
            {
                return(zonedDateTime.ToDateTimeUtc());
            }

            if (destinationType == typeof(DateTimeOffset))
            {
                return(zonedDateTime.ToDateTimeOffset());
            }

            if (destinationType == typeof(Instant))
            {
                return(zonedDateTime.ToInstant());
            }

            if (destinationType == typeof(LocalDateTime))
            {
                return(zonedDateTime.LocalDateTime);
            }

            if (destinationType == typeof(OffsetDateTime))
            {
                return(zonedDateTime.ToOffsetDateTime());
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
示例#11
0
        public void WhenLastRunStatusError_ReturnsDepthTimes10(int depth)
        {
            var currentDate = new DateTime(2017, 06, 1, 22, 1, 0, DateTimeKind.Utc);
            var date        = new DateCalculator(currentDate, trace)
                              .Calculate(Frequency.Daily, 10, 1.10M, RunStatus.Error, depth);

            var expectedDateTime = new ZonedDateTime(new LocalDateTime(2017, 06, 1, 22, 1, 0), DateTimeZone.Utc,
                                                     Offset.FromHours(0));

            expectedDateTime = expectedDateTime.PlusMinutes(depth * DateCalculator.BackOffInterval);

            Assert.That(date.Value.UtcDateTime, Is.EqualTo(expectedDateTime.ToDateTimeUtc()));
        }
 static EventDateTime ToGoogleEventDateTime(ZonedDateTime dateTime, bool isAllDay)
 {
     return(isAllDay
         ? new EventDateTime
     {
         Date = dateTime.Date.ToString("yyyy-MM-dd", new DateTimeFormatInfo())
     }
         : new EventDateTime
     {
         DateTime = dateTime.ToDateTimeUtc(),
         TimeZone = dateTime.Zone.Id
     });
 }
        /// <summary>
        /// Adds the days taking into account DST.
        /// </summary>
        /// <param name="targetUtc">The target UTC.</param>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="numberOfDays">The number of days.</param>
        /// <returns></returns>
        private DateTime AddDays(DateTime targetUtc, string timeZone, int numberOfDays)
        {
            Instant instant = Instant.FromDateTimeUtc(targetUtc);

            DateTimeZone timeZoneInfo = DateTimeZoneProviders.Tzdb[timeZone];

            ZonedDateTime zoned = instant.InZone(timeZoneInfo);

            LocalDateTime updated = zoned.LocalDateTime.PlusDays(numberOfDays); // Adding a number of days

            ZonedDateTime updatedZoned = timeZoneInfo.AtLeniently(updated);

            return(updatedZoned.ToDateTimeUtc());
        }
示例#14
0
        /// <summary>
        /// Converts a local-time DateTime to UTC DateTime based on the specified
        /// timezone. The returned object will be of UTC DateTimeKind. To be used
        /// when we want to know what's the UTC representation of the time somewhere
        /// in the world.
        /// </summary>
        /// <param name="dateTime">Local DateTime as UTC or Unspecified DateTimeKind.</param>
        /// <returns>UTC DateTime as UTC DateTimeKind.</returns>
        internal static DateTime ToUTC(this DateTime localDateTime)
        {
            if (localDateTime.Kind == DateTimeKind.Local)
            {
                return(localDateTime.ToUniversalTime());
            }

            DateTimeZone  zone         = CultureHelper.GetDateTimeZone();
            LocalDateTime asLocal      = localDateTime.ToLocalDateTime();
            ZonedDateTime asZoned      = asLocal.InZoneLeniently(zone);
            Instant       instant      = asZoned.ToInstant();
            ZonedDateTime asZonedInUtc = instant.InUtc();

            return(asZonedInUtc.ToDateTimeUtc());
        }
示例#15
0
    /// <summary>
    /// Converts a local-time DateTime to UTC DateTime based on the specified
    /// timezone. The returned object will be of UTC DateTimeKind. To be used
    /// when we want to know what's the UTC representation of the time somewhere
    /// in the world.
    /// </summary>
    /// <param name="dateTime">Local DateTime as UTC or Unspecified DateTimeKind.</param>
    /// <param name="timezone">Timezone name (in TZDB format).</param>
    /// <returns>UTC DateTime as UTC DateTimeKind.</returns>
    public static DateTime InZone(this DateTime dateTime, string timezone)
    {
        if (dateTime.Kind == DateTimeKind.Local)
        {
            throw new ArgumentException("Expected non-local kind of DateTime");
        }

        var           zone         = DateTimeZoneProviders.Tzdb[timezone];
        LocalDateTime asLocal      = dateTime.ToLocalDateTime();
        ZonedDateTime asZoned      = asLocal.InZoneLeniently(zone);
        Instant       instant      = asZoned.ToInstant();
        ZonedDateTime asZonedInUtc = instant.InUtc();
        DateTime      utc          = asZonedInUtc.ToDateTimeUtc();

        return(utc);
    }
示例#16
0
        private static string ConvertLocalDateTimeToIso8601(DateTime input, string timeZoneId)
        {
            const string ISO8601format = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK";

            var dateTimeOffset = DateTime.SpecifyKind(input, DateTimeKind.Unspecified);

            var instant = Instant.FromDateTimeOffset(dateTimeOffset);

            var tz       = TimeZoneConverter.TZConvert.WindowsToIana(timeZoneId);
            var timeZone = DateTimeZoneProviders.Tzdb[tz];

            var zonedDateTime = new ZonedDateTime(instant, timeZone);
            var utcDateTime   = zonedDateTime.ToDateTimeUtc();

            return(utcDateTime.ToString(ISO8601format));
        }
示例#17
0
        private DateTime WindowsTimeZone(EventDateTime time)
        {
            DateTime theDate = time.DateTime ?? DateTime.Parse(time.Date);

            if (time.TimeZone == null)
            {
                return(theDate);
            }

            LocalDateTime local     = new LocalDateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute);
            DateTimeZone  zone      = DateTimeZoneProviders.Tzdb[TimezoneDB.FixAlexa(time.TimeZone)];
            ZonedDateTime zonedTime = local.InZoneLeniently(zone);
            DateTime      zonedUTC  = zonedTime.ToDateTimeUtc();

            log.Fine("IANA Timezone \"" + time.TimeZone + "\" mapped to \"" + zone.Id.ToString() + "\" with a UTC of " + zonedUTC.ToString("dd/MM/yyyy HH:mm:ss"));
            return(zonedUTC);
        }
示例#18
0
        /// <summary>
        /// Creates and returns a new <see cref="OrderCancelRequest"/> FIX message.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="transactionTime">The transaction time.</param>
        /// <returns>The FIX message.</returns>
        public static OrderCancelRequest Create(
            Order order,
            ZonedDateTime transactionTime)
        {
            Debug.NotDefault(transactionTime, nameof(transactionTime));

            var message = new OrderCancelRequest();

            message.SetField(new OrigClOrdID(order.Id.Value));
            message.SetField(new OrderID(order.IdBroker?.Value));
            message.SetField(new ClOrdID(order.Id.Value));
            message.SetField(new Symbol(order.Symbol.Code));
            message.SetField(new Quantity(order.Quantity.Value));
            message.SetField(FxcmMessageHelper.GetFixOrderSide(order.OrderSide));
            message.SetField(new TransactTime(transactionTime.ToDateTimeUtc()));

            return(message);
        }
示例#19
0
        private static RequestForPositions Create(ZonedDateTime timeNow, int reqType, AccountNumber account, bool subscribe)
        {
            Debug.NotDefault(timeNow, nameof(timeNow));

            var message = new RequestForPositions();

            message.SetField(new PosReqID($"RP_{timeNow.TickOfDay}"));
            message.SetField(new PosReqType(reqType));
            message.SetField(new Account(account.Value));
            message.SetField(new AccountType(AccountType.ACCOUNT_IS_CARRIED_ON_NON_CUSTOMER_SIDE_OF_BOOKS_AND_IS_CROSS_MARGINED));
            message.SetField(new TradingSessionID(Broker));
            message.SetField(new TransactTime(timeNow.ToDateTimeUtc()));
            message.SetField(subscribe is true
                ? new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES)
                : new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT));

            return(message);
        }
        /// <summary>
        /// Creates and returns a new <see cref="OrderCancelReplaceRequest"/> FIX message.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="modifiedQuantity">The quantity to modify the order to.</param>
        /// <param name="modifiedPrice">The price to modify the order to.</param>
        /// <param name="transactionTime">The transaction time.</param>
        /// <returns>The FIX message.</returns>
        public static OrderCancelReplaceRequest Create(
            Order order,
            decimal modifiedQuantity,
            decimal modifiedPrice,
            ZonedDateTime transactionTime)
        {
            Debug.NotDefault(transactionTime, nameof(transactionTime));

            var message = new OrderCancelReplaceRequest();

            message.SetField(new OrigClOrdID(order.Id.Value));
            message.SetField(new OrderID(order.IdBroker?.Value));
            message.SetField(new ClOrdID(order.Id.Value));
            message.SetField(new Symbol(order.Symbol.Code));
            message.SetField(new Quantity(modifiedQuantity));
            message.SetField(FxcmMessageHelper.GetFixOrderSide(order.OrderSide));
            message.SetField(new TransactTime(transactionTime.ToDateTimeUtc()));
            message.SetField(FxcmMessageHelper.GetFixOrderType(order.OrderType));

            // Set the order price depending on order type.
            switch (order.OrderType)
            {
            case OrderType.Limit:
                message.SetField(new Price(modifiedPrice));
                break;

            case OrderType.StopLimit:
                message.SetField(new StopPx(modifiedPrice));
                break;

            case OrderType.Stop:
                message.SetField(new StopPx(modifiedPrice));
                break;

            case OrderType.Market:
            case OrderType.Undefined:
                goto default;

            default:
                throw ExceptionFactory.InvalidSwitchArgument(order.OrderType, nameof(order.OrderType));
            }

            return(message);
        }
示例#21
0
        /// <summary>
        /// Converts the date time to  UTC time
        /// </summary>
        /// <param name="dt">The date time to convert</param>
        /// <returns>The UTC date time</returns>
        public DateTime Convert(DateTime dt)
        {
            // Fork this method into the use of the current culture to do the utc conversion
            if (UseCurrentCulture)
            {
                CultureInfo currentCulture = CultureInfo.CurrentUICulture;
                RegionInfo  regionInfo     = new RegionInfo(currentCulture.Name);

                IEnumerable <string> zoneIds = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.ZoneLocations
                                               .Where(x => string.Compare(x.CountryCode, regionInfo.TwoLetterISORegionName, StringComparison.OrdinalIgnoreCase) == 0)
                                               .Select(x => x.ZoneId);

                if (!zoneIds.Any())
                {
                    return(dt);
                }

                DateTime dateTime        = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                Instant  dateTimeInstant = Instant.FromDateTimeUtc(dateTime);

                DateTimeZone  timeZone      = DateTimeZoneProviders.Tzdb[zoneIds.FirstOrDefault()];
                ZonedDateTime zonedDateTime = dateTimeInstant.InZone(timeZone);

                DateTime localDateTime = zonedDateTime.ToDateTimeUnspecified();
                return(localDateTime);
            }
            else
            {
                // Get local DateTime instance into a LocalDateTime object
                LocalDateTime localDateTime = new LocalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute);

                // Get the users' time zone
                IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
                DateTimeZone          usersTimezone    = timeZoneProvider[TimeZone];

                // Format the local DateTime instance with the time zones
                ZonedDateTime zonedDbDateTime = localDateTime.InZoneLeniently(usersTimezone);

                // At this point we have all information to convert to UTC: release the kraken!
                return(zonedDbDateTime.ToDateTimeUtc());
            }
        }
        private async Task <List <SensorDataTableEntity> > GetTemperatureDataForDate(ZonedDateTime zonedDateTime)
        {
            var dateTimeZone  = zonedDateTime.Zone;
            var startDateTime = zonedDateTime.ToDateTimeUtc();
            var endDateTime   = zonedDateTime.PlusHours(24).ToDateTimeUtc();

            var requestStartTick = startDateTime.ToTicks();
            var requestEndTick   = endDateTime.ToTicks();

            var operation = new TableQuery <SensorDataTableEntity>()
                            .Where(TableQuery.CombineFilters(
                                       TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, AppSettings.StoragePartitionKey),
                                       TableOperators.And,
                                       TableQuery.CombineFilters(
                                           TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThanOrEqual, requestStartTick),
                                           TableOperators.And,
                                           TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThan, requestEndTick))));

            return((await _table.ExecuteQuerySegmentedAsync(operation, null)).ToList());
        }
示例#23
0
        public async Task <List <TemperatureEntity> > GetTemperatureEntitiesForDate(string location, ZonedDateTime zonedDateTime)
        {
            var dateTimeZone         = zonedDateTime.Zone;
            var requestStartDateTime = zonedDateTime.ToDateTimeUtc();
            var requestEndDateTime   = zonedDateTime.PlusHours(24).ToDateTimeUtc();

            var requestStartReverseTick = requestStartDateTime.ToReverseTicks();
            var requestEndReverseTick   = requestEndDateTime.ToReverseTicks();

            //The nature of ReverseTicks is that the start time is greater than the end time.
            var operation = new TableQuery <TemperatureEntity>()
                            .Where(TableQuery.CombineFilters(
                                       TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, location),
                                       TableOperators.And,
                                       TableQuery.CombineFilters(
                                           TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThanOrEqual, requestStartReverseTick),
                                           TableOperators.And,
                                           TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, requestEndReverseTick))));

            return((await _table.ExecuteQuerySegmentedAsync(operation, null)).ToList());
        }
        /// <summary>
        /// Converts the time to UTC (using IANA (Olson) timezone).
        /// </summary>
        /// <param name="local">The local.</param>
        /// <param name="timezone">IANA (Olson) timezone.</param>
        /// <returns></returns>
        public static DateTime ConvertTimeToUtc(this DateTime local, string timezone)
        {
            if (string.IsNullOrEmpty(timezone))
            {
                throw new ArgumentException(nameof(timezone));
            }

            string tz = DateTimeZoneProviders.Tzdb.Ids.FirstOrDefault(e => e.ToLower() == timezone.ToLower());

            if (string.IsNullOrEmpty(tz))
            {
                throw new ArgumentException(nameof(timezone));
            }

            LocalDateTime localDateTime = LocalDateTime.FromDateTime(local);

            DateTimeZone timezoneInfo = DateTimeZoneProviders.Tzdb[tz];

            ZonedDateTime zoned = timezoneInfo.AtLeniently(localDateTime);

            return(zoned.ToDateTimeUtc());
        }
示例#25
0
        public void ToTimeZoneTests()
        {
            var now      = DateTime.Parse("2016-04-10 10:37:00");
            var actual   = NodaUtility.ToTimeZone(now, "America/New_York", "America/Los_Angeles", TimeSpan.FromHours(-4));
            var la       = DateTime.Parse("2016-04-10 07:37:00");
            var expected = new ZonedDateTime(LocalDateTime.FromDateTime(la), NodaUtility.GetTimeZone("America/Los_Angeles"), Offset.FromHours(-7));

            Assert.AreEqual(expected, actual);
            Assert.AreEqual(expected.ToDateTimeUtc(), actual.ToDateTimeUtc());

            var totalTime = TimeSpan.Zero;

            for (var i = 0; i < 100; i++)
            {
                var timer = Stopwatch.StartNew();
                actual   = NodaUtility.ToTimeZone(now, "America/New_York", "America/Los_Angeles", TimeSpan.FromHours(-4));
                expected = new ZonedDateTime(LocalDateTime.FromDateTime(la), NodaUtility.GetTimeZone("America/Los_Angeles"), Offset.FromHours(-7));
                timer.Stop();
                Assert.AreEqual(expected, actual);
                Assert.AreEqual(expected.ToDateTimeUtc(), actual.ToDateTimeUtc());
                totalTime = totalTime.Add(timer.Elapsed);
            }
            Assert.IsTrue(totalTime < TimeSpan.FromMilliseconds(2));
        }
示例#26
0
        private async Task CheckSchedules()
        {
            while (true)
            {
                foreach (var workspace in Settings.SettingsObject.Workspaces.Workspaces)
                {
                    WorkspaceInfo workspaceInfo = workspace.Value.ToObject <WorkspaceInfo>() !;
                    MongoDatabase database      = new MongoDatabase(workspace.Key, mongoDatabaseLogger);
                    SlackCore     slackApi      = new SlackCore(workspaceInfo.BotToken);
                    var           slackUsers    = await slackApi.UsersList();

                    List <Database.Models.VenmoUser> users = database.GetAllUsers();
                    foreach (var user in users)
                    {
                        if (user.Schedule != null && user.Schedule.Count > 0)
                        {
                            VenmoApi venmoApi    = new VenmoApi(venmoApiLogger);
                            string?  accessToken = await helperMethods.CheckIfVenmoAccessTokenIsExpired(user, venmoApi, database);

                            if (string.IsNullOrEmpty(accessToken))
                            {
                                logger.LogError($"Unable to refresh Venmo access token for {user.UserId}");
                                await WebhookController.SendSlackMessage(workspaceInfo,
                                                                         "Unable to process scheduled Venmos as your token has expired. Please refresh it.",
                                                                         user.UserId, httpClient);

                                continue;
                            }

                            venmoApi.AccessToken = accessToken;
                            bool saveNeeded = false;
                            for (int i = 0; i < user.Schedule.Count; i++)
                            {
                                VenmoSchedule schedule       = user.Schedule[i];
                                Instant       now            = clock.GetCurrentInstant();
                                Instant       scheduledTime  = Instant.FromDateTimeUtc(schedule.NextExecution);
                                bool          deleteSchedule = false;
                                if (now > scheduledTime)
                                {
                                    saveNeeded = true;
                                    await WebhookController.SendSlackMessage(workspaceInfo,
                                                                             $"Processing {schedule.Command}",
                                                                             user.UserId,
                                                                             httpClient);

                                    string[] splitPaymentMessage = helperMethods.ConvertScheduleMessageIntoPaymentMessage(schedule.Command.Split(' '));

                                    ParsedVenmoPayment parsedVenmoPayment;
                                    try
                                    {
                                        parsedVenmoPayment = helperMethods.ParseVenmoPaymentMessage(splitPaymentMessage);
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.LogWarning(ex, "Failed to parse payment, this shouldn't happen as it was parsed before being saved.");
                                        continue;
                                    }

                                    var response = await helperMethods.VenmoPayment(venmoApi, user, database,
                                                                                    parsedVenmoPayment.Amount, parsedVenmoPayment.Note, parsedVenmoPayment.Recipients,
                                                                                    parsedVenmoPayment.Action, parsedVenmoPayment.Audience);

                                    foreach (var r in response.responses)
                                    {
                                        if (!string.IsNullOrEmpty(r.Error))
                                        {
                                            await WebhookController.SendSlackMessage(workspaceInfo,
                                                                                     $"Venmo error: {r.Error}",
                                                                                     user.UserId, httpClient);

                                            continue;
                                        }

                                        if (parsedVenmoPayment.Action == VenmoAction.Charge)
                                        {
                                            await WebhookController.SendSlackMessage(workspaceInfo,
                                                                                     $"Successfully charged {r.Data!.Payment.Target!.User.Username} ${r.Data.Payment.Amount} for {r.Data.Payment.Note}. Audience is {r.Data.Payment.Audience}",
                                                                                     user.UserId, httpClient);
                                        }
                                        else
                                        {
                                            await WebhookController.SendSlackMessage(workspaceInfo,
                                                                                     $"Successfully paid {r.Data!.Payment.Target!.User.Username} ${r.Data.Payment.Amount} for {r.Data.Payment.Note}. Audience is {r.Data.Payment.Audience}",
                                                                                     user.UserId, httpClient);
                                        }
                                    }

                                    foreach (var u in response.unprocessedRecipients)
                                    {
                                        await WebhookController.SendSlackMessage(workspaceInfo,
                                                                                 $"You are not friends with {u}.",
                                                                                 user.UserId, httpClient);
                                    }

                                    if (schedule.Verb == "at" || schedule.Verb == "on")
                                    {
                                        deleteSchedule = true;
                                    }
                                    else if (schedule.Verb == "every")
                                    {
                                        SlackUser?slackUser = helperMethods.GetSlackUser(user.UserId, slackUsers);
                                        if (slackUser == null)
                                        {
                                            // user somehow doesn't exist?
                                            logger.LogError($"While trying to process schedule for a slack user they disappeared? {user.UserId}");
                                            deleteSchedule = true;
                                        }
                                        else
                                        {
                                            ZonedDateTime nextExecution = helperMethods.ConvertScheduleMessageIntoDateTime(
                                                schedule.Command.Split(' '),
                                                slackUser.TimeZone,
                                                clock);
                                            await WebhookController.SendSlackMessage(workspaceInfo,
                                                                                     $"Next execution is {nextExecution.GetFriendlyZonedDateTimeString()}",
                                                                                     user.UserId,
                                                                                     httpClient);

                                            schedule.NextExecution = nextExecution.ToDateTimeUtc();
                                        }
                                    }
                                }

                                if (deleteSchedule)
                                {
                                    user.Schedule.RemoveAt(i);
                                    i--;
                                }
                            }

                            if (saveNeeded)
                            {
                                database.SaveUser(user);
                            }
                        }
                    }
                }

                await Task.Delay(CheckDuration.ToTimeSpan());
            }
        }
 static EventDateTime ToGoogleEventDateTime(ZonedDateTime dateTime, bool isAllDay)
 {
     return isAllDay
         ? new EventDateTime
         {
             Date = dateTime.Date.ToString("yyyy-MM-dd", new DateTimeFormatInfo())
         }
         : new EventDateTime
         {
             DateTime = dateTime.ToDateTimeUtc(),
             TimeZone = dateTime.Zone.Id
         };
 }
示例#28
0
        public void Test_OldRecurringAppointment()
        {
            string gmailUsername;
            string syncProfile;

            LoadSettings(out gmailUsername, out syncProfile);

            EventsResource    service;
            CalendarListEntry primaryCalendar = null;
            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");

            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;

            byte[] jsonSecrets = Properties.Resources.client_secrets;

            //using (var stream = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location) + "\\client_secrets.json", FileMode.Open, FileAccess.Read))
            //using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            //using (var stream = new FileStream(Application.StartupPath + "\\client_secrets.json", FileMode.Open, FileAccess.Read))
            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, scopes, gmailUsername, CancellationToken.None,
                    fDS).Result;

                var initializer = new Google.Apis.Services.BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                var CalendarRequest = new CalendarService(initializer);
                //CalendarRequest.setUserCredentials(username, password);

                var list = CalendarRequest.CalendarList.List().Execute().Items;
                foreach (var calendar in list)
                {
                    if (calendar.Primary != null && calendar.Primary.Value)
                    {
                        primaryCalendar = calendar;
                        break;
                    }
                }

                if (primaryCalendar == null)
                {
                    throw new Exception("Primary Calendar not found");
                }


                //EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full");
                //ToDo: Upgrade to v3, EventQuery query = new EventQuery("https://www.googleapis.com/calendar/v3/calendars/default/events");
                service = CalendarRequest.Events;
            }

            #region Delete previously created test contact.
            var query = service.List(primaryCalendar.Id);
            query.MaxResults = 500;
            query.TimeMin    = DateTime.Now.AddDays(-10);
            query.TimeMax    = DateTime.Now.AddDays(10);
            //query.Q = "GCSM Test Appointment";

            var feed = query.Execute();
            Logger.Log("Loaded Google appointments", EventType.Information);
            foreach (Google.Apis.Calendar.v3.Data.Event entry in feed.Items)
            {
                if (entry.Summary != null && entry.Summary.Contains("GCSM Test Appointment") && !entry.Status.Equals("cancelled"))
                {
                    Logger.Log("Deleting Google appointment:" + entry.Summary + " - " + entry.Start.DateTime.ToString(), EventType.Information);
                    service.Delete(primaryCalendar.Id, entry.Id);
                    Logger.Log("Deleted Google appointment", EventType.Information);
                    //break;
                }
            }



            #endregion

            DateTimeZone zone = DateTimeZoneProviders.Tzdb["Europe/Warsaw"];

            LocalDateTime e1_start       = new LocalDateTime(1970, 10, 14, 10, 0, 0);
            ZonedDateTime e1_start_zoned = e1_start.InZoneLeniently(zone);
            DateTime      e1_start_utc   = e1_start_zoned.ToDateTimeUtc();

            LocalDateTime e1_end       = new LocalDateTime(1970, 10, 14, 11, 0, 0);
            ZonedDateTime e1_end_zoned = e1_start.InZoneLeniently(zone);
            DateTime      e1_end_utc   = e1_start_zoned.ToDateTimeUtc();

            var s = new EventDateTime();
            s.DateTime = e1_start_utc;
            s.TimeZone = "Europe/Warsaw";

            var e = new EventDateTime();
            e.DateTime = e1_end_utc;
            e.TimeZone = "Europe/Warsaw";

            var e1 = new Google.Apis.Calendar.v3.Data.Event()
            {
                Summary    = "Birthday 1",
                Start      = s,
                End        = e,
                Recurrence = new string[] { "RRULE:FREQ=YEARLY;BYMONTHDAY=14;BYMONTH=10" }
            };

            Assert.AreEqual("1970-10-14T09:00:00.000Z", e1.Start.DateTimeRaw);
            var c1 = service.Insert(e1, primaryCalendar.Id).Execute();
            Assert.AreEqual("1970-10-14T10:00:00+01:00", c1.Start.DateTimeRaw);

            LocalDateTime e2_start       = new LocalDateTime(2000, 10, 14, 10, 0, 0);
            ZonedDateTime e2_start_zoned = e2_start.InZoneLeniently(zone);
            DateTime      e2_start_utc   = e2_start_zoned.ToDateTimeUtc();

            LocalDateTime e2_end       = new LocalDateTime(2000, 10, 14, 11, 0, 0);
            ZonedDateTime e2_end_zoned = e2_start.InZoneLeniently(zone);
            DateTime      e2_end_utc   = e2_start_zoned.ToDateTimeUtc();

            var ss = new EventDateTime();
            ss.DateTime = e2_start_utc;
            ss.TimeZone = "Europe/Warsaw";

            var ee = new EventDateTime();
            ee.DateTime = e2_end_utc;
            ee.TimeZone = "Europe/Warsaw";

            var e2 = new Google.Apis.Calendar.v3.Data.Event()
            {
                Summary    = "Birthday 2",
                Start      = ss,
                End        = ee,
                Recurrence = new string[] { "RRULE:FREQ=YEARLY;BYMONTHDAY=14;BYMONTH=10" }
            };

            Assert.AreEqual("2000-10-14T08:00:00.000Z", e2.Start.DateTimeRaw);
            var c2 = service.Insert(e2, primaryCalendar.Id).Execute();
            Assert.AreEqual("2000-10-14T10:00:00+02:00", c2.Start.DateTimeRaw);

            Logger.Log("Created Google appointment", EventType.Information);

            Assert.IsNotNull(c1.Id);

            //delete test contacts
            //service.Delete(primaryCalendar.Id, createdEntry.Id).Execute();

            Logger.Log("Deleted Google appointment", EventType.Information);
        }
示例#29
0
        /// <summary>
        /// Creates and returns a new <see cref="NewOrderList"/> FIX message with contingency orders.
        /// </summary>
        /// <param name="symbolCode">The brokers symbol.</param>
        /// <param name="accountNumber">The account number.</param>
        /// <param name="bracketOrder">The bracket order.</param>
        /// <param name="timeNow">The time now.</param>
        /// <returns>The FIX message.</returns>
        public static NewOrderList CreateWithStopLoss(
            string symbolCode,
            AccountNumber accountNumber,
            BracketOrder bracketOrder,
            ZonedDateTime timeNow)
        {
            Debug.NotEmptyOrWhiteSpace(symbolCode, nameof(symbolCode));
            Debug.NotDefault(timeNow, nameof(timeNow));

            var message = new NewOrderList();

            message.SetField(new ListID(timeNow.TickOfDay.ToString()));
            message.SetField(new TotNoOrders(2));
            message.SetField(new ContingencyType(101));
            message.SetField(new NoOrders(2));
            message.SetField(new BidType(3));
            message.SetField(new TransactTime(timeNow.ToDateTimeUtc()));

            // Order 1
            var entry  = bracketOrder.Entry;
            var order1 = new NewOrderList.NoOrdersGroup();

            order1.SetField(new ClOrdID(entry.Id.Value));
            order1.SetField(new ListSeqNo(0));
            order1.SetField(new ClOrdLinkID("1"));
            order1.SetField(new Account(accountNumber.Value));
            order1.SetField(new Symbol(symbolCode));
            order1.SetField(FxcmMessageHelper.GetFixOrderSide(entry.OrderSide));
            order1.SetField(FxcmMessageHelper.GetFixOrderType(entry.OrderType));
            order1.SetField(FxcmMessageHelper.GetFixTimeInForce(entry.TimeInForce));
            order1.SetField(new OrderQty(entry.Quantity.Value));

            // Add price
            if (entry.Price?.Value != null)
            {
                switch (entry.OrderType)
                {
                case OrderType.Limit:
                    order1.SetField(new Price(entry.Price.Value));
                    break;

                case OrderType.Stop:
                    order1.SetField(new StopPx(entry.Price.Value));
                    break;

                case OrderType.StopLimit:
                    order1.SetField(new StopPx(entry.Price.Value));
                    break;

                case OrderType.Market:
                case OrderType.Undefined:
                    goto default;

                default:
                    throw ExceptionFactory.InvalidSwitchArgument(entry.OrderType, nameof(entry.OrderType));
                }
            }

            // Optional tags
            if (entry.ExpireTime.HasValue)
            {
                var expireTime = FxcmMessageHelper.ToExpireTimeFormat(entry.ExpireTime.Value);
                order1.SetField(new StringField(126, expireTime));
            }

            // Order 2 -----------------------------------------------------------------------------
            var stopLoss = bracketOrder.StopLoss;
            var order2   = new NewOrderList.NoOrdersGroup();

            order2.SetField(new ClOrdID(stopLoss.Id.Value));
            order2.SetField(new ListSeqNo(1));
            order2.SetField(new ClOrdLinkID("2"));
            order2.SetField(new Account(accountNumber.Value));
            order2.SetField(new Symbol(symbolCode));
            order2.SetField(FxcmMessageHelper.GetFixOrderSide(stopLoss.OrderSide));
            order2.SetField(new OrdType(OrdType.STOP));
            order2.SetField(FxcmMessageHelper.GetFixTimeInForce(stopLoss.TimeInForce));
            order2.SetField(new OrderQty(stopLoss.Quantity.Value));

            // Stop-loss orders should always have a stop price
            if (stopLoss.Price?.Value != null)
            {
                order2.SetField(new StopPx(stopLoss.Price.Value));
            }

            message.AddGroup(order1);
            message.AddGroup(order2);

            return(message);
        }
 protected override DateTime GetProperty1Value(ZonedDateTime value) => value.ToDateTimeUtc();