Here are the examples of the csharp api System.DateTimeOffset.ToUnixTimeSeconds() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
588 Examples
19
Source : StudentController.cs
with Apache License 2.0
from ccnetcore
with Apache License 2.0
from ccnetcore
[HttpGet]
public Result Login(string role)
{
string userName = "admin";
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Role,role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: JwtConst.Domain,
audience: JwtConst.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenData = new JwtSecurityTokenHandler().WriteToken(token);
return Result.Success("欢迎你!管理员!").SetData(new { token = tokenData });
}
19
Source : StudentController.cs
with Apache License 2.0
from ccnetcore
with Apache License 2.0
from ccnetcore
[HttpGet]
public Result Login(string role)
{
string userName = "admin";
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Role,role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: JwtConst.Domain,
audience: JwtConst.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenData= new JwtSecurityTokenHandler().WriteToken(token);
return Result.Success("欢迎你!管理员!").SetData(new { token= tokenData });
}
19
Source : MakeJwt.cs
with Apache License 2.0
from ccnetcore
with Apache License 2.0
from ccnetcore
public static string app(jwtUser _user)
{
//通过查询权限,把所有权限加入进令牌中
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
claims.Add(new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"));
claims.Add(new Claim(ClaimTypes.Name, _user.user.username));
claims.Add(new Claim(ClaimTypes.Sid, _user.user.id.ToString()));
foreach (var k in _user?.menuIds)
{
claims.Add(new Claim("menuIds",k.id.ToString()));
}
foreach (var k in _user.user.roles)
{
claims.Add(new Claim(ClaimTypes.Role, k.role_name));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: JwtConst.Domain,
audience: JwtConst.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenData = new JwtSecurityTokenHandler().WriteToken(token);
return tokenData;
}
19
Source : userBll.cs
with Apache License 2.0
from ccnetcore
with Apache License 2.0
from ccnetcore
public async Task<Result> login(user data)
{
//通过查询权限,把所有权限加入进令牌中
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
claims.Add(new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"));
claims.Add(new Claim(ClaimTypes.Name, data.username));
claims.Add(new Claim("Id", data.id.ToString()));
var actions = await getActionByUserId(data.id);
foreach (var k in actions)
{
claims.Add(new Claim("action", k.action_name));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: JwtConst.Domain,
audience: JwtConst.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenData = new JwtSecurityTokenHandler().WriteToken(token);
return Result.Success("登录成功!").SetData(new { token = tokenData, user = new { id = data.id, username = data.username, level = data.user_extra.level, icon = data.icon } });
}
19
Source : Timestamp.cs
with Apache License 2.0
from census-instrumentation
with Apache License 2.0
from census-instrumentation
public static Timestamp FromDateTimeOffset(DateTimeOffset time)
{
long seconds = 0;
#if NET45
var unixZero = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
seconds = (int)Math.Floor(time.Subtract(unixZero).TotalSeconds);
#else
seconds = time.ToUnixTimeSeconds();
#endif
int nanos = (int)time.Subtract(new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).Subtract(TimeSpan.FromSeconds(seconds)).Ticks * 100;
return Timestamp.Create(seconds, nanos);
}
19
Source : AlphaContext.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
private async Task Cleanup(Dictionary<byte[], WithdrawalWrapper> withdrawals)
{
byte[][] expiredTransactions = null;
var currentTimeSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
expiredTransactions = withdrawals.Where(w => w.Value.IsExpired(currentTimeSeconds)).Select(w => w.Key).ToArray();
if (expiredTransactions.Length < 1)
return;
//we must ignore all transactions that was submitted. TxListener will handle submitted transactions.
var unhandledTxs = await GetUnhandledTx();
foreach (var expiredTransaction in expiredTransactions.Where(tx => !unhandledTxs.Contains(tx, ByteArrayComparer.Default)))
_ = QuantumHandler.HandleAsync(new WithrawalsCleanupQuantum { ExpiredWithdrawal = expiredTransaction }.CreateEnvelope());
}
19
Source : PriceHistoryPeriodManager.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
private async Task<List<PriceHistoryFrame>> GetUnit(DateTime unitDate, bool isCurrentFrame = false)
{
if (!framesUnit.TryGetValue<List<PriceHistoryFrame>>(unitDate, out var frames))
{
var semapreplaced = locks.GetOrAdd(unitDate, (d) => new SemapreplacedSlim(1));
await semapreplaced.WaitAsync();
try
{
if (!framesUnit.TryGetValue(unitDate, out frames))
{
var nextUnitDate = GetFramesNextUnitStart(unitDate);
var toTimeStamp = (int)((DateTimeOffset)nextUnitDate).ToUnixTimeSeconds();
var unixTimeStamp = (int)((DateTimeOffset)unitDate).ToUnixTimeSeconds();
var rawFrames = await replacedyticsStorage.GetPriceHistory(unixTimeStamp, toTimeStamp, Market, Period);
frames = rawFrames.Select(f => f.FromModel()).OrderByDescending(f => f.StartTime).ToList();
foreach (var f in frames)
{
if (f.StartTime < unitDate || f.StartTime >= nextUnitDate || f.Market != Market)
break;
}
framesUnit.Set(unitDate, frames, GetMemoryCacheEntryOptions(isCurrentFrame, frames.Count));
}
}
finally
{
semapreplaced.Release();
}
}
return frames;
}
19
Source : WithdrawalRequestProcessor.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
private void ValidateTransaction(WithdrawalProcessorContext context)
{
var transaction = context.Transaction;
var txSourceAccount = transaction.SourceAccount;
if (ByteArrayPrimitives.Equals(context.CentaurusContext.Constellation.Vault.Data, txSourceAccount.PublicKey))
throw new BadRequestException("Vault account cannot be used as transaction source.");
if (transaction.TimeBounds == null || transaction.TimeBounds.MaxTime <= 0)
throw new BadRequestException("Max time must be set.");
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (transaction.TimeBounds.MaxTime - currentTime > 1000)
throw new BadRequestException("Transaction expiration time is to far.");
if (transaction.Operations.Any(o => !(o is PaymentOperation)))
throw new BadRequestException("Only payment operations are allowed.");
if (transaction.Operations.Length > 100)
throw new BadRequestException("Too many operations.");
}
19
Source : PriceHistoryFrameExtensions.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
public static PriceHistoryFrameModel ToFrameModel(this PriceHistoryFrame frame)
{
if (frame is null)
throw new ArgumentNullException(nameof(frame));
var id = PriceHistoryExtensions.EncodeId(frame.Market, (int)frame.Period, (int)((DateTimeOffset)frame.StartTime).ToUnixTimeSeconds());
return new PriceHistoryFrameModel
{
Id = id,
Open = frame.Open,
Close = frame.Close,
Low = frame.Low,
High = frame.High,
BaseVolume = frame.BaseVolume,
CounterVolume = frame.CounterVolume
};
}
19
Source : PriceHistoryManager.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
public async Task<(List<PriceHistoryFrame> frames, int nextCursor)> GetPriceHistory(int cursor, int market, PriceHistoryPeriod framePeriod)
{
var managerId = EncodereplacedetTradesResolution(market, framePeriod);
var cursorDate = cursor == 0 ? default : DateTimeOffset.FromUnixTimeSeconds(cursor).UtcDateTime;
var res = await managers[managerId].GetPriceHistoryForDate(cursorDate);
return (
res.frames,
nextCursor: (res.nextCursor == default ? 0 : (int)((DateTimeOffset)res.nextCursor).ToUnixTimeSeconds())
);
}
19
Source : SmartTransaction.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public string ToLine()
{
// GetHash is also serialized, so file can be interpreted with our eyes better.
return string.Join(
':',
GetHash(),
Transaction.ToHex(),
Height,
BlockHash,
BlockIndex,
Label,
FirstSeen.ToUnixTimeSeconds(),
IsReplacement);
}
19
Source : E2ETests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
private WebHostServerFixture<Startup> Create(Dictionary<string, string> config,
Action<IServiceCollection> additionalServiceConfig = null)
{
return new WebHostServerFixture<Startup>(builder =>
{
builder.ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder.AddInMemoryCollection(config);
}).ConfigureServices(
collection =>
{
additionalServiceConfig?.Invoke(collection);
collection.Replace(ServiceDescriptor.Singleton<IDataDirProvider>(_ =>
new TestDataDirProvider($"{DateTimeOffset.Now.ToUnixTimeSeconds()}_{Guid.NewGuid()}")));
});
});
}
19
Source : HashCashUtils.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public static string GenerateChallenge(string subject, DateTimeOffset expiry, int difficulty)
{
return
$"H:{difficulty}:{expiry.ToUnixTimeSeconds()}:{subject}:SHA-256:{Convert.ToBase64String(Encoding.UTF8.GetBytes(GenerateString(5)))}";
}
19
Source : DateTimeOffsetUnixSecondsConverter.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTimeOffset)value).ToUnixTimeSeconds());
}
19
Source : SendPushService.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
private string GenerateAuthenticationHeader()
{
var headerBytes = JsonSerializer.SerializeToUtf8Bytes(new {
alg = "ES256",
kid = _auth_key_id
});
var header = Convert.ToBase64String(headerBytes);
var claimsBytes = JsonSerializer.SerializeToUtf8Bytes(new
{
iss = _teamId,
iat = DateTimeOffset.Now.ToUnixTimeSeconds()
});
var claims = Convert.ToBase64String(claimsBytes);
var p8KeySpan = GetBytesFromPem(_keyPath);
var signer = ECDsa.Create();
signer.ImportPkcs8PrivateKey(p8KeySpan, out _);
var dataToSign = Encoding.UTF8.GetBytes($"{header}.{claims}");
var signatureBytes = signer.SignData(dataToSign, HashAlgorithmName.SHA256);
var signature = Convert.ToBase64String(signatureBytes);
return $"{header}.{claims}.{signature}";
}
19
Source : ExtPubKeyExplorerTests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[Fact]
public void ShouldFindNeverUsedKey()
{
var filters = new[]
{
FilterModel.FromLine($"0:000000000000de90e633e1b1330859842795d39018d033044e8b003e8cbf58e4:050a2f58828c9820642769ae320a40:{uint256.One}:{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}")
};
var unusedKeyIndex = ExtPubKeyExplorer.GetUnusedBech32Keys(1, true, ExtPubKey.GetWif(Network.Main), filters).First().ScriptPubKey.ToCompressedBytes();
replacedert.Equal(DerivateScript(true, 0), unusedKeyIndex);
}
19
Source : SmartTransactionTests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[Fact]
public void FirstSeenBackwardsCompatibility()
{
var now = DateTimeOffset.UtcNow;
DateTimeOffset twoThousandEight = new DateTimeOffset(2008, 1, 1, 0, 0, 0, TimeSpan.Zero);
DateTimeOffset twoThousandNine = new DateTimeOffset(2009, 1, 1, 0, 0, 0, TimeSpan.Zero);
// Compatbile with FirstSeenIfMempoolTime json property.
// FirstSeenIfMempoolTime is null.
var serialized = "{\"FirstSeenIfMempoolTime\": null, \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
var deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(now.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeenIfMempoolTime is empty.
serialized = "{\"FirstSeenIfMempoolTime\": \"\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(now.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeenIfMempoolTime is value.
serialized = "{\"FirstSeenIfMempoolTime\": \"" + twoThousandEight.ToString(CultureInfo.InvariantCulture) + "\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(twoThousandEight.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeen is null.
serialized = "{\"FirstSeen\": \"" + twoThousandEight.ToUnixTimeSeconds() + "\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(twoThousandEight.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeen is empty.
serialized = "{\"FirstSeen\": \"\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(now.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeen is real value.
serialized = "{\"FirstSeen\": \"" + twoThousandEight.ToUnixTimeSeconds() + "\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(twoThousandEight.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeen and FirstSeenIfMempoolTime are both missing.
serialized = "{\"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(now.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
// FirstSeen and FirstSeenIfMempoolTime are both provided.
serialized = "{\"FirstSeen\": \"" + twoThousandEight.ToUnixTimeSeconds() + "\", \"FirstSeenIfMempoolTime\": \"" + twoThousandNine.ToString(CultureInfo.InvariantCulture) + "\", \"Transaction\":\"02000000040aa8d0af84518df6e3a60c5bb19d9c3fcc3dc6e26b2f2449e8d7bf8d3fe84b87010000006a473044022018dfe9216c1209dd6c2b6c1607dbac4e499c1fce4878bc7d5d83fccbf3e24c9402202cac351c9c6a2b5eef338cbf0ec000d8de1c05e96a904cbba2b9e6ffc2d4e19501210364cc39da1091b1a9c12ec905a14a9e8478f951f7a1accdabeb40180533f2eaa5feffffff112c07d0f5e0617d720534f0b2b84dc0d5b7314b358c3ab338823b9e5bfbddf5010000006b483045022100ec155e7141e74661ee511ae980150a6c89261f31070999858738369afc28f2b6022006230d2aa24fac110b74ef15b84371486cf76c539b335a253c14462447912a300121020c2f41390f031d471b22abdb856e6cdbe0f4d74e72c197469bfd54e5a08f7e67feffffff38e799b8f6cf04fd021a9b135cdcd347da7aac4fd8bb8d0da9316a9fb228bb6e000000006b483045022100fc1944544a3f96edd8c8a9795c691e2725612b5ab2e1c999be11a2a4e3f841f1022077b2e088877829edeada0c707a9bb577aa79f26dafacba3d1d2d047f52524296012102e6015963dff9826836400cf8f45597c0705757d5dcdc6bf734f661c7dab89e69feffffff64c3f0377e86625123f2f1ee229319ed238e8ca8b7dda5bc080a2c5ecb984629000000006a47304402204233a90d6296182914424fd2901e16e6f5b13b451b67b0eec25a5eaacc5033c902203d8a13ef0b494c12009663475458e51da6bd55cc67688264230ece81d3eeca24012102f806d7152da2b52c1d9ad928e4a6253ccba080a5b9ab9efdd80e37274ac67f9bfeffffff0290406900000000001976a91491ac4e49b66f845180d98d8f8be6121588be6e3b88ac52371600000000001976a9142f44ed6749e8c84fd476e4440741f7e6f55542fa88acadd30700\",\"Height\":\"2147483646\"}";
deserialized = JsonConvert.DeserializeObject<SmartTransaction>(serialized);
replacedert.Equal(twoThousandEight.UtcDateTime, deserialized.FirstSeen.UtcDateTime, TimeSpan.FromSeconds(1));
}
19
Source : DefaultTypeConverter.Setup.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
private static void RegisterDateTimeConversions(
DefaultTypeConverter registry)
{
registry.Register<DateTimeOffset, DateTime>(
from => from.UtcDateTime);
registry.Register<DateTime, DateTimeOffset>(
from => (DateTimeOffset)from);
registry.Register<DateTimeOffset, long>(
from => from.ToUnixTimeSeconds());
registry.Register<long, DateTimeOffset>(
from => DateTimeOffset.FromUnixTimeSeconds(from));
registry.Register<DateTime, long>(
from => ((DateTimeOffset)from).ToUnixTimeSeconds());
registry.Register<long, DateTime>(
from => DateTimeOffset.FromUnixTimeSeconds(from).UtcDateTime);
registry.Register<DateTimeOffset, string>(
from =>
{
if (from.Offset == TimeSpan.Zero)
{
return from.ToString(
_utcFormat,
CultureInfo.InvariantCulture);
}
return from.ToString(
_localFormat,
CultureInfo.InvariantCulture);
});
registry.Register<DateTime, string>(
from =>
{
var offset = new DateTimeOffset(from);
if (offset.Offset == TimeSpan.Zero)
{
return offset.ToString(
_utcFormat,
CultureInfo.InvariantCulture);
}
return offset.ToString(
_localFormat,
CultureInfo.InvariantCulture);
});
}
19
Source : LibraryHelper.cs
with GNU General Public License v3.0
from CircuitLord
with GNU General Public License v3.0
from CircuitLord
public double DateTimeToUnixTimeStamp(DateTime dateTime) {
return ((DateTimeOffset) dateTime).ToUnixTimeSeconds();
}
19
Source : Asset.cs
with GNU Affero General Public License v3.0
from citizenfx
with GNU Affero General Public License v3.0
from citizenfx
public bool Save(string replacedetPath)
{
if (Dictionary == null)
{
throw new Exception("Attempt to save replacedet with no Dictionary");
}
if (LoadType != replacedetLoadType.Full)
{
throw new Exception("Attempt to save a non-fully loaded replacedets");
}
Dictionary.Save(replacedetPath);
string lastUpdated = DateTimeOffset.Now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
replacedetFile replacedetFile = new replacedetFile
{
replacedetName = Name,
LastUpdated = lastUpdated,
DictionaryName = Dictionary.Name,
LastExportPath = LastExportPath,
ExportName = ExportName,
Clips = Clips.ToArray()
};
string jsonString = JsonSerializer.Serialize(replacedetFile, new JsonSerializerOptions
{
WriteIndented = true
});
string filePath = Path.Combine(replacedetPath, Constants.replacedetManifestName);
string dictionaryPath = Path.Combine(replacedetPath, Dictionary.Name);
File.WriteAllText(filePath, jsonString);
if (!Directory.Exists(dictionaryPath))
{
_ = Directory.CreateDirectory(dictionaryPath);
}
return true;
}
19
Source : DiscordRateLimitPolicyTests.cs
with MIT License
from Color-Chan
with MIT License
from Color-Chan
[TestCase("234", "1", "78545.234", "64.57", "asfd4ytvbnt67ig", "guilds/54678568456", "GET")]
[TestCase("10", "1", "34576.123", "64.57", "abcd1234", "guilds/67894563456", "POST")]
[TestCase("4234234", "1", "46.453", "234.456", "asdgf3w6sdfgsgxcvb", "guilds/789567345", "PUT")]
[TestCase("2342343", "1", "3456.678", "12323.56", "kgh567dhncvbne4t", "guilds/2345345656786789", "PATCH")]
[TestCase("645645", "1", "57645.345", "2345.2", "abxcvb45y4y3457hkhjljk;cd1234", "guilds/678945673456233452", "DELETE")]
public async Task Should_prevent_rateLimit(string limit, string remaining, string resetAt, string resetAfter, string id, string endpoint, string method)
{
// Arrange
var services = new ServiceCollection()
.AddColorChanCache()
.AddLogging()
.BuildServiceProvider();
var restConfig = new OptionsWrapper<RestConfiguration>(new RestConfiguration());
var policy = new DiscordRateLimitPolicy(services.GetRequiredService<ICacheService>(), services.GetRequiredService<ILogger<DiscordRateLimitPolicy>>(), restConfig);
var context = new Context { { "endpoint", endpoint }, { "method", method } };
var message = new HttpResponseMessage();
message.StatusCode = HttpStatusCode.OK;
// Time span should always be in the future.
var resetAtTimeSpan = DateTimeOffset.UtcNow.AddSeconds(double.Parse(resetAt, CultureInfo.InvariantCulture));
var headers = message.Headers;
headers.Add("X-RateLimit-Limit", limit);
headers.Add("X-RateLimit-Remaining", remaining);
headers.Add("X-RateLimit-Reset", resetAtTimeSpan.ToUnixTimeSeconds().ToString());
headers.Add("X-RateLimit-Reset-After", resetAfter);
headers.Add("X-RateLimit-Bucket", id);
// Act
await policy.ExecuteAsync((_, _) => Task.FromResult(message), context, new CancellationToken()); // 2 remaining
headers.Remove("X-RateLimit-Remaining");
headers.Add("X-RateLimit-Remaining", (int.Parse(remaining) - 1).ToString());
await policy.ExecuteAsync((_, _) => Task.FromResult(message), context, new CancellationToken()); // 1 remaining
var result = await policy.ExecuteAsync((_, _) => Task.FromResult(message), context, new CancellationToken()); // 0 remaining
// replacedert
result.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
}
19
Source : MessageProvider.cs
with GNU General Public License v3.0
from CommentViewerCollection
with GNU General Public License v3.0
from CommentViewerCollection
private static long GetCurrentUnixTime()
{
var dto = new DateTimeOffset(GetCurrent().Ticks, new TimeSpan(9, 0, 0));
return dto.ToUnixTimeSeconds();
}
19
Source : GameContext.cs
with MIT License
from CommitteeOfZero
with MIT License
from CommitteeOfZero
private static bool ValidateBytecodeCache(
string nssFolder,
string bytecodeCacheDir,
string startupScript)
{
static string getModulePath(string rootDir, string fullPath)
{
return Path.ChangeExtension(
Path.GetRelativePath(rootDir, fullPath),
extension: null
);
}
string startupModule = getModulePath(
rootDir: nssFolder,
Path.Combine(nssFolder, startupScript)
);
foreach (string nssFile in Directory
.EnumerateFiles(nssFolder, "*.nss", SearchOption.AllDirectories))
{
string currentModule = getModulePath(rootDir: nssFolder, nssFile);
string nsxPath = Path.ChangeExtension(
Path.Combine(bytecodeCacheDir, currentModule),
"nsx"
);
try
{
using (FileStream nsxStream = File.OpenRead(nsxPath))
{
long nsxTimestamp = NsxModule.GetSourceModificationTime(nsxStream);
long nssTimestamp = new DateTimeOffset(File.GetLastWriteTimeUtc(nssFile))
.ToUnixTimeSeconds();
if (nsxTimestamp != nssTimestamp)
{
return false;
}
}
}
catch
{
if (currentModule.Equals(startupModule, StringComparison.Ordinal))
{
return false;
}
}
}
return true;
}
19
Source : SourceReferenceResolver.cs
with MIT License
from CommitteeOfZero
with MIT License
from CommitteeOfZero
public override long GetModificationTimestamp(ResolvedPath path)
{
return new DateTimeOffset(File.GetLastWriteTimeUtc(path.Value), TimeSpan.Zero)
.ToUnixTimeSeconds();
}
19
Source : BMBFConfig.cs
with GNU General Public License v3.0
from ComputerElite
with GNU General Public License v3.0
from ComputerElite
public void Init()
{
this.PlaylistId = PlaylistName + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
}
19
Source : JwtHelper.cs
with Apache License 2.0
from CoreUnion
with Apache License 2.0
from CoreUnion
public static string IssueJwt(TokenModelJwt tokenModel)
{
string iss = AppSettingsConstVars.JwtConfigIssuer;
string aud = AppSettingsConstVars.JwtConfigAudience;
string secret = AppSettingsConstVars.JwtConfigSecretKey;
//var claims = new Claim[] //old
var claims = new List<Claim>
{
/*
* 特别重要:
1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法,或者在整个解决方案,搜索这个方法,看哪里使用了!
2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
*/
new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
//这个就是过期时间,目前是过期1000秒,可自定义,注意JWT有自己的缓冲过期时间
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()),
new Claim(JwtRegisteredClaimNames.Iss,iss),
new Claim(JwtRegisteredClaimNames.Aud,aud)
//new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
};
// 可以将一个用户的多个角色全部赋予;
// 作者:DX 提供技术支持;
claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwt = new JwtSecurityToken(
issuer: iss,
claims: claims,
signingCredentials: creds);
var jwtHandler = new JwtSecurityTokenHandler();
var encodedJwt = jwtHandler.WriteToken(jwt);
return encodedJwt;
}
19
Source : RefreshWeChatAccessTokenJob.cs
with Apache License 2.0
from CoreUnion
with Apache License 2.0
from CoreUnion
public async System.Threading.Tasks.Task Execute()
{
try
{
//微信公众号刷新
if (!string.IsNullOrEmpty(_weChatOptions.WeiXinAppId) && !string.IsNullOrEmpty(_weChatOptions.WeiXinAppSecret))
{
var enreplacedy = await _weChatAccessTokenServices.QueryByClauseAsync(p => p.appId == _weChatOptions.WeiXinAppId && p.appType == (int)GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken);
if (enreplacedy == null || enreplacedy.expireTimestamp <= DateTimeOffset.Now.ToUnixTimeSeconds())
{
var client = _weChatApiHttpClientFactory.CreateWeXinClient();
var request = new CgibinTokenRequest();
var response = await client.ExecuteCgibinTokenAsync(request);
if (!response.IsSuccessful())
{
//插入日志
var log = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = false,
name = "定时刷新获取微信AccessToken",
parameters = $"刷新 AppId 为 {_weChatOptions.WeiXinAppId} 微信 AccessToken 失败(状态码:{response.RawStatus},错误代码:{response.ErrorCode},错误描述:{response.ErrorMessage})。"
};
await _taskLogServices.InsertAsync(log);
}
else
{
// 提前十分钟过期,以便于系统能及时刷新,防止因在过期临界点时出现问题
long nextExpireTimestamp = DateTimeOffset.Now.AddSeconds(response.ExpiresIn).AddMinutes(-10).ToUnixTimeSeconds();
if (enreplacedy == null)
{
enreplacedy = new WeChatAccessToken();
enreplacedy.appId = _weChatOptions.WeiXinAppId;
enreplacedy.accessToken = response.AccessToken;
enreplacedy.appType = (int)GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken;
enreplacedy.expireTimestamp = nextExpireTimestamp;
enreplacedy.createTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
enreplacedy.updateTimestamp = enreplacedy.createTimestamp;
enreplacedy.id = await _weChatAccessTokenServices.InsertAsync(enreplacedy);
}
else
{
enreplacedy.accessToken = response.AccessToken;
enreplacedy.expireTimestamp = nextExpireTimestamp;
enreplacedy.updateTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
await _weChatAccessTokenServices.UpdateAsync(enreplacedy);
}
await _redisOperationRepository.Set(GlobalEnumVars.AccessTokenEnum.WeiXinAccessToken.ToString(), enreplacedy, TimeSpan.FromMinutes(120));
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "定时刷新获取微信AccessToken",
parameters = JsonConvert.SerializeObject(enreplacedy)
};
await _taskLogServices.InsertAsync(model);
}
}
else
{
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "定时刷新获取微信AccessToken",
parameters = "无需刷新AccessToken,AccessToken 未过期"
};
await _taskLogServices.InsertAsync(model);
}
}
//微信小程序也刷新
if (!string.IsNullOrEmpty(_weChatOptions.WxOpenAppId) && !string.IsNullOrEmpty(_weChatOptions.WxOpenAppSecret))
{
var enreplacedy = await _weChatAccessTokenServices.QueryByClauseAsync(p => p.appId == _weChatOptions.WxOpenAppId && p.appType == (int)GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken);
if (enreplacedy == null || enreplacedy.expireTimestamp <= DateTimeOffset.Now.ToUnixTimeSeconds())
{
var client = _weChatApiHttpClientFactory.CreateWxOpenClient();
var request = new CgibinTokenRequest();
var response = await client.ExecuteCgibinTokenAsync(request);
if (response.IsSuccessful())
{
// 提前十分钟过期,以便于系统能及时刷新,防止因在过期临界点时出现问题
long nextExpireTimestamp = DateTimeOffset.Now.AddSeconds(response.ExpiresIn).AddMinutes(-10).ToUnixTimeSeconds();
if (enreplacedy == null)
{
enreplacedy = new WeChatAccessToken();
enreplacedy.appId = _weChatOptions.WxOpenAppId;
enreplacedy.accessToken = response.AccessToken;
enreplacedy.appType = (int)GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken;
enreplacedy.expireTimestamp = nextExpireTimestamp;
enreplacedy.createTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
enreplacedy.updateTimestamp = enreplacedy.createTimestamp;
await _weChatAccessTokenServices.InsertAsync(enreplacedy);
}
else
{
enreplacedy.accessToken = response.AccessToken;
enreplacedy.expireTimestamp = nextExpireTimestamp;
enreplacedy.updateTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
await _weChatAccessTokenServices.UpdateAsync(enreplacedy);
}
await _redisOperationRepository.Set(
GlobalEnumVars.AccessTokenEnum.WxOpenAccessToken.ToString(), enreplacedy,
TimeSpan.FromMinutes(120));
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "定时刷新获取微信AccessToken",
parameters = JsonConvert.SerializeObject(enreplacedy)
};
await _taskLogServices.InsertAsync(model);
}
else
{
//插入日志
var log = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = false,
name = "定时刷新获取微信AccessToken",
parameters = $"刷新 AppId 为 {_weChatOptions.WeiXinAppId} 微信 AccessToken 失败(状态码:{response.RawStatus},错误代码:{response.ErrorCode},错误描述:{response.ErrorMessage})。"
};
await _taskLogServices.InsertAsync(log);
}
}
else
{
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "定时刷新获取微信AccessToken",
parameters = "无需刷新AccessToken,AccessToken 未过期"
};
await _taskLogServices.InsertAsync(model);
}
}
}
catch (Exception ex)
{
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = false,
name = "定时刷新获取微信AccessToken",
parameters = JsonConvert.SerializeObject(ex)
};
await _taskLogServices.InsertAsync(model);
}
}
19
Source : TimeStampHelper.cs
with Apache License 2.0
from cosmos-loops
with Apache License 2.0
from cosmos-loops
public static (long Start, long End, string TimeStr) Get(DateTimeOffset offset) {
var endOffset = offset.AddHours(1);
var start = offset.ToUnixTimeSeconds();
var end = endOffset.ToUnixTimeSeconds();
return (start, end, $"{start};{end}");
}
19
Source : JwtHelper.cs
with MIT License
from cq-panda
with MIT License
from cq-panda
public static string IssueJwt(UserInfo userInfo)
{
string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(AppSetting.ExpMinutes)).ToUnixTimeSeconds()}";
var claims = new List<Claim>
{
//new Claim(ClaimTypes.Name,userInfo.UserName ),
//new Claim(ClaimTypes.Role,userInfo.Role_Id ),
new Claim(JwtRegisteredClaimNames.Jti,userInfo.User_Id.ToString()),
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
//JWT过期时间
//验证是否过期 从User读取过期 时间,再将时间戳转换成日期,如果时间在半个小时内即将过期,通知前台刷新JWT
//int val= HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp).FirstOrDefault().Value;
//new DateTime(621355968000000000 + (long)val* (long)10000000, DateTimeKind.Utc).ToLocalTime()
//默认设置jwt过期时间120分钟
new Claim (JwtRegisteredClaimNames.Exp,exp),
new Claim(JwtRegisteredClaimNames.Iss,AppSetting.Secret.Issuer),
new Claim(JwtRegisteredClaimNames.Aud,AppSetting.Secret.Audience),
};
//秘钥16位
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret.JWT));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken securityToken = new JwtSecurityToken(issuer: AppSetting.Secret.Issuer, claims: claims, signingCredentials: creds);
string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
return jwt;
}
19
Source : DateTimeConvertService.cs
with MIT License
from CovidWorld
with MIT License
from CovidWorld
public long DateTimeToUnixTimestamp(DateTime dateTime)
{
var dateTimeOffset = new DateTimeOffset(dateTime);
long unixDateTime = dateTimeOffset.ToUnixTimeSeconds();
return unixDateTime;
}
19
Source : Time.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public static long DateTimeToUnixTime(DateTime dateTime)
{
return ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
}
19
Source : GoogleTTS.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
private static string MakeToken(string text)
{
// Get the hours since epoch
// Other methods:
// a = b = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalHours;
// a = b = (long)TimeSpan.FromSeconds(DateTimeOffset.Now.ToUnixTimeSeconds()).TotalHours;
long b;
long a = b = DateTimeOffset.Now.ToUnixTimeSeconds() / 3600;
foreach (char ch in text)
{
a = WorkToken(a + ch, _salt1);
}
a = WorkToken(a, _salt2);
if (a < 0)
{
a = (a & int.MaxValue) + int.MaxValue + 1;
}
a %= 1000000;
return $"{a}.{a ^ b}";
}
19
Source : Extensions.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public static string ToDiscordTimestamp(this DateTimeOffset dateTime, char style = 'f')
{
return dateTime.ToUnixTimeSeconds().ToDiscordTimestamp(style);
}
19
Source : DateTimeConverter.cs
with MIT License
from dahomey-technologies
with MIT License
from dahomey-technologies
public override void Write(ref CborWriter writer, DateTime value)
{
switch (_options.DateTimeFormat)
{
case DateTimeFormat.ISO8601:
writer.WriteSemanticTag(0);
writer.WriteString(value.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFK"));
break;
case DateTimeFormat.Unix:
writer.WriteSemanticTag(1);
writer.WriteInt64(new DateTimeOffset(value).ToUnixTimeSeconds());
break;
case DateTimeFormat.UnixMilliseconds:
writer.WriteSemanticTag(1);
writer.WriteDouble((double)new DateTimeOffset(value).ToUnixTimeMilliseconds() / 1000.0);
break;
}
}
19
Source : DynamoDbLockManager.cs
with MIT License
from danielgerlag
with MIT License
from danielgerlag
public async Task<bool> AcquireLock(string Id)
{
try
{
var req = new PureplacedemRequest()
{
TableName = _tableName,
Item = new Dictionary<string, AttributeValue>
{
{ "id", new AttributeValue(Id) },
{ "lock_owner", new AttributeValue(_nodeId) },
{
"expires", new AttributeValue()
{
N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + _defaultLeaseTime)
}
},
{
"purge_time", new AttributeValue()
{
N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + (_defaultLeaseTime * 10))
}
}
},
ConditionExpression = "attribute_not_exists(id) OR (expires < :expired)",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":expired", new AttributeValue()
{
N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + _jitterTolerance)
}
}
}
};
var response = await _client.PureplacedemAsync(req);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
_lockTracker.Add(Id);
return true;
}
}
catch (ConditionalCheckFailedException)
{
}
return false;
}
19
Source : HeartbeatDispatcher.cs
with MIT License
from danielgerlag
with MIT License
from danielgerlag
private async void SendHeartbeat()
{
while (!_cancellationTokenSource.IsCancellationRequested)
{
try
{
await Task.Delay(_interval, _cancellationTokenSource.Token);
foreach (var item in _lockTracker.GetSnapshot())
{
var req = new PureplacedemRequest
{
TableName = _tableName,
Item = new Dictionary<string, AttributeValue>
{
{ "id", new AttributeValue(item) },
{ "lock_owner", new AttributeValue(_nodeId) },
{
"expires", new AttributeValue()
{
N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + _leaseTime)
}
},
{
"purge_time", new AttributeValue()
{
N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + (_leaseTime * 10))
}
}
},
ConditionExpression = "lock_owner = :node_id",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":node_id", new AttributeValue(_nodeId) }
}
};
try
{
await _client.PureplacedemAsync(req, _cancellationTokenSource.Token);
}
catch (ConditionalCheckFailedException)
{
_logger.LogWarning($"Lock not owned anymore when sending heartbeat for {item}");
}
}
}
catch (Exception ex)
{
_logger.LogError(default(EventId), ex, ex.Message);
}
}
}
19
Source : BuildVersionGeneratorBase.cs
with MIT License
from dansiegel
with MIT License
from dansiegel
protected string GetBuildNumber()
{
if(Behavior == VersionBehavior.PreferBuildNumber && CIBuildEnvironmentUtils.IsBuildHost)
{
if(int.TryParse(CIBuildEnvironmentUtils.BuildNumber, out var buildId))
{
return $"{buildId + VersionOffset}";
}
return CIBuildEnvironmentUtils.BuildNumber;
}
var timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds() - EPOCOffset.ToUnixTimeSeconds();
return $"{VersionOffset + timeStamp}";
}
19
Source : JwtAppService.cs
with MIT License
from danvic712
with MIT License
from danvic712
public JwtAuthorizationDto Create(UserDto dto)
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecurityKey"]));
DateTime authTime = DateTime.UtcNow;
DateTime expiresAt = authTime.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpireMinutes"]));
//将用户信息添加到 Claim 中
var idenreplacedy = new ClaimsIdenreplacedy(JwtBearerDefaults.AuthenticationScheme);
IEnumerable<Claim> claims = new Claim[] {
new Claim(ClaimTypes.Name,dto.UserName),
new Claim(ClaimTypes.Role,dto.Role.ToString()),
new Claim(ClaimTypes.Email,dto.Email),
new Claim(ClaimTypes.Expiration,expiresAt.ToString())
};
idenreplacedy.AddClaims(claims);
//签发一个加密后的用户信息凭证,用来标识用户的身份
_httpContextAccessor.HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal(idenreplacedy));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(claims),//创建声明信息
Issuer = _configuration["Jwt:Issuer"],//Jwt token 的签发者
Audience = _configuration["Jwt:Audience"],//Jwt token 的接收者
Expires = expiresAt,//过期时间
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//创建 token
};
var token = tokenHandler.CreateToken(tokenDescriptor);
//存储 Token 信息
var jwt = new JwtAuthorizationDto
{
UserId = dto.Id,
Token = tokenHandler.WriteToken(token),
Auths = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
Expires = new DateTimeOffset(expiresAt).ToUnixTimeSeconds(),
Success = true
};
_tokens.Add(jwt);
return jwt;
}
19
Source : MomentJsFormatter.cs
with Apache License 2.0
from DarkLiKally
with Apache License 2.0
from DarkLiKally
private string GetSpecialTokenValue(DateTimeOffset value, string token, CultureInfo culture)
{
switch (token)
{
case "Mo": return AddOrdinal(value.Month);
case "Q": return GetQuarter(value.Month).ToString();
case "Qo": return AddOrdinal(GetQuarter(value.Month));
case "Do": return AddOrdinal(value.Day);
case "DDD": return value.DayOfYear.ToString();
case "DDDo": return AddOrdinal(value.DayOfYear);
case "DDDD": return value.DayOfYear.ToString("000");
case "d": return ((int) value.DayOfWeek).ToString();
case "do": return AddOrdinal((int) value.DayOfWeek);
case "e": return ((int) value.DayOfWeek).ToString();
case "E": return ((int) value.DayOfWeek + 1).ToString();
case "w":
case "wo":
case "ww":
case "W":
case "Wo":
case "WW":
return GetWeekTokenValue(value, token, culture);
case "a": return value.ToString("tt", culture).ToLower();
case "k": return (value.Hour + 1).ToString();
case "kk": return (value.Hour + 1).ToString("00");
case "SSSSSSSS": return value.ToString("fffffff00", culture);
case "SSSSSSSSS": return value.ToString("fffffff000", culture);
case "z":
case "zz":
return TimeZoneData.GetFirstForOffset(value.Offset).Abbreviation;
case "ZZ": return value.ToString("zzz", culture).Replace(":", "");
case "X": return value.ToUnixTimeSeconds().ToString();
case "x": return value.ToUnixTimeMilliseconds().ToString();
}
return token;
}
19
Source : Expiration.cs
with MIT License
from davidfowl
with MIT License
from davidfowl
private static Expiration SetExpiration(TimeSpan? expireIn)
{
uint value = 0;
if (expireIn != null)
{
if (expireIn < TimeSpan.FromDays(30))
{
value = (uint)expireIn.Value.TotalSeconds;
}
else
{
value = (uint)new DateTimeOffset(DateTime.UtcNow.Add(expireIn.Value)).ToUnixTimeSeconds();
}
}
return new Expiration(value);
}
19
Source : CustomNode.cs
with Apache License 2.0
from DeepOceanSoft
with Apache License 2.0
from DeepOceanSoft
public CustomNode(string name, long userId, string message, DateTimeOffset? time = null)
{
MessageId = null;
Name = name;
UserId = userId.ToString();
Messages = message;
Time = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}";
}
19
Source : CustomNode.cs
with Apache License 2.0
from DeepOceanSoft
with Apache License 2.0
from DeepOceanSoft
public CustomNode(string name, long userId, MessageBody customMessage, DateTimeOffset? time = null)
{
MessageId = null;
Name = name;
UserId = userId.ToString();
Messages = customMessage.Where(msg => msg.MessageType != SegmentType.Ignore)
.Select(msg => msg.ToOnebotMessage())
.ToList();
Time = $"{time?.ToUnixTimeSeconds() ?? DateTimeOffset.Now.ToUnixTimeSeconds()}";
}
19
Source : DBEditDlg.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
private bool ShouldDisplayGame(DatabaseEntry entry)
{
if (entry == null)
{
return false;
}
if (Settings.IgnoreList.Contains(entry.AppId) && !CheckShowIgnored.Checked)
{
return false;
}
if (chkIdRange.Checked && (entry.AppId < _currentMinId || entry.AppId > _currentMaxId))
{
return false;
}
if (!Database.Contains(entry.AppId))
{
return false;
}
if (_ownedList != null && chkOwned.Checked && !_ownedList.Games.ContainsKey(entry.AppId))
{
return false;
}
if (chkTypeAll.Checked == false)
{
switch (entry.AppType)
{
case AppType.Game:
if (chkTypeGame.Checked == false)
{
return false;
}
break;
case AppType.DLC:
if (chkTypeDLC.Checked == false)
{
return false;
}
break;
case AppType.Unknown:
if (chkTypeUnknown.Checked == false)
{
return false;
}
break;
default:
if (chkTypeOther.Checked == false)
{
return false;
}
break;
}
}
if (radWebAll.Checked == false)
{
if (radWebNo.Checked && entry.LastStoreScrape > 0)
{
return false;
}
if (radWebYes.Checked && entry.LastStoreScrape <= 0)
{
return false;
}
if (radWebSince.Checked && entry.LastStoreScrape > ((DateTimeOffset) dateWeb.Value).ToUnixTimeSeconds())
{
return false;
}
}
if (radAppAll.Checked == false)
{
if (radAppNo.Checked && entry.LastAppInfoUpdate > 0)
{
return false;
}
if (radAppYes.Checked && entry.LastAppInfoUpdate <= 0)
{
return false;
}
}
if (_currentFilter.Length > 0 && entry.Name.IndexOf(_currentFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
{
return false;
}
return true;
}
19
Source : Database.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
public int UpdateFromAppInfo(string path)
{
int updated = 0;
Dictionary<int, AppInfo> appInfos = AppInfo.LoadApps(path);
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
foreach (AppInfo aInf in appInfos.Values)
{
if (!Contains(aInf.Id, out DatabaseEntry entry))
{
entry = new DatabaseEntry(aInf.Id);
Add(entry);
}
entry.LastAppInfoUpdate = timestamp;
if (aInf.AppType != AppType.Unknown)
{
entry.AppType = aInf.AppType;
}
if (!string.IsNullOrEmpty(aInf.Name))
{
entry.Name = aInf.Name;
}
if (entry.Platforms == AppPlatforms.None || entry.LastStoreScrape == 0 && aInf.Platforms > AppPlatforms.None)
{
entry.Platforms = aInf.Platforms;
}
if (aInf.ParentId > 0)
{
entry.ParentId = aInf.ParentId;
}
updated++;
}
return updated;
}
19
Source : Database.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
public int UpdateFromHLTB(bool includeImputedTimes)
{
int updated = 0;
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
string result = client.DownloadString(Constants.HowLongToBeat);
if (result.Contains("An error has occurred."))
{
return updated;
}
HLTB_RawData rawData = JsonConvert.DeserializeObject<HLTB_RawData>(result);
if (rawData == null)
{
return updated;
}
foreach (Game game in rawData.Games)
{
SteamAppData steamAppData = game.SteamAppData;
int id = steamAppData.SteamAppId;
if (!Contains(id, out DatabaseEntry entry))
{
continue;
}
HltbInfo info = steamAppData.HltbInfo;
if (!includeImputedTimes && info.MainTtbImputed)
{
entry.HltbMain = 0;
}
else
{
entry.HltbMain = info.MainTtb;
}
if (!includeImputedTimes && info.ExtrasTtbImputed)
{
entry.HltbExtras = 0;
}
else
{
entry.HltbExtras = info.ExtrasTtb;
}
if (!includeImputedTimes && info.CompletionistTtbImputed)
{
entry.HltbCompletionists = 0;
}
else
{
entry.HltbCompletionists = info.CompletionistTtb;
}
updated++;
}
}
LastHLTBUpdate = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
return updated;
}
19
Source : DlgGameDBEntry.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
private bool SaveToGame()
{
if (!ValidateEntries(out int id, out int parent))
{
return false;
}
if (Game == null)
{
Game = new DatabaseEntry(id);
}
Game.AppId = id;
Game.ParentId = parent;
Game.AppType = (AppType?) cmbType.SelectedItem ?? AppType.Unknown;
Game.Name = txtName.Text;
Game.Genres = SplitAndTrim(txtGenres.Text);
Game.Flags = SplitAndTrim(txtFlags.Text);
Game.Tags = SplitAndTrim(txtTags.Text);
Game.Developers = SplitAndTrim(txtDev.Text);
Game.Publishers = SplitAndTrim(txtPub.Text);
Game.TotalAchievements = (int) numAchievements.Value;
Game.ReviewPositivePercentage = (int) numReviewScore.Value;
Game.ReviewTotal = (int) numReviewCount.Value;
Game.HltbMain = (int) numHltbMain.Value;
Game.HltbExtras = (int) numHltbExtras.Value;
Game.HltbCompletionists = (int) numHltbCompletionist.Value;
Game.MetacriticUrl = txtMCName.Text;
Game.SteamReleaseDate = txtRelease.Text;
Game.Platforms = AppPlatforms.None;
if (chkPlatWin.Checked)
{
Game.Platforms |= AppPlatforms.Windows;
}
if (chkPlatMac.Checked)
{
Game.Platforms |= AppPlatforms.Mac;
}
if (chkPlatLinux.Checked)
{
Game.Platforms |= AppPlatforms.Linux;
}
Game.LastStoreScrape = chkWebUpdate.Checked ? ((DateTimeOffset) dateWeb.Value).ToUnixTimeSeconds() : 0;
Game.LastAppInfoUpdate = chkAppInfoUpdate.Checked ? ((DateTimeOffset) dateAppInfo.Value).ToUnixTimeSeconds() : 0;
return true;
}
19
Source : AutomaticModeForm.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
private bool UpdateDatabaseFromHLTB(bool doUpdate)
{
if (!doUpdate)
{
WriteLine("Skipping HLTB update.");
return true;
}
int HalfAWeekInSecs = 84 * 24 * 60 * 60;
if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() > Database.LastHLTBUpdate + HalfAWeekInSecs)
{
WriteLine("Skipping HLTB update.");
return true;
}
Write("Updating database from HLTB...");
bool success = false;
try
{
if (Database.UpdateFromHLTB(Settings.Instance.IncludeImputedTimes) > 0)
{
dbModified = true;
}
success = true;
}
catch (Exception e)
{
WriteLine("Error updating database from HLTB: " + e.Message);
Logger.Exception("Automatic mode: Error updating from HLTB.", e);
}
if (success)
{
WriteLine("HLTB update complete.");
}
return success;
}
19
Source : DepressurizerPremium.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
public static void load(DatabaseEntry entry, Uri uri)
{
HttpClient client = new HttpClient();
using (Stream s = client.GetStreamAsync(uri).Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
DepressurizerPremiumResponse response = new JsonSerializer().Deserialize<DepressurizerPremiumResponse>(reader);
if (!Enum.TryParse(response.appType, true, out AppType type) || type == AppType.Unknown)
{
return;
}
entry.Name = response.name;
entry.AppType = type;
entry.SteamReleaseDate = response.releaseDate;
entry.TotalAchievements = response.totalAchievements;
entry.ReviewTotal = response.totalReview;
entry.ReviewPositivePercentage = (int)Math.Round(response.totalPositiveReview / (double)response.totalReview * 100.00);
entry.MetacriticUrl = response.metacriticLink;
entry.HltbCompletionists = response.hltbCompletionists;
entry.HltbExtras = response.hltbExtras;
entry.HltbMain = response.hltbMain;
entry.Platforms = 0;
if (response.supportsLinux)
{
entry.Platforms |= AppPlatforms.Linux;
}
if (response.supportsMac)
{
entry.Platforms |= AppPlatforms.Mac;
}
if (response.supportsWindows)
{
entry.Platforms |= AppPlatforms.Windows;
}
entry.Flags.Clear();
foreach (string flag in response.flags)
{
entry.Flags.Add(flag);
}
entry.Genres.Clear();
foreach (string genre in response.genres)
{
entry.Genres.Add(genre);
}
entry.Tags.Clear();
foreach (string tag in response.tags)
{
entry.Tags.Add(tag);
}
entry.Developers.Clear();
foreach (string developer in response.developers)
{
entry.Developers.Add(developer);
}
entry.Publishers.Clear();
foreach (string publisher in response.publishers)
{
entry.Publishers.Add(publisher);
}
entry.VRSupport = new VRSupport()
{
Headsets = response.virtualRealityHeadsets,
Input = response.virtualRealityInput,
PlayArea = response.virtualRealityPlayArea
};
entry.LastStoreScrape = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
}
19
Source : DatabaseEntry.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
private AppType ScrapeStoreHelper(string languageCode)
{
Logger.Verbose("Scraping {0}: Initiating scraping of the Steam Store.", AppId);
int redirectTarget = -1;
HttpWebResponse resp = null;
try
{
HttpWebRequest req = GetSteamRequest(string.Format(CultureInfo.InvariantCulture, Constants.SteamStoreApp + "?l=" + languageCode, AppId));
resp = (HttpWebResponse) req.GetResponse();
int count = 0;
while (resp.StatusCode == HttpStatusCode.Found && count < MaxFollowAttempts)
{
resp.Close();
if (Regexes.IsSteamStore.IsMatch(resp.Headers[HttpResponseHeader.Location]))
{
Logger.Warn("Scraping {0}: Location header points to the Steam Store homepage, aborting scraping.", AppId);
return AppType.Unknown;
}
// If page redirects to itself
if (resp.ResponseUri.ToString() == resp.Headers[HttpResponseHeader.Location])
{
Logger.Warn("Scraping {0}: Location header points to itself, aborting scraping.", AppId);
return AppType.Unknown;
}
req = GetSteamRequest(resp.Headers[HttpResponseHeader.Location]);
resp = (HttpWebResponse) req.GetResponse();
count++;
}
if (count == MaxFollowAttempts && resp.StatusCode == HttpStatusCode.Found)
{
Logger.Warn("Scraping {0}: Received too many redirects, aborting scraping.", AppId);
return AppType.Unknown;
}
if (resp.ResponseUri.Segments.Length < 2)
{
Logger.Warn("Scraping {0}: Redirected to the Steam Store homepage, aborting scraping.", AppId);
return AppType.Unknown;
}
// If we encountered an age gate (cookies should bypreplaced this, but sometimes they don't seem to)
if (resp.ResponseUri.Segments[1] == "agecheck/")
{
// If we got an age check with no redirect
if (resp.ResponseUri.Segments.Length < 4 || resp.ResponseUri.Segments[3].TrimEnd('/') == AppId.ToString())
{
Logger.Warn("Scraping {0}: Hit an age check without redirect, aborting scraping.", AppId);
return AppType.Unknown;
}
Logger.Verbose("Scraping {0}: Hit age check for id {1}.", AppId, resp.ResponseUri.Segments[3].TrimEnd('/'));
// If we got an age check without numeric id (shouldn't happen)
if (!int.TryParse(resp.ResponseUri.Segments[3].TrimEnd('/'), out redirectTarget))
{
Logger.Warn("Scraping {0}: Hit an age check without numeric id, aborting scraping.", AppId);
return AppType.Unknown;
}
}
else if (resp.ResponseUri.Segments[1] != "app/")
{
Logger.Warn("Scraping {0}: Redirected to a non-app URL, aborting scraping.", AppId);
return AppType.Unknown;
}
// The URI ends with "/app/" ?
else if (resp.ResponseUri.Segments.Length < 3)
{
Logger.Warn("Scraping {0}: Response URI ends with 'app' thus missing the redirect ID, aborting scraping.", AppId);
return AppType.Unknown;
}
// Redirected to a different app id
else if (resp.ResponseUri.Segments[2].TrimEnd('/') != AppId.ToString())
{
if (!int.TryParse(resp.ResponseUri.Segments[2].TrimEnd('/'), out redirectTarget))
{
Logger.Verbose("Scraping {0}: Redirected to a different but failed parsing the id: {1}, aborting scraping.", AppId, resp.ResponseUri.Segments[2].TrimEnd('/'));
return AppType.Unknown;
}
Logger.Verbose("Scraping {0}: Redirected to a different id: {1}.", AppId, redirectTarget);
}
}
catch (UriFormatException e)
{
Logger.Warn("Scraping {0}: Caught an UriFormatException most likely something on Steam side is wrong; {1}.", AppId, e);
resp?.Dispose();
return AppType.Unknown;
}
catch (WebException e) when (e.Status == WebExceptionStatus.Timeout)
{
Logger.Warn("Scraping {0}: Exception thrown while reading page - operation timed out (page no longer exists or internet connection interrupted?); {1}.", AppId, e);
resp?.Dispose();
return AppType.Unknown;
}
catch (WebException e)
{
Logger.Warn("Scraping {0}: Exception thrown while reading page - {1}.", AppId, e);
resp?.Dispose();
return AppType.Unknown;
}
catch (Exception e)
{
Logger.Warn("Scraping {0}: Exception thrown while reading page; {1}.", AppId, e);
resp?.Dispose();
throw;
}
string page;
Stream responseStream = null;
try
{
responseStream = resp.GetResponseStream();
if (responseStream == null)
{
Logger.Warn("Scraping {0}: The response stream was null, aborting scraping.", AppId);
return AppType.Unknown;
}
using (StreamReader streamReader = new StreamReader(responseStream))
{
page = streamReader.ReadToEnd();
}
Logger.Verbose("Scraping {0}: Successfully read page.", AppId);
}
catch (Exception e)
{
Logger.Warn("Scraping {0}: Exception thrown while reading page; {1}.", AppId, e);
throw;
}
finally
{
resp.Dispose();
responseStream?.Dispose();
}
LastStoreScrape = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
AppType result = AppType.Unknown;
if (page.Contains("<replacedle>Site Error</replacedle>"))
{
if (redirectTarget == -1)
{
Logger.Warn("Scraping {0}: Received a site error, aborting scraping.", AppId);
return AppType.Unknown;
}
Logger.Verbose("Scraping {0}: Received a site error, following redirect target.", AppId);
}
// Here we should have an app, but make sure.
else if (RegexIsGame.IsMatch(page) || RegexIsSoftware.IsMatch(page))
{
GetAllDataFromPage(page);
// Check whether it's DLC and return appropriately
if (RegexIsDLC.IsMatch(page))
{
result = AppType.DLC;
}
else
{
result = RegexIsSoftware.IsMatch(page) ? AppType.Application : AppType.Game;
}
}
// The URI is right, but it didn't preplaced the regex check
else
{
if (redirectTarget == -1)
{
Logger.Warn("Scraping {0}: Could not parse information from page, aborting scraping.", AppId);
return result;
}
Logger.Verbose("Scraping {0}: Could not parse information from page, following redirect target.", AppId);
}
if (redirectTarget == -1)
{
return result;
}
ParentId = redirectTarget;
return AppType.Unknown;
}
19
Source : DlgRandomGame.cs
with GNU General Public License v3.0
from Depressurizer
with GNU General Public License v3.0
from Depressurizer
private void btnLaunch_Click(object sender, EventArgs e)
{
game.LastPlayed = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Process.Start(game.Executable);
Close();
}
See More Examples