public async Task <IEnumerable <Activity> > GetAllActivities(DateTimeOffset?startDate, DateTimeOffset?endDate)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await _sessionStorage.GetItemAsync <string>(TokenSessionItem));

            var  activities        = new List <Activity>();
            int  maxPageSize       = 200;
            int  page              = 1;
            bool pageHasActivities = true;

            while (pageHasActivities)
            {
                var tokenParameters = new Dictionary <string, string>
                {
                    { "after", startDate?.ToUnixTimeSeconds().ToString() },
                    { "before", endDate?.ToUnixTimeSeconds().ToString() },
                    { "per_page", $"{maxPageSize}" },
                    { "page", $"{page}" }
                };

                var pageActivitiesStream = _httpClient.GetStreamAsync($"{ActivitiesUri}{await tokenParameters.ToQueryStringAsync()}");
                var pageActivities       = await JsonSerializer.DeserializeAsync <IEnumerable <Activity> >(await pageActivitiesStream);

                activities.AddRange(pageActivities);

                pageHasActivities = pageActivities.Any();
                page++;
            }

            return(activities);
        }
Exemple #2
0
 /// <summary>
 /// 构造自定义节点
 /// </summary>
 /// <param name="name">发送者名</param>
 /// <param name="userId">发送者ID</param>
 /// <param name="customMessage">消息段</param>
 /// <param name="time">消息段转发时间</param>
 public CustomNode(string name, long userId, List <CQCode> customMessage, DateTimeOffset?time = null)
 {
     MessageId = null;
     Name      = name;
     UserId    = userId.ToString();
     Messages  = customMessage.Select(msg => msg.ToOnebotMessage()).ToList();
     Time      = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}";
 }
Exemple #3
0
 /// <summary>
 /// 构造自定义节点
 /// </summary>
 /// <param name="name">发送者名</param>
 /// <param name="userId">发送者ID</param>
 /// <param name="cqString">CQ码字符串格式</param>
 /// <param name="time">消息段转发时间</param>
 public CustomNode(string name, long userId, string cqString, DateTimeOffset?time = null)
 {
     MessageId = null;
     Name      = name;
     UserId    = userId.ToString();
     Messages  = cqString;
     Time      = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}";
 }
        public void ToUnixTimeInSeconds_DateTimeOffset_ShouldMatch()
        {
            var offset = new DateTimeOffset(2016, 1, 8, 4, 11, 28, TimeSpan.FromHours(7));
            var expected = offset.ToUnixTimeSeconds();
            var actual = offset.ToUnixTimeInSeconds();

            Assert.AreEqual(expected, actual);
        }
        public static int GetIdOfFirstPostOfDay(DateTimeOffset day)
        {
            var items = Query(
                $"/2.2/posts",
                $"pagesize=1&order=asc&min={day.ToUnixTimeSeconds()}&max={day.AddDays(1).ToUnixTimeSeconds()}&sort=creation").Result;

            return items[0].post_id;
        }
Exemple #6
0
 public PlatformUserConnectionInfoViewModel(Guid externalPlatformId, string name, string description,
                                            string logoUrl, string websiteUrl, bool isConnected,
                                            PlatformAuthenticationMechanism authMechanism, PlatformConnectionDeleteReason?disconnectedReason, DateTimeOffset?lastDataFetchTimeStamp) : base(externalPlatformId, name, description, logoUrl,
                                                                                                                                                                                            websiteUrl,
                                                                                                                                                                                            authMechanism)
 {
     IsConnected            = isConnected;
     DisconnectedReason     = disconnectedReason;
     LastDataFetchTimeStamp = lastDataFetchTimeStamp?.ToUnixTimeSeconds();
 }
