public SortieStatisticCustomTimeSpanGroupViewModel(SortieStatisticViewModel rpOwner) : base(rpOwner, SortieStatisticTimeSpanType.Custom) { var rNow = new DateTimeOffset(DateTime.Now.AddDays(1.0).Date.AddSeconds(-1.0)); r_SelectedDateStart = r_SelectedDateEnd = rNow.DateTime; TimeSpanStart = TimeSpanEnd = rNow.ToUnixTime().ToString(); }
public static Uri History( string method, string fsym, string tsym, int?limit, string e, DateTimeOffset?toTs, bool?allData, int?aggregate, bool?tryConversion) { Check.NotNullOrWhiteSpace(fsym, nameof(fsym)); Check.NotNullOrWhiteSpace(tsym, nameof(tsym)); return(new Uri(MinApiEndpoint, $"histo{method}").ApplyParameters( new Dictionary <string, string> { { nameof(fsym), fsym }, { nameof(tsym), tsym }, { nameof(limit), limit.ToString() }, { nameof(toTs), toTs?.ToUnixTime().ToString(CultureInfo.InvariantCulture) }, { nameof(tryConversion), tryConversion?.ToString() }, { nameof(e), e }, { nameof(allData), allData?.ToString() }, { nameof(aggregate), aggregate?.ToString() } })); }
/// <summary> /// Gets all authorization codes that matches the specified redirect uri and expires after the /// specified date. Called when authenticating an authorization code. /// </summary> /// <param name="redirectUri">The redirect uri.</param> /// <param name="expires">The expire date.</param> /// <returns>The authorization codes.</returns> public virtual async Task <IEnumerable <IAuthorizationCode> > GetAuthorizationCodes(string redirectUri, DateTimeOffset expires) { var db = this.GetDatabase(); var min = expires.ToUnixTime(); var codes = new List <IAuthorizationCode>(); var nonExpiredKeys = db.SortedSetRangeByScore($"{this.Configuration.AuthorizationCodePrefix}:_index:expires", min, DateTimeMax); var redirectUriKeys = db.HashGetAll($"{this.Configuration.AuthorizationCodePrefix}:_index:redirecturi:{redirectUri}"); var unionKeys = nonExpiredKeys.Join(redirectUriKeys, x => x, y => y.Name, (x, y) => x); foreach (var key in unionKeys) { var hashEntries = await db.HashGetAllAsync(key.ToString()); if (hashEntries.Any()) { var code = new RedisAuthorizationCode(hashEntries); if (code.ValidTo > expires) { codes.Add(code); } } } return(codes); }
/// <summary> /// Gets all access tokens for the specified user that expires **after** the specified date. /// Called when authenticating an access token to limit the number of tokens to go through when validating the hash. /// </summary> /// <param name="subject">The subject.</param> /// <param name="expires">The expire date.</param> /// <returns>The access tokens.</returns> public virtual async Task <IEnumerable <IAccessToken> > GetAccessTokens(string subject, DateTimeOffset expires) { var db = this.GetDatabase(); var min = expires.ToUnixTime(); var tokens = new List <IAccessToken>(); var nonExpiredKeys = await db.SortedSetRangeByScoreAsync($"{this.Configuration.AccessTokenPrefix}:_index:expires", min, DateTimeMax); var subjectKeys = await db.HashGetAllAsync($"{this.Configuration.AccessTokenPrefix}:_index:subject:{subject}"); var unionKeys = nonExpiredKeys.Join(subjectKeys, x => x.ToString(), y => y.Name.ToString(), (x, y) => x); foreach (var key in unionKeys) { var hashEntries = await db.HashGetAllAsync(key.ToString()); if (hashEntries.Any()) { var token = new RedisAccessToken(hashEntries); if (token.ValidTo > expires) { tokens.Add(token); } } } return(tokens.Where(x => x.Subject == subject)); }
/// <summary> /// Gets all refresh tokens for the specified user that expires **after** the specified date. /// </summary> /// <param name="subject">The subject.</param> /// <param name="expires">The expire date.</param> /// <returns>The refresh tokens.</returns> public virtual async Task <IEnumerable <IRefreshToken> > GetUserRefreshTokens(string subject, DateTimeOffset expires) { var db = this.GetDatabase(); var min = expires.ToUnixTime(); var tokens = new List <IRefreshToken>(); var keys = db.SortedSetRangeByScore($"{this.Configuration.RefreshTokenPrefix}:_index:expires", min, DateTimeMax); foreach (var key in keys) { var hashEntries = await db.HashGetAllAsync(key.ToString()); if (hashEntries.Any()) { var token = new RedisRefreshToken(hashEntries); if (token.Subject == subject && token.ValidTo > expires) { tokens.Add(token); } } } return(tokens); }
/// <summary>Creates an access token.</summary> /// <param name="clientId">Identifier for the client.</param> /// <param name="redirectUri">The redirect URI.</param> /// <param name="userPrincipal">The user principal.</param> /// <param name="scope">The scope.</param> /// <param name="expireTime">The expire time.</param> /// <returns>An object containing the new access token entity and the hashed token.</returns> public async Task <TokenCreationResult <IRefreshToken> > CreateRefreshToken( string clientId, string redirectUri, ISentinelPrincipal userPrincipal, IEnumerable <string> scope, DateTimeOffset expireTime) { string token; var hashedToken = this.cryptoProvider.CreateHash(out token, 2048); // Add expire claim userPrincipal.Identity.AddClaim(new SentinelClaim(ClaimType.Expiration, expireTime.ToUnixTime().ToString())); var refreshToken = new RefreshToken() { ClientId = clientId, RedirectUri = redirectUri, Subject = userPrincipal.Identity.Name, Scope = scope, Token = hashedToken, ValidTo = expireTime }; return(new TokenCreationResult <IRefreshToken>(token, refreshToken)); }
/// <summary> /// Gets all access tokens that expires **after** the specified date. Called when authenticating /// an access token to limit the number of tokens to go through when validating the hash. /// </summary> /// <param name="expires">The expire date.</param> /// <returns>The access tokens.</returns> public virtual async Task <IEnumerable <IAccessToken> > GetAccessTokens(DateTimeOffset expires) { var db = this.GetDatabase(); var min = expires.ToUnixTime(); var tokens = new List <IAccessToken>(); var nonExpiredKeys = await db.SortedSetRangeByScoreAsync($"{this.Configuration.AccessTokenPrefix}:_index:expires", min, DateTimeMax); foreach (var key in nonExpiredKeys) { var hashEntries = await db.HashGetAllAsync(key.ToString()); if (hashEntries.Any()) { var token = new RedisAccessToken(hashEntries); if (token.ValidTo > expires) { tokens.Add(token); } } } return(tokens); }
/// <summary>Creates an authorization code.</summary> /// <param name="clientId">Identifier for the client.</param> /// <param name="redirectUri">The redirect URI.</param> /// <param name="userPrincipal">The user principal.</param> /// <param name="scope">The scope.</param> /// <param name="expireTime">The expire time.</param> /// <returns>An object containing the new access token entity and the hashed token.</returns> public async Task <TokenCreationResult <IAuthorizationCode> > CreateAuthorizationCode( string clientId, string redirectUri, ISentinelPrincipal userPrincipal, IEnumerable <string> scope, DateTimeOffset expireTime) { string code; var hashedCode = this.cryptoProvider.CreateHash(out code, 256); // Add expire claim userPrincipal.Identity.AddClaim(new SentinelClaim(ClaimType.Expiration, expireTime.ToUnixTime().ToString())); var authorizationCode = new AuthorizationCode() { ClientId = clientId, RedirectUri = redirectUri, Subject = userPrincipal.Identity.Name, Scope = scope, Code = hashedCode, Ticket = this.principalProvider.Encrypt(userPrincipal, code), ValidTo = expireTime }; return(new TokenCreationResult <IAuthorizationCode>(code, authorizationCode)); }
/// <summary> /// Asynchronously retrieves weather data for a particular latitude and longitude, on /// a given day. /// <para> /// Only conditions for the day are given (i.e. the time is ignored, and taken to be the /// current time). /// </para> /// <para> /// Allows specification of units of measurement, language used, extended hourly forecasts, /// and exclusion of data blocks. /// </para> /// </summary> /// <param name="latitude"> /// The latitude to retrieve data for. /// </param> /// <param name="longitude"> /// The longitude to retrieve data for. /// </param> /// <param name="date"> /// The date to retrieve data for. /// </param> /// <param name="unit"> /// The units of measurement to use. /// </param> /// <param name="extends"> /// The type of forecast to retrieve extended results for. Currently limited to hourly blocks. /// </param> /// <param name="excludes"> /// Any blocks that should be excluded from the request. /// </param> /// <param name="language"> /// The language to use for summaries. /// </param> /// <returns> /// A <see cref="Task"/> for a <see cref="Forecast"/> with the requested data, or null if the data was corrupted. /// </returns> public Task <Forecast> GetTimeMachineWeatherAsync( double latitude, double longitude, DateTimeOffset date, Unit unit, IList <Extend> extends, IList <Exclude> excludes, Language language) { ThrowExceptionIfApiKeyInvalid(); var unitValue = unit.ToValue(); var extendList = string.Join(",", extends.Select(x => x.ToValue())); var excludeList = string.Join(",", excludes.Select(x => x.ToValue())); var languageValue = language.ToValue(); var unixTime = date.ToUnixTime(); var requestUrl = string.Format( CultureInfo.InvariantCulture, SpecificTimeConditionsUrl, apiKey, latitude, longitude, unixTime, unitValue, extendList, excludeList, languageValue); return(GetForecastFromUrlAsync(requestUrl)); }
/// <summary> /// The most general method to retrieve the observed (in the past) or forecasted (in the future) hour-by-hour weather and daily weather /// conditions for a particular date. A Time Machine request is identical in structure to a Forecast Request, except: /// * The 'currently' data point will refer to the time provided, rather than the current time. /// * The 'minutely' data block will be omitted, unless you are requesting a time within an hour of the present. /// * The 'hourly data block will contain data points starting at midnight (local time) of the day requested, and continuing /// until midnight (local time) of the following day. /// * The 'daily' data block will contain a single data point referring to the requested date. /// * The 'alerts' data block will be omitted. /// </summary> /// <param name="latitude">The latitude to retrieve data for.</param> /// <param name="longitude">The longitude to retrieve data for.</param> /// <param name="date">Requested date</param> /// <param name="excludes">Any blocks that should be excluded from the request.</param> /// <param name="extends">The type of forecast to retrieve extended results for. Currently limited to hourly blocks.</param> /// <param name="unit">Default <see cref="DSUnit.Auto"/></param> /// <param name="language">Default <see cref="Language.English"/></param> /// <returns>A <see cref="Task"/> for a <see cref="Forecast"/> with the requested data, or null if the data was corrupted.</returns> /// <exception cref="System.Net.Http.HttpRequestException">Thrown when the service returned anything other than a 200 (Status OK) code.</exception> public Task <Forecast> GetWeatherByDate( double latitude, double longitude, DateTimeOffset date, IList <Extend> extends, IList <Exclude> excludes, DSUnit unit = DSUnit.Auto, Language language = Language.English) { ThrowExceptionIfApiKeyInvalid(); var unitValue = unit.ToValue(); var extendList = (extends != null) ? string.Join(",", extends.Select(x => x.ToValue())) : string.Empty; var excludeList = (excludes != null) ? string.Join(",", excludes.Select(x => x.ToValue())) : string.Empty; var languageValue = language.ToValue(); var unixTime = date.ToUnixTime(); var requestUrl = string.Format( CultureInfo.InvariantCulture, SpecificTimeConditionsUrl, _apiKey, latitude, longitude, unixTime, unitValue, extendList, excludeList, languageValue); return(GetForecastFromUrlAsync(requestUrl)); }
public async Task ShouldSerializeCandleData() { var date = new DateTimeOffset(2018, 6, 15, 0, 0, 0, new TimeSpan(0, 0, 0)); var unix = date.ToUnixTime(); var hist = await CryptoCompareClient.Instance.History.HourlyAsync("BTC", "USD", 2, "Coinbase", date); var json = Newtonsoft.Json.JsonConvert.SerializeObject(hist); }
public void ToUnixTime(int expected, int seconds) { // Arrange var input = new DateTimeOffset(1970, 1, 1, 0, 0, seconds, TimeSpan.Zero); // Act var actual = input.ToUnixTime(); // Assert Assert.Equal(expected, actual); }
/// <summary>Adds or updates the specified tag collections with the specified key.</summary> /// <param name="tags">The tags.</param> /// <param name="key">The cache key.</param> /// <param name="expires">The expire time.</param> /// <returns>An async void.</returns> private async Task AddOrUpdateTagIndex(string[] tags, string key, DateTimeOffset expires) { var db = this.configuration.Connection.GetDatabase(); foreach (var tag in tags) { await db.SortedSetAddAsync($"{this.configuration.TagKey}{this.configuration.Separator}{tag}", key, expires.ToUnixTime(), flags : CommandFlags.FireAndForget); } }
bool CheckFileVersionAndTimestamp(ResourceSession rpResourceSession, DateTimeOffset rpTimestamp) { using (var rCommand = r_Connection.CreateCommand()) { rCommand.CommandText = "SELECT (CASE WHEN version IS NOT NULL THEN version ELSE '' END) = @version AND timestamp = @timestamp FROM cache.file WHERE name = @name;"; rCommand.Parameters.AddWithValue("@name", rpResourceSession.Path); rCommand.Parameters.AddWithValue("@version", rpResourceSession.CacheVersion ?? string.Empty); rCommand.Parameters.AddWithValue("@timestamp", rpTimestamp.ToUnixTime()); return(Convert.ToBoolean(rCommand.ExecuteScalar())); } }
public static Uri PriceHistorical( string fsym, IEnumerable <string> tsyms, IEnumerable <string> markets, DateTimeOffset ts, CalculationType?calculationType, bool?tryConversion) { return(new Uri(MinApiEndpoint, "pricehistorical").ApplyParameters( new Dictionary <string, string> { { nameof(fsym), fsym }, { nameof(tsyms), tsyms.ToJoinedList() }, { nameof(ts), ts.ToUnixTime().ToString(CultureInfo.InvariantCulture) }, { nameof(markets), markets?.ToJoinedList() }, { nameof(calculationType), calculationType?.ToString("G") }, { nameof(tryConversion), tryConversion?.ToString() } })); }
/// <summary>Adds or updated the key index with the specified data.</summary> /// <param name="key">The key.</param> /// <param name="expires">The expire time.</param> /// <returns>An async void.</returns> private async Task AddOrUpdateKeyIndex(string key, DateTimeOffset expires) { var db = this.configuration.Connection.GetDatabase(); var score = expires > DateTimeOffset.MinValue ? expires.ToUnixTime() : double.MaxValue; // Update score if key exists, otherwise add it var oldScore = await db.SortedSetScoreAsync(this.configuration.IndexKey, key); if (oldScore.HasValue) { var newScore = (score - oldScore.Value) > DateTimeOffsetExtensions.Epoch.ToUnixTime() ? score - oldScore.Value : DateTimeOffsetExtensions.Epoch.ToUnixTime(); await db.SortedSetIncrementAsync(this.configuration.IndexKey, key, newScore, flags : CommandFlags.FireAndForget); } else { await db.SortedSetAddAsync(this.configuration.IndexKey, key, score, flags : CommandFlags.FireAndForget); } }
public static Uri ExchangeHistory( string method, [NotNull] string tsym, string e, DateTimeOffset?toTs, int?limit, int?aggregate, bool?aggregatePredictableTimePeriods) { Check.NotNullOrWhiteSpace(tsym, nameof(tsym)); return(new Uri(MinApiEndpoint, $"exchange/histo{method}").ApplyParameters( new Dictionary <string, string> { { nameof(tsym), tsym }, { nameof(limit), limit.ToString() }, { nameof(toTs), toTs?.ToUnixTime().ToString(CultureInfo.InvariantCulture) }, { nameof(e), e }, { nameof(aggregate), aggregate?.ToString() }, { nameof(aggregatePredictableTimePeriods), aggregatePredictableTimePeriods?.ToString() } })); }
public void ReturnsRandomDateCorrectly() { var epoch = new DateTimeOffset(1975, 1, 23, 1, 1, 1, TimeSpan.Zero); Assert.Equal(159670861, epoch.ToUnixTime()); }
/// <summary> /// Deletes the refresh tokens that expires before the specified expire date. Called when /// creating a refresh token to cleanup. /// </summary> /// <param name="expires">The expire date.</param> /// <returns>The number of deleted tokens.</returns> public async Task <int> DeleteRefreshTokens(DateTimeOffset expires) { var db = this.GetDatabase(); var tran = db.CreateTransaction(); var keysToDelete = await db.SortedSetRangeByScoreAsync($"{this.Configuration.RefreshTokenPrefix}:_index:expires", 0, expires.ToUnixTime()); // Remove items from indexes tran.SortedSetRemoveRangeByScoreAsync($"{this.Configuration.RefreshTokenPrefix}:_index:expires", 0, expires.ToUnixTime()); // Remove items foreach (var key in keysToDelete) { var data = await db.HashGetAllAsync(key.ToString()); var token = new RedisRefreshToken(data); tran.HashDeleteAsync($"{this.Configuration.RefreshTokenPrefix}:_index:client:{token.ClientId}", key); tran.HashDeleteAsync($"{this.Configuration.RefreshTokenPrefix}:_index:redirecturi:{token.RedirectUri}", key); tran.HashDeleteAsync($"{this.Configuration.RefreshTokenPrefix}:_index:subject:{token.Subject}", key); tran.KeyDeleteAsync(key.ToString()); } var result = await tran.ExecuteAsync(CommandFlags.HighPriority); if (result) { return(keysToDelete.Length); } return(0); }
/// <summary> /// Deletes the authorization codes that expires before the specified expire date. Called when /// creating an authorization code to cleanup. /// </summary> /// <param name="expires">The expire date.</param> /// <returns>The number of deleted codes.</returns> public async Task <int> DeleteAuthorizationCodes(DateTimeOffset expires) { var db = this.GetDatabase(); var tran = db.CreateTransaction(); var keysToDelete = await db.SortedSetRangeByScoreAsync($"{this.Configuration.AuthorizationCodePrefix}:_index:expires", 0, expires.ToUnixTime()); // Remove items from index tran.SortedSetRemoveRangeByScoreAsync($"{this.Configuration.AuthorizationCodePrefix}:_index:expires", 0, expires.ToUnixTime()); // Remove keys foreach (var key in keysToDelete) { var hashEntries = await db.HashGetAllAsync(key.ToString()); if (hashEntries.Any()) { var code = new RedisAuthorizationCode(hashEntries); tran.HashDeleteAsync($"{this.Configuration.AuthorizationCodePrefix}:_index:redirecturi:{code.RedirectUri}", key); } tran.KeyDeleteAsync(key.ToString()); } var result = await tran.ExecuteAsync(CommandFlags.HighPriority); if (result) { return(keysToDelete.Length); } return(0); }
public static void Inc <T>(this ICounter <T> counter, T increment, DateTimeOffset timestamp) where T : struct { counter.Inc(increment, timestamp.ToUnixTime()); }
public void ReturnsUnixEpochCorrectly() { var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); Assert.Equal(0, epoch.ToUnixTime()); }
bool CheckFileVersionAndTimestamp(ResourceSession rpResourceSession, DateTimeOffset rpTimestamp) { using (var rCommand = r_Connection.CreateCommand()) { rCommand.CommandText = "SELECT (CASE WHEN version IS NOT NULL THEN version ELSE '' END) = @version AND timestamp = @timestamp FROM cache.file WHERE name = @name;"; rCommand.Parameters.AddWithValue("@name", rpResourceSession.Path); rCommand.Parameters.AddWithValue("@version", rpResourceSession.CacheVersion ?? string.Empty); rCommand.Parameters.AddWithValue("@timestamp", rpTimestamp.ToUnixTime()); return Convert.ToBoolean(rCommand.ExecuteScalar()); } }
public static void Observe(this IValueObserver observer, double val, DateTimeOffset timestamp) { observer.Observe(val, timestamp.ToUnixTime()); }
public static void Inc(this IGauge gauge, double increment, DateTimeOffset timestamp) { gauge.Inc(increment, timestamp.ToUnixTime()); }
/// <summary> /// Asynchronously retrieves weather data for a particular latitude and longitude, on /// a given day. /// <para> /// Only conditions for the day are given (i.e. the time is ignored, and taken to be the /// current time). /// </para> /// <para> /// Allows specification of units of measurement, language used, extended hourly forecasts, /// and exclusion of data blocks. /// </para> /// </summary> /// <param name="latitude"> /// The latitude to retrieve data for. /// </param> /// <param name="longitude"> /// The longitude to retrieve data for. /// </param> /// <param name="date"> /// The date to retrieve data for. /// </param> /// <param name="unit"> /// The units of measurement to use. /// </param> /// <param name="extends"> /// The type of forecast to retrieve extended results for. Currently limited to hourly blocks. /// </param> /// <param name="excludes"> /// Any blocks that should be excluded from the request. /// </param> /// <param name="language"> /// The language to use for summaries. /// </param> /// <returns> /// A <see cref="Task"/> for a <see cref="Forecast"/> with the requested data, or null if the data was corrupted. /// </returns> public async Task<Forecast> GetTimeMachineWeatherAsync( double latitude, double longitude, DateTimeOffset date, Unit unit, IList<Extend> extends, IList<Exclude> excludes, Language language) { this.ThrowExceptionIfApiKeyInvalid(); var unitValue = unit.ToValue(); var extendList = string.Join(",", extends.Select(x => x.ToValue())); var excludeList = string.Join(",", excludes.Select(x => x.ToValue())); var languageValue = language.ToValue(); var unixTime = date.ToUnixTime(); var requestUrl = string.Format( CultureInfo.InvariantCulture, SpecificTimeConditionsUrl, this.apiKey, latitude, longitude, unixTime, unitValue, extendList, excludeList, languageValue); return await this.GetForecastFromUrl(requestUrl); }
public static void Set(this IGauge gauge, double val, DateTimeOffset timestamp) { gauge.Set(val, timestamp.ToUnixTime()); }
public static void Set(this IUntyped untyped, double val, DateTimeOffset timestamp) { untyped.Set(val, timestamp.ToUnixTime()); }
public static void Dec(this IGauge gauge, double decrement, DateTimeOffset timestamp) { gauge.Dec(decrement, timestamp.ToUnixTime()); }