Exemple #7
0
        /// <summary>
        /// Lists all tasks in a workspace
        /// </summary>
        /// <param name="workspaceId">Workspace ID</param>
        /// <param name="active">Specifies whether active and/or archived projects are included in results. If null, uses server default.</param>
        /// <param name="page">Page number</param>
        /// <param name="cancellationToken">Token to observe</param>
        /// <returns></returns>
        public async Task <Models.PagedResult <Models.Task> > ListAsync(long workspaceId, DateTimeOffset?since = null, BothBool?active = null, int page = 1, CancellationToken cancellationToken = default(CancellationToken))
        {
            Utilities.CheckPageArgument(page);
            string uri = $"workspaces/{workspaceId}/tasks" +
                         $"?active={active?.ToTrueFalseBoth()}" +
                         $"&since={since?.ToUnixTimeSeconds()}" +
                         $"&page={page}";

            var result = await _client.Get <Models.PagedResult <Models.Task> >(Apis.TogglV9, uri, cancellationToken);

            return(result);
        }
        ///<summary>
        ///Timebounds constructor.
        ///</summary>
        ///<param name="minTime"> earliest time the transaction is valid from</param>
        ///<param name="maxTime"> latest time the transaction is valid to</param>
        public TimeBounds(DateTimeOffset?minTime = null, DateTimeOffset?maxTime = null)
        {
            if (maxTime != null && minTime >= maxTime)
            {
                throw new ArgumentException("minTime must be >= maxTime");
            }

            var minEpoch = minTime?.ToUnixTimeSeconds() ?? 0;
            var maxEpoch = maxTime?.ToUnixTimeSeconds() ?? 0;

            MinTime = minEpoch;
            MaxTime = maxEpoch;
        }
Exemple #9
0
        public static byte[] EncodeBlockHeader(UInt32 Version, UInt256 PreviousBlock, UInt256 MerkleRoot, DateTimeOffset Time, UInt32 Bits, UInt32 Nonce)
        {
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.WriteUInt32(Version);
                writer.WriteUInt256(PreviousBlock);
                writer.WriteUInt256(MerkleRoot);
                writer.WriteUInt32((uint)Time.ToUnixTimeSeconds());
                writer.WriteUInt32(Bits);
                writer.WriteUInt32(Nonce);

                return stream.ToArray();
            }
        }
Exemple #10
0
        private async Task <AccessToken> GenerateAccessToken(User user)
        {
            try
            {
                var roles = await _userManager.GetRolesAsync(user);

                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token");


                claimsIdentity.AddClaims(roles.Select(role => new Claim(ClaimTypes.Role, role)));

                var key            = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Key"]));
                var creds          = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var expires        = DateTime.Now.AddMinutes(Convert.ToDouble(20));
                var dateTimeOffset = new DateTimeOffset(expires);

                var token = new JwtSecurityToken(
                    _configuration["Issuer"],
                    _configuration["Audience"],
                    claimsIdentity.Claims,
                    expires: expires,
                    signingCredentials: creds
                    );

                return(new AccessToken
                {
                    Token = new JwtSecurityTokenHandler().WriteToken(token),
                    ExpiresIn = dateTimeOffset.ToUnixTimeSeconds() - 30
                });
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #11
0
        private void AddAdmissionDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            //予約枠手動登録ダイアログの登録ボタン
            var title      = AddAdmissionDialogProgramTitle.Text;
            var id         = AddAdmissionDialogProgramID.Text;
            var datePicker = AddAdmissionDialogDatePicker.Date;
            var timePicker = AddAdmissionDialogTimePicker.Time;

            //非表示
            AddAdmissionDialog.Hide();
            if (title != null && id != null && datePicker != null && timePicker != null)
            {
                //Dateに時間追加すりゅ
                var date = DateTime.Parse($"{datePicker.Year}/{datePicker.Month}/{datePicker.Day} {timePicker.Hours}:{timePicker.Minutes}:00");
                //UnixTimeへ
                var unix = new DateTimeOffset(date.Ticks, new TimeSpan(+09, 00, 00));
                //追加する
                autoAdmissionList.addAdmission(title, id, unix.ToUnixTimeSeconds());
            }
        }
Exemple #12
0
        public async Task <ServiceResult> ValidateCode(DateTimeOffset timeOfRequest, CodeVerificationSM sm, string userId)
        {
            if (codeVault.ValidateHash(sm.Code, timeOfRequest.ToUnixTimeSeconds()))
            {
                // Check date of birth.
                var user = await Db.Users.FindAsync(int.Parse(userId));

                if (user.DateOfBirth.Value < DateTime.Today.AddYears(-sm.MinimumAgeRequired))
                {
                    return(ServiceResult);
                }
                else
                {
                    ServiceResult.Errors.Add("User is not old enough");
                    return(ServiceResult);
                }
            }
            ServiceResult.Errors.Add("Code provided is invalid.");
            return(ServiceResult);
        }
        public static void TryBind(this IStatement statement, string name, DateTimeOffset value, bool enableMsPrecision)
        {
            IBindParameter bindParam;

            if (statement.BindParameters.TryGetValue(name, out bindParam))
            {
                if (enableMsPrecision)
                {
                    bindParam.Bind(value.ToUnixTimeMilliseconds());
                }
                else
                {
                    bindParam.Bind(value.ToUnixTimeSeconds());
                }
            }
            else
            {
                CheckName(statement, name);
            }
        }
Exemple #14
0
        public async Task <IEnumerable <TimesheetModel> > Handle(GetTimesheets request, CancellationToken cancellationToken)
        {
            DateTimeOffset startDate = DateTimeOffset.Parse(request.Start, CultureInfo.InvariantCulture);
            DateTimeOffset endDate   = DateTimeOffset.Parse(request.End, CultureInfo.InvariantCulture);

            if (request.Start == request.End)
            {
                endDate = endDate.AddDays(1).AddMinutes(-1);
            }

            var url = new Url(request.TenantUrl)
                      .AppendPathSegment("/Ajax/GetTimesheets")
                      .SetQueryParam("employeeID", request.EmpID)
                      .SetQueryParam("start", startDate.ToUnixTimeSeconds())
                      .SetQueryParam("end", endDate.ToUnixTimeSeconds())
                      // TimePro bug: Basic auth is not base64 decoded on the server and takes the raw token.
                      .WithHeader("Authorization", $"Basic {request.Token}");

            return(await url.GetJsonAsync <TimesheetModel[]>());
        }
Exemple #15
0
        public async Task <(double today, double tomorrow)> GetMaximums(string cityName)
        {
            var city = await GetForecast(cityName);

            var dtoToday            = new DateTimeOffset(DateTime.Today.ToUniversalTime());
            var dtoTomorrow         = new DateTimeOffset(DateTime.Today.AddDays(1).ToUniversalTime());
            var dtoDayAfterTomorrow = new DateTimeOffset(DateTime.Today.AddDays(2).ToUniversalTime());

            var todayMax = city.List.Where
                               (_ => _.Dt >= dtoToday.ToUnixTimeSeconds() &&
                               _.Dt <= dtoTomorrow.ToUnixTimeSeconds())
                           .Max(_ => _.Main.Temp);

            var tomorrowMax = city.List.Where
                                  (_ => _.Dt >= dtoTomorrow.ToUnixTimeSeconds() &&
                                  _.Dt <= dtoDayAfterTomorrow.ToUnixTimeSeconds())
                              .Max(_ => _.Main.Temp);

            return(todayMax, tomorrowMax);
        }
Exemple #16
0
        // to unitime
        /*
        public static int UnixTime(DateTime now)
        {
            //(long)new DateTime(1970, 1, 1, 9, 0, 0, 0).ToFileTimeUtc();
            return (int)(now.ToFileTimeUtc() / 10000000 - 11644506000L);
        }
        */
        private void Form1_Load(object sender, EventArgs e)
        {
            string dt_str = "";

            // unixtime : date
            this.label2.Text = "^:UnixTime  v:DateTime";

            DateTime now_unix_time_dt = DateTime.Now;
            TimeSpan ts = new TimeSpan(0, 0, 0, 0);
            now_unix_time_dt = now_unix_time_dt + ts;

            dt_str = now_unix_time_dt.ToString();
            this.textBox2.Text = dt_str;

            var dto = new DateTimeOffset(now_unix_time_dt, new TimeSpan(+09, 00, 00));
            var dtot = dto.ToUnixTimeSeconds();

            dt_str = dtot.ToString();
            this.textBox1.Text = dt_str;
        }
Exemple #17
0
    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        _followerCount    = 0;
        _oldFollowerCount = _followerCount;
        _rawFollowerCount = _followerCount;
        Money             = 50;
        _oldMoney         = Money;
        _currentDate      = new DateTimeOffset(new DateTime(2012, 12, 22));

        _gui        = GetParent().GetNode <Gui>("GUI/GUI");
        _cashJingle = GetParent().GetNode <AudioStreamPlayer>("CashJingle");
        GetParent().GetNode <AudioStreamPlayer>("Music").Play();

        Connect(nameof(FollowersChange), _gui, "OnFollowerUpdate");
        EmitSignal(nameof(FollowersChange), _followerCount);
        Connect(nameof(MoneyChanges), _gui, "OnMoneyUpdate");
        EmitSignal(nameof(MoneyChanges), Money);
        Connect(nameof(DateChanges), _gui, "OnDateUpdate");
        EmitSignal(nameof(DateChanges), _currentDate.ToUnixTimeSeconds());
        Connect(nameof(RatesUpdated), _gui, "OnRatesUpdated");
        Connect(nameof(Victory), _gui, "OnVictory");


        // Setup global upgrades
        using (var file = new File()) {
            file.Open("res://upgradeData.json", File.ModeFlags.Read);
            var upgradeScene = (PackedScene)ResourceLoader.Load("res://scenes/Upgrade.tscn");

            _upgrades = new List <Upgrade>();
            var upgradesData = JsonConvert.DeserializeObject <UpgradeData[]>(file.GetAsText());

            // Initialise upgrades
            foreach (var upgradeData in upgradesData.Where(u => u.Global))
            {
                var upgrade = (Upgrade)(upgradeScene.Instance());
                _upgrades.Add(upgrade);
                _gui.UpgradesElement.AddChild(upgrade);
                upgrade.Initialise(upgradeData, this);
            }
        }
    }
Exemple #18
0
        void updateServiceInfo()
        {
            try {
                var dbc            = Program.GetConnection();
                var inventoryIndex = (comboBoxInventory.SelectedItem as InventoryInfo).id;
                var dto            = new DateTimeOffset(dateTimePicker1.Value);
                var date           = dto.ToUnixTimeSeconds();

                var comm = new SQLiteCommand($"select * from Service where inventory = {inventoryIndex} AND date < {date} ORDER BY date DESC", dbc);
                var lst  = new List <string>();
                using (SQLiteDataReader read = comm.ExecuteReader()) {
                    while (read.Read())
                    {
                        var service_date = (long)read["date"];

                        var dto2 = DateTimeOffset.FromUnixTimeSeconds(service_date);
                        lst.Add((string)read["description"]);

                        if (lst.Count == 1)
                        {
                            textBoxSericeInfoDate.Text = dto2.LocalDateTime.ToShortDateString();

                            var commDist = new SQLiteCommand($"select sum(distance) from workout where inventory = {inventoryIndex} AND datetime >= {service_date}", dbc);
                            var dist     = commDist.ExecuteScalar();
                            textBoxSericeInfoDist.Text = (dist != null && !(dist is DBNull) ? (double)dist : 0).ToString();
                        }
                    }
                }


                if (lst.Count > 0)
                {
                    textBoxServiceInfo.Text = lst[0];
                }
                else
                {
                    textBoxSericeInfoDist.Text = textBoxSericeInfoDate.Text = textBoxServiceInfo.Text = "";
                }
            } catch (Exception) {
            }
        }
        public AllMetrics <NetworkMetric> GetByTimeIntervalPercentile(
            int agentId,
            DateTimeOffset fromTime,
            DateTimeOffset toTime,
            Percentile percentile)
        {
            var metrics = new AllMetrics <NetworkMetric>();

            using (var connection = new SQLiteConnection(mySql.ConnectionString))
            {
                try
                {
                    metrics.Metrics = connection.Query <NetworkMetric>(
                        "SELECT * " +
                        $"FROM {mySql[Tables.NetworkMetric]} " +
                        $"WHERE (" +
                        $"{mySql[Columns.AgentId]} == @agentId) " +
                        $"AND {mySql[Columns.Time]} >= @fromTime " +
                        $"AND {mySql[Columns.Time]} <= @toTime " +
                        $"ORDER BY {mySql[Columns.Value]}",
                        new
                    {
                        agentId  = agentId,
                        fromTime = fromTime.ToUnixTimeSeconds(),
                        toTime   = toTime.ToUnixTimeSeconds(),
                    }).ToList();
                }
                catch (Exception ex)
                {
                    _logger.LogDebug(ex.Message);
                }
            }

            var percentileIndex = ((int)percentile * metrics.Metrics.Count / 100);

            var returnMetrics = new AllMetrics <NetworkMetric>();

            returnMetrics.Metrics.Add(metrics.Metrics[percentileIndex - 1]);

            return(returnMetrics);
        }
Exemple #20
0
        public DynamoDbMetastoreImplTest(DynamoDBContainerFixture dynamoDbContainerFixture)
        {
            AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig
            {
                ServiceURL = dynamoDbContainerFixture.ServiceUrl
            };

            amazonDynamoDbClient = new AmazonDynamoDBClient(clientConfig);

            CreateTableRequest request = new CreateTableRequest
            {
                TableName            = TableName,
                AttributeDefinitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition(PartitionKey, ScalarAttributeType.S),
                    new AttributeDefinition(SortKey, ScalarAttributeType.N)
                },
                KeySchema = new List <KeySchemaElement>
                {
                    new KeySchemaElement(PartitionKey, KeyType.HASH),
                    new KeySchemaElement(SortKey, KeyType.RANGE)
                },
                ProvisionedThroughput = new ProvisionedThroughput(1L, 1L)
            };

            CreateTableResponse createTableResponse = amazonDynamoDbClient.CreateTableAsync(request).Result;

            table = Table.LoadTable(amazonDynamoDbClient, TableName);

            JObject  jObject  = JObject.FromObject(keyRecord);
            Document document = new Document
            {
                [PartitionKey]       = TestKey,
                [SortKey]            = created.ToUnixTimeSeconds(),
                [AttributeKeyRecord] = Document.FromJson(jObject.ToString())
            };

            Document result = table.PutItemAsync(document).Result;

            dynamoDbMetastoreImpl = new DynamoDbMetastoreImpl(amazonDynamoDbClient);
        }
Exemple #21
0
        public async Task <IActionResult> CreateInclAsync([FromForm] CreateInclSensorDto createInclSensorDto)
        {
            try
            {
                if (!_mqttClient.IsConnected)
                {
                    await _mqttClient.ConnectAsync(_clientOptions);
                }

                if (createInclSensorDto.X != null)
                {
                    _logger.LogInformation("X: {0}; Y: {1}", createInclSensorDto.X[0], createInclSensorDto.Y[0]);
                    var info = new SensorInfo(createInclSensorDto.PER, createInclSensorDto.VOLT, createInclSensorDto.CSQ);
                    var meas = createInclSensorDto.X.Select((x, i) => new InclSensorMeas(x, createInclSensorDto.Y[i], createInclSensorDto.T[i], createInclSensorDto.TS[i]));
                    var msg  = new Message(info, meas);

                    var str = JsonConvert.SerializeObject(msg);

                    var message = new MqttApplicationMessageBuilder()
                                  .WithTopic("legacy/incl/" + createInclSensorDto.UID)
                                  .WithPayload(str)
                                  .WithAtMostOnceQoS()
                                  .Build();

                    await _mqttClient.PublishAsync(message);
                }

                var dateNow        = DateTime.Now;
                var dateTimeOffset = new DateTimeOffset(dateNow);
                var unixDateTime   = dateTimeOffset.ToUnixTimeSeconds();

                return(Ok(String.Format("UID={0}, ST={1}, TS={2}, SPER={3}, MPER={4}, IGVAL={5},CRVAL={6},", createInclSensorDto.UID, createInclSensorDto.ST, unixDateTime, 1200, 10, 2, 150)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
            await _mqttClient.DisconnectAsync();

            return(StatusCode(StatusCodes.Status500InternalServerError));
        }
Exemple #22
0
            public async Task ReturnsOnlyTheTimeEntriesWhichAreBetweenTheStartAndEndDates()
            {
                var(api, user) = await SetupTestUser();

                var timeEntryA = createTimeEntry(user, start.AddDays(-1));
                var timeEntryB = createTimeEntry(user, start.AddDays(1));
                var timeEntryC = createTimeEntry(user, end.AddDays(1));
                await api.TimeEntries.Create(timeEntryA);

                await api.TimeEntries.Create(timeEntryB);

                await api.TimeEntries.Create(timeEntryC);

                var list = await api.TimeEntries.GetAll(start, end);

                list.Should().HaveCount(1);
                var item = list[0];

                item.Start.ToUnixTimeSeconds().Should().BeGreaterOrEqualTo(start.ToUnixTimeSeconds());
                item.Start.ToUnixTimeSeconds().Should().BeLessThan(end.ToUnixTimeSeconds());
            }
        public void DateTimeOffsetAttributeGetDefault_Success(long value)
        {
            string           attrName = "AttrA";
            VaultSecretEntry vseA     = new VaultSecretEntry();

            DateTimeOffset aDate = new DateTimeOffset();

            aDate = DateTimeOffset.FromUnixTimeSeconds(value);

            // Save value
            vseA.SetDateTimeOffsetAttribute(attrName, aDate);

            // Get Value
            DateTimeOffset answer = vseA.GetDateTimeOffsetAttributeDefault(attrName);

            Assert.NotNull(answer, "A10:  Expected a DateTime, not a Null value");

            long unixTimeSeconds = answer.ToUnixTimeSeconds();

            Assert.AreEqual(value, unixTimeSeconds);
        }
Exemple #24
0
        public SignalRAccessInfo GetSignalRServiceAccessInfo(string userId, TimeSpan lifetime)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return(null);
            }
            IEnumerable <Claim> claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId)
            };
            string         url    = signalRServiceUtils.GetClientUrl(signalROptions.HubName);
            DateTimeOffset expire = DateTimeOffset.UtcNow.Add(lifetime);
            string         token  = signalRServiceUtils.GenerateAccessToken(url, claims, expire.UtcDateTime);

            return(new SignalRAccessInfo
            {
                Url = url,
                Token = token,
                Expire = expire.ToUnixTimeSeconds()
            });
        }
        public virtual async Task <DetailsResult> GetPaymentDetailsAsync(string merchantPaymentId, string nonce)
        {
            DateTimeOffset timestamp = DateTimeOffset.UtcNow;
            long           epoc      = timestamp.ToUnixTimeSeconds();

            string body        = string.Empty;
            string contentType = string.Empty;
            string path        = $"/v2/codes/payments/{merchantPaymentId}";
            string method      = "GET";

            var headerAuthorizationObject = this.GetHeaderAuthorizationObject(body, contentType, path, method, nonce, epoc);
            var authorization             = new AuthenticationHeaderValue("hmac", headerAuthorizationObject);

            var result = await this.GetAsync($"{this.Uri}{path}", authorization, this.MerchantId);

            var responseContent = await result.Content.ReadAsStringAsync();

            var response = JsonConvert.DeserializeObject <DetailsResult>(responseContent);

            return(response);
        }
Exemple #26
0
        /* This class is responsible for taking the value gotten from the
         * dateTimePicker, converts to the unixTimeseconds format,uses this value as
         * a threshold and compare it with the values gotten from the
         * GetUsernamesSortedByRecordDate Method then return a list of
         * the Authors that match the criteria
         */
        private void Btn_RecordDate_Click(object sender, EventArgs e)
        {
            var            theTime   = this.datePicker.Value;
            DateTimeOffset offset    = new DateTimeOffset(theTime);
            int            threshold = (int)offset.ToUnixTimeSeconds();

            textBox.Text = string.Empty;
            try
            {
                var name = AddImplementation.GetUsernamesSortedByRecordDate(threshold);
                for (var i = 0; i < name.Count; i++)
                {
                    // print values gotten to the textBox and arrange them in new Lines(list format)
                    textBox.Text += name[i] + Environment.NewLine;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Input Threshold");
            }
        }
        public Contact GetContact()
        {
            if (!IsValidInput())
            {
                return(null);
            }

            DateTimeOffset timeOffet = new DateTimeOffset(birthDatePicker.SelectedDate ?? DateTime.Now);

            Contact contact = new Contact
            {
                Name      = nameTextBox.Text,
                WorkPhone = workPhoneTextBox.Text,
                HomePhone = homePhoneTextBox.Text,
                Email     = emailTextBox.Text,
                BirthDate = timeOffet.ToUnixTimeSeconds(),
                Comment   = commentTextBox.Text
            };

            return(contact);
        }
        private decimal TimeseriesSummary(Dictionary <long, decimal> index, DateTimeOffset intervalStartTime, DateTimeOffset intervalEndTime)
        {
            long    intervalStart = intervalStartTime.ToUnixTimeSeconds();
            long    intervalEnd   = intervalEndTime.ToUnixTimeSeconds();
            decimal lastValue     = 0;
            decimal sum           = 0;
            long    instant       = intervalStart;

            while (instant <= intervalEnd)
            {
                if (index.ContainsKey(instant))
                {
                    var value = index[instant];
                    lastValue = value;
                }
                sum += lastValue;
                instant++;
            }

            return(sum);
        }
Exemple #29
0
        private TokenResponse GenerateToken(string username)
        {
            DateTimeOffset dtExpired = new DateTimeOffset(DateTime.Now.AddDays(1));

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, dtExpired.ToUnixTimeSeconds().ToString()),
            };

            var token = new JwtSecurityToken(
                new JwtHeader(new SigningCredentials(new SymmetricSecurityKey(SecurityHelpers.GetSharedKey()), SecurityAlgorithms.HmacSha256)),
                new JwtPayload(claims));

            TokenResponse response = new TokenResponse();

            response.ExpiredDate = dtExpired;
            response.Token       = new JwtSecurityTokenHandler().WriteToken(token);
            return(response);
        }
Exemple #30
0
        /// <summary>
        /// Get a list of recent bills
        /// </summary>
        /// <returns>List of BillInfo (short)</returns>
        public async Task <AtomicPayResponse <BillingList <BillInfo> > > GetBillsAsync(DateTimeOffset startDate, DateTimeOffset endDate, BillingStatus billingStatus = BillingStatus.All)
        {
            VerifyAuthentication();

            var request = new HttpRequestMessage()
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri(Constants.GetEp_Billing(_apiVersion).
                                     AddParameterToUrl(Constants.PARAM_DateStart, startDate.ToUnixTimeSeconds()).
                                     AddParameterToUrl(Constants.PARAM_DateEnd, endDate.ToUnixTimeSeconds()).
                                     AddParameterToUrl(Constants.PARAM_Status, billingStatus.ToString().ToLowerInvariant()))
            };

            var response = await _client.SendAsync(request).ConfigureAwait(false);

            var json = await response.Content.ReadAsStringAsync();

            return(new AtomicPayResponse <BillingList <BillInfo> >(response, false, new List <Newtonsoft.Json.JsonConverter> {
                StringToBillingStatusConverter.Instance
            }));
        }
        public void Run()
        {
            var dateTime       = DateTime.Now;
            var dateTimeOffset = new DateTimeOffset(dateTime);
            var unixDateTime   = dateTimeOffset.ToUnixTimeSeconds();

            Console.WriteLine($"Run Start lastInsertDate : {dateTimeOffset.ToLocalTime().ToString()}");

            BsonValue lastInsertDate = new BsonTimestamp((int)unixDateTime, 1);

            while (true)
            {
                BsonValue lastId = BsonMinKey.Value;

                List <OpLog> oplogs = _mongoOpLogManager.TailCollection(lastInsertDate);

                if (oplogs != null && oplogs.Count > 0)
                {
                    Console.WriteLine($"==============================================\n");
                    Console.WriteLine($"oplogs.Count : {oplogs.Count}");
                    lastInsertDate = _connectorIntermediary.Run(oplogs);
                    Console.WriteLine($"==============================================\n");
                }
                else
                {
                    Console.WriteLine($"oplogs is empty");

                    dateTime       = DateTime.Now;
                    dateTimeOffset = new DateTimeOffset(dateTime);
                    unixDateTime   = dateTimeOffset.ToUnixTimeSeconds();

                    lastInsertDate = new BsonTimestamp((int)unixDateTime, 1);
                }
                Console.WriteLine($"lastInsertDate : {lastInsertDate.ToString()}");
                Console.WriteLine($"current Time : {DateTime.Now.ToString()}");
                Console.WriteLine("\n");

                System.Threading.Thread.Sleep(3000);
            }
        }
Exemple #32
0
        static void Main(string[] args)
        {
            /*
             * //https://docs.microsoft.com/zh-tw/dotnet/api/system.datetimeoffset.fromunixtimeseconds?view=net-5.0
             * DateTimeOffset offset = DateTimeOffset.FromUnixTimeSeconds(20);
             * Console.WriteLine("DateTimeOffset = {0}", offset);
             * Console.WriteLine("DateTimeOffset (other format) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss}", offset);
             */

            /*
             * //https://docs.microsoft.com/zh-tw/dotnet/api/system.datetimeoffset.tounixtimeseconds?view=net-5.0
             * DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
             * Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds());
             *
             * dto = new DateTimeOffset(1969, 12, 31, 23, 59, 0, TimeSpan.Zero);
             * Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds());
             *
             * dto = new DateTimeOffset(1970, 1, 1, 0, 1, 0, TimeSpan.Zero);
             * Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds());
             */

            DateTimeOffset dto00 = new DateTimeOffset(DateTime.Now);

            Console.WriteLine("{0} --> Unix Seconds_00: {1}", dto00, dto00.ToUnixTimeSeconds());           //long
            Console.WriteLine("{0} --> Unix Milliseconds_00: {1}", dto00, dto00.ToUnixTimeMilliseconds()); //long

            Console.WriteLine("");

            DateTimeOffset dto01 = new DateTimeOffset(DateTime.UtcNow);//https://currentmillis.com/

            byte[] byteArray   = System.Text.Encoding.Default.GetBytes((dto01.ToUnixTimeMilliseconds() + 200000).ToString());
            byte[] byteArray16 = new byte[16];
            Array.Copy(byteArray, byteArray16, byteArray.Length);

            Console.WriteLine("{0} --> Unix Seconds_01: {1}", dto01, dto01.ToUnixTimeSeconds());                                //long
            Console.WriteLine("{0} --> Unix Milliseconds_01: {1}", dto01, dto01.ToUnixTimeMilliseconds() + 200000);             //long
            Console.WriteLine("{0} --> Unix Milliseconds_01: {1}", dto01, System.Text.Encoding.Default.GetString(byteArray16)); //long

            Pause();
        }
Exemple #33
0
    private void OnClickOkButton()
    {
        switch (_currentSettingType)
        {
        case SettingType.Save:

            var dateTimeOffset = new DateTimeOffset(DateTime.Now, new TimeSpan(+09, 00, 00));
            _currentUserData.time = dateTimeOffset.ToUnixTimeSeconds();

            for (int i = 0; i < _userDataList.Count; i++)
            {
                if (_userDataList[i].slotId == _currentSelectSlot)
                {
                    _userDataList[i] = _currentUserData;


                    break;
                }
            }
            var png = CreateReadabeTexture2D(cacheScreenShot.texture).EncodeToPNG();
            File.WriteAllBytes(RESOURCES_SCREEN_SHOT_PATH + _currentSelectSlot.ToString(), png);

            PlayerPrefsUtil.SetValue <UserData[]>(KEY_USER_DATA_LIST, _userDataList.ToArray());
            UpdateGameDataPanel();

            break;

        case SettingType.Load:

            var loadUserData = _userDataList.FirstOrDefault(data => data.slotId == _currentSelectSlot);

            _onChangeState(GameState.InitMain, new Dictionary <string, object>()
            {
                { "userData", loadUserData }
            });

            break;
        }
        _objConfirmation.gameObject.SetActive(false);
    }
Exemple #34
0
        public async Task <GuidDTO> Handle(GetGUIDQuery request, CancellationToken cancellationToken)
        {
            GuidMetadata entity;
            var          cacheKey      = request.Id;
            var          cacheMetadata = _distributedCache.GetString(cacheKey);

            if (!string.IsNullOrEmpty(cacheMetadata))
            {
                //parse metadata and create rich domain object
                string[] metadata = cacheMetadata.Split('|');
                entity = new GuidMetadata(request.Id, Convert.ToInt64(metadata[0]), metadata[1]);
            }
            else
            {
                //get entity from database
                try
                {
                    entity = await _context.GUIDs.SingleAsync(c => c.Id == request.Id, cancellationToken);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //update cache
                cacheMetadata = entity.Expire + "|" + entity.User;
                _distributedCache.SetString(cacheKey, cacheMetadata);
            }

            //check expired
            DateTime       dateTime       = DateTime.UtcNow;
            DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime.ToLocalTime());

            if (dateTimeOffset.ToUnixTimeSeconds() > entity.Expire)
            {
                throw new ExpiredException();
            }

            return(GuidDTO.Create(entity));
        }
Exemple #35
0
        // クリップボードにテキストがコピーされると呼び出される
        private void OnClipBoardChanged(object sender, ClipboardEventArgs args)
        {
            string input_str;
            int i = 0;

            this.textBox1.Text = args.Text;
            input_str = this.textBox1.Text;

            // unixtime or datetime を確認
            DateTime dt;
            if (DateTime.TryParse(input_str, out dt))
            {
                // date -> unixtime
                this.label2.Text = "DateTime -> UnixTime";

                var dto = new DateTimeOffset(dt, new TimeSpan(+09, 00, 00));
                var dtot = dto.ToUnixTimeSeconds();

                string dt_str = dtot.ToString();
                this.textBox2.Text = dt_str;

            }
            else if ( int.TryParse(input_str, out i) )
            {
                // unixtime -> date
                this.label2.Text = "UnixTime -> DateTime";

                //int input_int = int.Parse(input_str);

                var dto = (DateTimeOffset.FromUnixTimeSeconds(int.Parse(input_str)).ToLocalTime());

                string dt_str = dto.ToString();
                this.textBox2.Text = dt_str;

            }
            else
            {
                this.label2.Text = "DateTimeに変換できません。";
                this.textBox2.Text = "";
            }
        }
Exemple #36
0
        async Task<int> GetStackOverflowReputation(DateTimeOffset start, DateTimeOffset end, int firstPostIdToConsider)
        {
            dynamic items = await QueryHelpers.Query(
                $"/2.2/users/{StackOverflowID}/reputation",
                $"fromdate={start.ToUnixTimeSeconds()}&todate={end.ToUnixTimeSeconds()}");

            int reputation = 0;
            foreach (var item in items)
            {
                // Ignore if the post that the event is attached to is too old
                if (item.post_id < firstPostIdToConsider)
                    continue;

                if (item.vote_type == "up_votes")
                {
                    if (item.post_type == "answer")
                    {
                        reputation += 10;
                    }
                    else
                    {
                        // No points for upvotes on questions
                    }
                }
                else if (item.vote_type == "accepts")
                {
                    reputation += 20;
                }
                else
                {
                    // We ignore bounties
                }
            }

            return reputation;
        }