Here are the examples of the csharp api System.TimeSpan.FromHours(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1233 Examples
19
Source : EdisFace.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
private void CacheDeniedClient(string clientIp)
{
string key = Edi.MakeUniqueCacheKey("EDI_DENYLIST");
HashSet<string> denyHashlist = null;
lock (lck)
{
if (!CacheManager.TryGetCachedResult<HashSet<string>>(
key,
out denyHashlist)
)
{
denyHashlist = new HashSet<string>();
}
if (!denyHashlist.Contains(clientIp))
{
denyHashlist.Add(clientIp);
CacheManager.CacheObject(key, denyHashlist,TimeSpan.FromHours(3));
}
}
denyHashlist.Clear();
denyHashlist = null;
}
19
Source : PersonService.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task<object> GetName(int id)
{
await Task.Delay(TimeSpan.FromHours(1));
return await Task.FromResult(new
{
name = $"[{id}]Owen",
//message = await HelloService.SayHello("Owen")
});
}
19
Source : CSRedisClientKeyTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void Persist() {
replacedert.True(rds.MSet("TestPersist_null1", base.Null, "TestPersist_string1", base.String, "TestPersist_bytes1", base.Bytes, "TestPersist_clreplaced1", base.Clreplaced));
replacedert.True(rds.Expire("TestPersist_null1", 10));
replacedert.Equal(10, rds.Ttl("TestPersist_null1"));
replacedert.True(rds.Expire("TestPersist_string1", TimeSpan.FromHours(1)));
replacedert.Equal(60 * 60, rds.Ttl("TestPersist_string1"));
replacedert.True(rds.Persist("TestPersist_null1"));
replacedert.False(rds.Persist("TestPersist_null11"));
replacedert.True(rds.Persist("TestPersist_string1"));
replacedert.False(rds.Persist("TestPersist_string11"));
replacedert.Equal(-1, rds.Ttl("TestPersist_null1"));
replacedert.Equal(-1, rds.Ttl("TestPersist_string1"));
}
19
Source : CSRedisClientKeyTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void Expire() {
replacedert.True(rds.MSet("TestExpire_null1", base.Null, "TestExpire_string1", base.String, "TestExpire_bytes1", base.Bytes, "TestExpire_clreplaced1", base.Clreplaced));
replacedert.True(rds.Expire("TestExpire_null1", 10));
replacedert.Equal(10, rds.Ttl("TestExpire_null1"));
replacedert.True(rds.Expire("TestExpire_string1", TimeSpan.FromHours(1)));
replacedert.Equal(60 * 60, rds.Ttl("TestExpire_string1"));
}
19
Source : CSRedisClientKeyTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void PExpire() {
replacedert.True(rds.MSet("TestPExpire_null1", base.Null, "TestPExpire_string1", base.String, "TestPExpire_bytes1", base.Bytes, "TestPExpire_clreplaced1", base.Clreplaced));
replacedert.True(rds.PExpire("TestPExpire_null1", 10000));
replacedert.InRange(rds.PTtl ("TestPExpire_null1"), 9000, 10000);
replacedert.True(rds.PExpire("TestPExpire_string1", TimeSpan.FromHours(1)));
replacedert.InRange(rds.PTtl("TestPExpire_string1"), 1000 * 60 * 60 - 1000, 1000 * 60 * 60);
}
19
Source : NpcCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
private PropertyInfo GetFieldPropertyInfo(PlayerEnreplacedy player, string field)
{
var fieldEnum = (PlayerConditionFieldEnum)Enum.Parse(typeof(PlayerConditionFieldEnum), field, true);
var key = $"player_properties";
var properties = _cache.GetOrCreate(key, p => {
p.SetAbsoluteExpiration(TimeSpan.FromHours(24));
return player.GetType().GetProperties();
});
foreach (var prop in properties)
{
var attribute = prop.GetCustomAttributes(typeof(ConditionFieldAttribute), true).FirstOrDefault();
if (attribute != null)
{
if ((attribute as ConditionFieldAttribute).FieldEnum == fieldEnum)
{
return prop;
}
}
}
return null;
}
19
Source : WorkFlowManager.cs
with Apache License 2.0
from AbpApp
with Apache License 2.0
from AbpApp
private async Task<ICollection<WorkflowDefinitionVersion>> ReadCacheAsync(CancellationToken cancellationToken)
{
return await cache.GetOrCreateAsync(
CacheKey,
async entry =>
{
var workflowDefinitions = await LoadWorkflowDefinitionsAsync(cancellationToken);
entry.SlidingExpiration = TimeSpan.FromHours(1);
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(4);
entry.Monitor(signal.GetToken(CacheKey));
return workflowDefinitions;
});
}
19
Source : CreateSimpleStockChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void CreateSciTradeChartLoaded(object sender, RoutedEventArgs e)
{
var dataSeries = new OhlcDataSeries<DateTime, double>()
{
// Note: SeriesName is needed to display the legend correctly.
SeriesName = "Price Data"
};
// Append price data
var prices = DataManager.Instance.GetPriceData(Instrument.Indu.Value, TimeFrame.Daily);
dataSeries.Append(prices.TimeData, prices.OpenData, prices.HighData, prices.LowData, prices.CloseData);
// Set BarTimeFrame = 3600 seconds (time of one bar in the input data)
StockChart.BarTimeFrame = TimeSpan.FromHours(1).TotalSeconds;
StockChart.RenderableSeries[0].DataSeries = dataSeries;
}
19
Source : SciChartMvvmBindingsViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void InitializeAxes()
{
var xNumAxis = new NumericAxisViewModel
{
AxisAlignment = AxisAlignment.Bottom,
Axisreplacedle = "XAxis",
DrawMajorBands = false,
TextFormatting = "0.00#",
VisibleRange = new DoubleRange(0, 10),
BorderThickness = new Thickness(3),
BorderBrush = new SolidColorBrush(Colors.CadetBlue)
};
XAxes.Add(xNumAxis);
var xDateTimeAxis = new DateTimeAxisViewModel
{
AxisAlignment = AxisAlignment.Top,
Id = "DateTimeAxis",
VisibleRange = new DateRange(new DateTime(2017, 1, 1), new DateTime(2017, 1, 31)),
StyleKey = "DateTimeAxisStyle"
};
XAxes.Add(xDateTimeAxis);
var yNumAxis = new NumericAxisViewModel
{
Axisreplacedle = "YAxis",
DrawMajorBands = false,
TextFormatting = "0.0#",
VisibleRange = new DoubleRange(-10, 10)
};
YAxes.Add(yNumAxis);
var yTimeSpanAxis = new TimeSpanAxisViewModel
{
Id = "TimeSpanAxis",
DrawMajorBands = false,
VisibleRange = new TimeSpanRange(TimeSpan.FromHours(1), TimeSpan.FromHours(24)),
AxisAlignment = AxisAlignment.Left
};
YAxes.Add(yTimeSpanAxis);
}
19
Source : WorldManager.cs
with MIT License
from adamgoodrich
with MIT License
from adamgoodrich
public void SetDecimalTime(double time)
{
var ts = TimeSpan.FromHours(time);
var gameTime = new DateTime(m_gameTime.Year, m_gameTime.Month, m_gameTime.Day, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
if (m_gameTime != gameTime)
{
m_gameTime = gameTime;
m_changeMask |= WorldConstants.WorldChangeEvents.GameTimeChanged;
RaiseEvent();
}
}
19
Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void replacedertWithinJitterRange(DateTimeOffset actual, DateTimeOffset now)
{
// The jitter can cause the actual value to fall in the range [now + 80% of refresh period, now + 100% of refresh period)
replacedert.InRange(actual, now + TimeSpan.FromHours(24 * 0.8), now + TimeSpan.FromHours(24));
}
19
Source : AuthorizedToken.razor.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected override void OnInitialized()
{
Localizer.OnResourceReady = () => InvokeAsync(StateHasChanged);
if (Value != null)
{
var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(Value));
_token = new Token
{
ValueString = timeSpan.ToString(DISPLAY_FORMAT)
};
}
else
{
_token = new Token();
}
_token.PropertyChanged += (s, e) =>
{
if (_updatingValue)
{
return;
}
var match = _regex.Match(_token.ValueString);
if (!match.Success)
{
return;
}
var groups = match.Groups;
if (groups["DaysTime"].Success || groups["Time"].Success)
{
var newTimeSpan = TimeSpan.Parse(_token.ValueString);
SetValue(newTimeSpan);
}
else if (groups["MinutesSecondes"].Success)
{
var newTimeSpan = TimeSpan.Parse($"00:{_token.ValueString}");
SetValue(newTimeSpan);
}
else if (groups["Days"].Success)
{
var newTimeSpan = TimeSpan.FromDays(int.Parse(_token.ValueString[0..^1]));
SetValue(newTimeSpan);
}
else if (groups["Hours"].Success)
{
var newTimeSpan = TimeSpan.FromHours(int.Parse(_token.ValueString[0..^1]));
SetValue(newTimeSpan);
}
else if (groups["Minutes"].Success)
{
var newTimeSpan = TimeSpan.FromMinutes(int.Parse(_token.ValueString[0..^1]));
SetValue(newTimeSpan);
}
else if (_token.ValueString.EndsWith("s"))
{
var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString[0..^1]));
SetValue(newTimeSpan);
}
else
{
var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString));
SetValue(newTimeSpan);
}
};
base.OnInitialized();
}
19
Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void GetCurrentKeyRing_NoKeyRingCached_CachesAndReturns()
{
// Arrange
var now = StringToDateTime("2015-03-01 00:00:00Z");
var expectedKeyRing = new Mock<IKeyRing>().Object;
var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
mockCacheableKeyRingProvider
.Setup(o => o.GetCacheableKeyRing(now))
.Returns(new CacheableKeyRing(
expirationToken: CancellationToken.None,
expirationTime: StringToDateTime("2015-03-02 00:00:00Z"),
keyRing: expectedKeyRing));
var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);
// Act
var retVal1 = keyRingProvider.GetCurrentKeyRingCore(now);
var retVal2 = keyRingProvider.GetCurrentKeyRingCore(now + TimeSpan.FromHours(1));
// replacedert - underlying provider only should have been called once
replacedert.Same(expectedKeyRing, retVal1);
replacedert.Same(expectedKeyRing, retVal2);
mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(It.IsAny<DateTimeOffset>()), Times.Once);
}
19
Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void GetCurrentKeyRing_KeyRingCached_AfterExpiration_ClearsCache()
{
// Arrange
var now = StringToDateTime("2015-03-01 00:00:00Z");
var expectedKeyRing1 = new Mock<IKeyRing>().Object;
var expectedKeyRing2 = new Mock<IKeyRing>().Object;
var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
mockCacheableKeyRingProvider
.Setup(o => o.GetCacheableKeyRing(now))
.Returns(new CacheableKeyRing(
expirationToken: CancellationToken.None,
expirationTime: StringToDateTime("2015-03-01 00:30:00Z"), // expire in half an hour
keyRing: expectedKeyRing1));
mockCacheableKeyRingProvider
.Setup(o => o.GetCacheableKeyRing(now + TimeSpan.FromHours(1)))
.Returns(new CacheableKeyRing(
expirationToken: CancellationToken.None,
expirationTime: StringToDateTime("2015-03-02 00:00:00Z"),
keyRing: expectedKeyRing2));
var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);
// Act
var retVal1 = keyRingProvider.GetCurrentKeyRingCore(now);
var retVal2 = keyRingProvider.GetCurrentKeyRingCore(now + TimeSpan.FromHours(1));
// replacedert - underlying provider only should have been called once
replacedert.Same(expectedKeyRing1, retVal1);
replacedert.Same(expectedKeyRing2, retVal2);
mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(It.IsAny<DateTimeOffset>()), Times.Exactly(2));
}
19
Source : ConfigurationExtensionTests.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
[Fact]
public void TestExtractDiscordConfig_Haphzard()
{
var source = this.DiscordHaphazardConfig();
var config = source.ExtractConfig<DiscordConfiguration>("Discord");
var expectedIntents = DiscordIntents.GuildEmojisAndStickers | DiscordIntents.GuildMembers |
DiscordIntents.Guilds;
replacedert.Equal(expectedIntents, config.Intents);
replacedert.True(config.MobileStatus);
replacedert.Equal(1000, config.LargeThreshold);
replacedert.Equal(TimeSpan.FromHours(10), config.HttpTimeout);
}
19
Source : ClearLoginLogBackgroundService.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public async Task DoWork()
{
while (true)
{
// 清理过期的日志
var setting = _loginSetting.GetCacheData(60 * 60 * 24).FirstOrDefault();
if (setting != null)
{
var expire = DateTime.Now.AddDays(-setting.SaveTime);
await _loginLogDetail.RemoveAsync(d => d.OperateAt < expire);
}
await _systemIdenreplacedyDbUnitOfWork.SaveAsync();
// 一小时清理一次
await Task.Delay(TimeSpan.FromHours(1));
}
}
19
Source : AbstractTimedBackgroundService.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
private TimeSpan GetDelaySpan()
{
return TimeSpan.FromDays(_backgroundJob.Days)
.Add(TimeSpan.FromHours(_backgroundJob.Hours))
.Add(TimeSpan.FromMinutes(_backgroundJob.Minutes))
.Add(TimeSpan.FromSeconds(_backgroundJob.Seconds));
}
19
Source : ClearOperateLogBackgroundService.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public async Task DoWork()
{
while (true)
{
// 清理过期的日志
var settings = _logSettingCaching.GetCacheData();
foreach (var setting in settings)
{
var expire = DateTime.Now.AddDays(-setting.SaveTime);
await _logDetaiRepository.RemoveAsync(d => d.OperateAt < expire && d.SettingId == setting.Id);
}
await _systemIdenreplacedyDbUnitOfWork.SaveAsync();
// 一小时清理一次
await Task.Delay(TimeSpan.FromHours(1));
}
}
19
Source : HangFireExtension.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public static IServiceCollection AddPostgreSQLHangFire(this IServiceCollection services,
string connectionString)
{
services.AddHangfire(configuration =>
{
configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimplereplacedemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions
{
QueuePollInterval = TimeSpan.FromSeconds(3), // 作业队列轮询间隔
PrepareSchemaIfNecessary = true, // 自动创建表
SchemaName = "Hangfire" // Schema名
}).WithJobExpirationTimeout(TimeSpan.FromHours(1000)); // 作业过期时间,过期任务会被从数据库清理。此值不能小于1小时,否则会引起异常
}).AddHangfireServer(option =>
{
option.SchedulePollingInterval = TimeSpan.FromSeconds(1);
});
return services;
}
19
Source : HangFireExtension.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public static IServiceCollection AddMySQLHangFire(this IServiceCollection services,
string connectionString)
{
services.AddHangfire(configruation =>
{
configruation.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimplereplacedemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseStorage(new MySqlStorage(connectionString, new MySqlStorageOptions
{
TransactionIsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, // 事务隔离级别
QueuePollInterval = TimeSpan.FromSeconds(3), // 作业队列轮询间隔
JobExpirationCheckInterval = TimeSpan.FromHours(1), // 作业过期检查间隔(管理过期记录)
CountersAggregateInterval = TimeSpan.FromMinutes(5), // 计数器统计间隔
PrepareSchemaIfNecessary = true, // 自动创建表
DashboardJobListLimit = 50000, // 仪表盘显示作业限制
TransactionTimeout = TimeSpan.FromMinutes(1), // 事务超时时间
TablesPrefix = "T_Hangfire", // hangfire表名前缀
InvisibilityTimeout = TimeSpan.FromDays(1) // 弃用属性,设定线程重开间隔
})).WithJobExpirationTimeout(TimeSpan.FromHours(24 * 7)); // 作业过期时间,过期任务会被从数据库清理。此值不能小于1小时,否则会引起异常
}).AddHangfireServer(option =>
{
option.SchedulePollingInterval = TimeSpan.FromSeconds(1);
});
return services;
}
19
Source : LastSaidJudger.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public bool ShallBeGroupped(string userId, int conversationId)
{
if (_memoryCache.TryGetValue($"conversation-{conversationId}-last-said", out DateTime lastSaid))
{
var justSaid = lastSaid + TimeSpan.FromHours(1) > DateTime.UtcNow;
if (justSaid)
{
if (_memoryCache.TryGetValue($"conversation-{conversationId}-last-said-person", out string lastSaidPerson))
{
if (lastSaidPerson == userId)
{
return true;
}
}
}
}
return false;
}
19
Source : EmailNotifier.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private async void DoWork(object state)
{
try
{
_logger.LogInformation("Email notifier task started!");
using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<KahlaDbContext>();
var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
var emailSender = scope.ServiceProvider.GetRequiredService<AiurEmailSender>();
var timeLimit = DateTime.UtcNow - TimeSpan.FromHours(23);
var users = await dbContext
.Users
.Where(t => t.EmailConfirmed)
.Where(t => t.EnableEmailNotification)
// Only for users who did not send email for a long time.
.Where(t => t.LastEmailHimTime < timeLimit)
.ToListAsync();
foreach (var user in users)
{
_logger.LogInformation($"Building email for user: {user.NickName}...");
var (emailMessage, reason) = await BuildEmail(user, dbContext, configuration["EmailAppDomain"]);
if (string.IsNullOrWhiteSpace(emailMessage))
{
_logger.LogInformation($"User: {user.NickName}'s Email is empty. Skip.");
continue;
}
if (user.EmailReasonInJson == JsonConvert.SerializeObject(reason))
{
_logger.LogInformation($"User: {user.NickName}'s Email has the same send reason with the previous one. Skip.");
continue;
}
_logger.LogInformation($"Sending email to user: {user.NickName}.");
await emailSender.SendEmail("Kahla Notification", user.Email, "New notifications in Kahla", emailMessage);
user.LastEmailHimTime = DateTime.UtcNow;
user.EmailReasonInJson = JsonConvert.SerializeObject(reason);
dbContext.Update(user);
}
await dbContext.SaveChangesAsync();
}
catch (Exception ex)
{
try
{
_logger.LogCritical(ex, ex.Message);
using var scope = _scopeFactory.CreateScope();
var eventService = scope.ServiceProvider.GetRequiredService<EventService>();
var accessToken = await _appsContainer.AccessToken();
await eventService.LogExceptionAsync(accessToken, ex, "Email Notifier");
}
catch
{
// ignored
}
}
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_No_Consumers()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Complete();
await push.replacedertResult(1, 2, 3, 4, 5);
await push.replacedertResult(1, 2, 3, 4, 5);
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_No_Consumers_Error()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Error(new InvalidOperationException());
await push.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
await push.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_One_Consumer()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
var en1 = push.GetAsyncEnumerator(default);
var task1 = Task.Run(async () =>
{
await en1.replacedertResult(1, 2, 3, 4, 5);
});
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Complete();
await task1;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_One_Consumer_Error()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
var en1 = push.GetAsyncEnumerator(default);
var task1 = Task.Run(async () =>
{
await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
});
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Error(new InvalidOperationException());
await task1;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_2_Consumers()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
var en1 = push.GetAsyncEnumerator(default);
var en2 = push.GetAsyncEnumerator(default);
var task1 = Task.Run(async () =>
{
await en1.replacedertResult(1, 2, 3, 4, 5);
});
var task2 = Task.Run(async () =>
{
await en2.replacedertResult(1, 2, 3, 4, 5);
});
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Complete();
await task1;
await task2;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_2_Consumers_Error()
{
var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));
var en1 = push.GetAsyncEnumerator(default);
var en2 = push.GetAsyncEnumerator(default);
var task1 = Task.Run(async () =>
{
await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
});
var task2 = Task.Run(async () =>
{
await en2.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
});
for (var i = 1; i <= 5; i++)
{
await push.Next(i);
}
await push.Error(new InvalidOperationException());
await task1;
await task2;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_Bounded_1_Normal()
{
var push = new ReplayAsyncEnumerable<int>(1, TimeSpan.FromHours(1));
await push.Next(1);
await push.Next(2);
var t1 = push.replacedertResult(2, 3, 4, 5);
await push.Next(3);
await push.Next(4);
await push.Next(5);
await push.Complete();
await t1;
await push.replacedertResult(5);
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void Timed_Long()
{
const long n = 1_000_000;
var push = new ReplayAsyncEnumerable<long>(TimeSpan.FromHours(1));
var t = push
.Reduce((a, b) => a + b)
.replacedertResult(n * (n + 1) / 2);
for (var i = 1; i <= n; i++)
{
await push.Next(i);
}
await push.Complete();
await t;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void SizedTimed_Long()
{
const long n = 1_000_000;
var push = new ReplayAsyncEnumerable<long>(10, TimeSpan.FromHours(1));
var t = push
.Reduce((a, b) => a + b)
.replacedertResult(n * (n + 1) / 2);
for (var i = 1; i <= n; i++)
{
await push.Next(i);
}
await push.Complete();
await t;
}
19
Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void TimedSized_Long_Halfway()
{
const long n = 1_000_000;
var push = new ReplayAsyncEnumerable<long>((int)n, TimeSpan.FromHours(1));
var t = default(ValueTask);
for (var i = 1; i <= n; i++)
{
await push.Next(i);
if (i * 2 == n)
{
t = push
.Reduce((a, b) => a + b)
.replacedertResult(n * (n + 1) / 2);
}
}
await push.Complete();
await t;
}
19
Source : DateTimeUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
private static bool TryReadOffset(StringReference offsetText, int startIndex, out TimeSpan offset)
{
bool negative = (offsetText[startIndex] == '-');
int hours;
if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success)
{
offset = default(TimeSpan);
return false;
}
int minutes = 0;
if (offsetText.Length - startIndex > 5)
{
if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 3, 2, out minutes) != ParseResult.Success)
{
offset = default(TimeSpan);
return false;
}
}
offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
if (negative)
{
offset = offset.Negate();
}
return true;
}
19
Source : CustomQueueProcessorFactory.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
protected override async Task ReleaseMessageAsync(CloudQueueMessage message, FunctionResult result, TimeSpan visibilityTimeout, CancellationToken cancellationToken)
{
visibilityTimeout = message.DequeueCount switch
{
1 => TimeSpan.FromSeconds(10),
2 => TimeSpan.FromSeconds(30),
3 => TimeSpan.FromMinutes(1),
4 => TimeSpan.FromMinutes(5),
5 => TimeSpan.FromMinutes(10),
6 => TimeSpan.FromMinutes(30),
7 => TimeSpan.FromHours(1),
8 => TimeSpan.FromHours(3),
9 => TimeSpan.FromHours(6),
10 => TimeSpan.FromHours(12),
11 => TimeSpan.FromHours(12),
_ => visibilityTimeout,
};
19
Source : SyncCloudStatusCheckJob.cs
with GNU General Public License v3.0
from Amazing-Favorites
with GNU General Public License v3.0
from Amazing-Favorites
public ValueTask StartAsync()
{
_jobHandler = _eventSubject
.Concat(Observable.Interval(TimeSpan.FromHours(1)))
.Select(_ => Observable.FromAsync(async () =>
{
try
{
await RunSyncAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Failed");
}
}))
.Concat()
.Subscribe();
_eventSubject.OnNext(1);
return ValueTask.CompletedTask;
}
19
Source : DailyWorkRecordHeader.cs
with MIT License
from ambleside138
with MIT License
from ambleside138
public TimeSpan CalcExpectedTotalWorkTimeSpan()
{
var startTime = _DailyWorkTaskUnits.SelectMany(u => u.WorkingTimeRanges).Min(t => t.TimePeriod.StartDateTime);
var endTime = _DailyWorkTaskUnits.SelectMany(u => u.WorkingTimeRanges).Where(t => t.TimePeriod.IsStopped).Max(t => t.TimePeriod.EndDateTime.Value);
// 実際の勤務時間に近づける
if(WorkingHour != null)
{
if(WorkingHour.StartTime.HasValue)
{
startTime = WorkingHour.StartTime.Value;
}
if (WorkingHour.EndTime.HasValue)
{
endTime = WorkingHour.EndTime.Value;
}
}
var workingTime = endTime - startTime;
// 労働基準法第34条で、
// 労働時間が6時間を超え、8時間以下の場合は少なくとも45分
// 8時間を超える場合は、少なくとも1時間の休憩を与えなければならない、と定めています
if (workingTime.Hours > 8)
{
return workingTime - TimeSpan.FromHours(1); // 1時間の休憩
}
else if(workingTime.Hours > 6)
{
return workingTime - TimeSpan.FromMinutes(45); // 45分の休憩
}
else
{
return workingTime;
}
}
19
Source : CheckForUpdates.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public static void MaybePerformUpdateCheck(IAnkhServiceProvider context)
{
if (context == null)
throw new ArgumentNullException("context");
if (_checkedOnce)
return;
_checkedOnce = true;
IAnkhConfigurationService config = context.GetService<IAnkhConfigurationService>();
using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
{
int interval = 24 * 6; // 6 days
object value = rk.GetValue("Interval");
if (value is int)
{
interval = (int)value;
if (interval <= 0)
return;
}
TimeSpan ts = TimeSpan.FromHours(interval);
value = rk.GetValue("LastVersion");
if (IsDevVersion() || (value is string && (string)value == GetCurrentVersion(context).ToString()))
{
value = rk.GetValue("LastCheck");
long lv;
if (value is string && long.TryParse((string)value, out lv))
{
DateTime lc = new DateTime(lv, DateTimeKind.Utc);
if ((lc + ts) > DateTime.UtcNow)
return;
// TODO: Check the number of fails to increase the check interval
}
}
}
context.GetService<IAnkhScheduler>().Schedule(new TimeSpan(0, 0, 20), AnkhCommand.CheckForUpdates);
}
19
Source : JsonParser.cs
with Apache License 2.0
from anadventureisu
with Apache License 2.0
from anadventureisu
public static void Parse(string json, AppState state)
{
JObject data = JObject.Parse(json);
// Update shares
state.SharesAccepted = (int)data["shares"]["num_accepted"];
state.SharesRejected = (int)data["shares"]["num_rejected"];
state.SharesInvalid = (int)data["shares"]["num_invalid"];
state.SharesOutdated = (int)data["shares"]["num_outdated"];
state.SharesNetworkError = (int)data["shares"]["num_network_fail"];
state.TotalShares = state.SharesAccepted + state.SharesInvalid + state.SharesNetworkError + state.SharesOutdated + state.SharesRejected;
// Update devices.
foreach (JToken device in data["devices"])
{
int index = (int)device["device_id"];
GpuSample sample = new GpuSample(DateTime.Now, (long)device["hash_rate"]/1000, (int)device["gpu_fan_rpm"], (int)device["gpu_temperature"]);
GpuState gpu = state.GetGpu(index);
gpu.AddSample(sample);
gpu.UpdateAverages();
gpu.PruneSamplesOlderThan(TimeSpan.FromHours(1));
}
state.UpdateGlobalRates();
}
19
Source : Class1.cs
with MIT License
from andersnm
with MIT License
from andersnm
[TestMethod]
public void TestTimeSpan()
{
Test(TimeSpan.FromHours(100), "[hh]:mm:ss", "100:00:00");
Test(TimeSpan.FromHours(100), "[mm]:ss", "6000:00");
Test(TimeSpan.FromMilliseconds(100 * 60 * 60 * 1000 + 123), "[mm]:ss.000", "6000:00.123");
Test(new TimeSpan(1, 2, 31, 45), "[hh]:mm:ss", "26:31:45");
Test(new TimeSpan(1, 2, 31, 44, 500), "[hh]:mm:ss", "26:31:45");
Test(new TimeSpan(1, 2, 31, 44, 500), "[hh]:mm:ss.000", "26:31:44.500");
Test(new TimeSpan(-1, -2, -31, -45), "[hh]:mm:ss", "-26:31:45");
Test(new TimeSpan(0, -2, -31, -45), "[hh]:mm:ss", "-02:31:45");
Test(new TimeSpan(0, -2, -31, -44, -500), "[hh]:mm:ss", "-02:31:45");
Test(new TimeSpan(0, -2, -31, -44, -500), "[hh]:mm:ss.000", "-02:31:44.500");
}
19
Source : Startup.cs
with MIT License
from andrewlock
with MIT License
from andrewlock
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddHsts(options =>
{
options.MaxAge = TimeSpan.FromHours(1);
});
}
19
Source : TimeSpanExtensionsTests.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
[Fact]
public void OneHour() => Check("01:00:00 (3600 sec)", TimeSpan.FromHours(1));
19
Source : LoadBalancingStrategiesTests.cs
with MIT License
from angelobreuer
with MIT License
from angelobreuer
[Fact]
public void TestScoreBalancingStrategy()
{
var badNode = new NodeStatistics(10, 200, TimeSpan.FromHours(60),
new MemoryStatistics { AllocatedMemory = 10000, FreeMemory = 1000, ReservableMemory = 1000, UsedMemory = 5000 },
new ProcessorStatistics { Cores = 10, NodeLoad = 100, SystemLoad = 100 },
new FrameStatistics { AverageDeficitFrames = 10, AverageFramesSent = 100000, AverageNulledFrames = 100 });
var goodNode = new NodeStatistics(1, 1, TimeSpan.FromSeconds(100),
new MemoryStatistics { AllocatedMemory = 1000, FreeMemory = 500, ReservableMemory = 100, UsedMemory = 1000 },
new ProcessorStatistics { Cores = 54, NodeLoad = 20, SystemLoad = 30 },
new FrameStatistics { AverageDeficitFrames = 0, AverageFramesSent = 10000, AverageNulledFrames = 0 });
var badScore = LoadBalancingStrategies.CalculateScore(badNode);
var goodScore = LoadBalancingStrategies.CalculateScore(goodNode);
replacedert.True(badScore < goodScore, $"bad score ({badScore}) < good score ({goodScore})");
}
19
Source : ChartElement.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
internal static double GetIntervalSize(
double current,
double interval,
DateTimeIntervalType type,
Series series,
double intervalOffset,
DateTimeIntervalType intervalOffsetType,
bool forceIntIndex,
bool forceAbsInterval)
{
// AxisName is not date.
if( type == DateTimeIntervalType.Number || type == DateTimeIntervalType.Auto )
{
return interval;
}
// Special case for indexed series
if(series != null && series.IsXValueIndexed)
{
// Check point index
int pointIndex = (int)Math.Ceiling(current - 1);
if(pointIndex < 0)
{
pointIndex = 0;
}
if(pointIndex >= series.Points.Count || series.Points.Count <= 1)
{
return interval;
}
// Get starting and ending values of the closest interval
double adjuster = 0;
double xValue = series.Points[pointIndex].XValue;
xValue = AlignIntervalStart(xValue, 1, type, null);
double xEndValue = xValue + GetIntervalSize(xValue, interval, type);
xEndValue += GetIntervalSize(xEndValue, intervalOffset, intervalOffsetType);
xValue += GetIntervalSize(xValue, intervalOffset, intervalOffsetType);
if(intervalOffset < 0)
{
xValue = xValue + GetIntervalSize(xValue, interval, type);
xEndValue = xEndValue + GetIntervalSize(xEndValue, interval, type);
}
// The first point in the series
if(pointIndex == 0 && current < 0)
{
// Round the first point value depending on the interval type
DateTime dateValue = DateTime.FromOADate(series.Points[pointIndex].XValue);
DateTime roundedDateValue = dateValue;
switch(type)
{
case(DateTimeIntervalType.Years): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Months): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Days): // Ignore hours,...
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
case(DateTimeIntervalType.Hours): //
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, dateValue.Hour,
dateValue.Minute, 0);
break;
case(DateTimeIntervalType.Minutes):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month,
dateValue.Day,
dateValue.Hour,
dateValue.Minute,
dateValue.Second);
break;
case(DateTimeIntervalType.Seconds):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month,
dateValue.Day,
dateValue.Hour,
dateValue.Minute,
dateValue.Second,
0);
break;
case(DateTimeIntervalType.Weeks):
roundedDateValue = new DateTime(dateValue.Year,
dateValue.Month, dateValue.Day, 0, 0, 0);
break;
}
// The first point value is exactly on the interval boundaries
if(roundedDateValue.ToOADate() == xValue || roundedDateValue.ToOADate() == xEndValue)
{
return - current + 1;
}
}
// Adjuster of 0.5 means that position should be between points
++pointIndex;
while(pointIndex < series.Points.Count)
{
if(series.Points[pointIndex].XValue >= xEndValue)
{
if(series.Points[pointIndex].XValue > xEndValue && !forceIntIndex)
{
adjuster = -0.5;
}
break;
}
++pointIndex;
}
// If last point outside of the max series index
if(pointIndex == series.Points.Count)
{
pointIndex += series.Points.Count/5 + 1;
}
double size = (pointIndex + 1) - current + adjuster;
return (size != 0) ? size : interval;
}
// Non indexed series
else
{
DateTime date = DateTime.FromOADate(current);
TimeSpan span = new TimeSpan(0);
if(type == DateTimeIntervalType.Days)
{
span = TimeSpan.FromDays(interval);
}
else if(type == DateTimeIntervalType.Hours)
{
span = TimeSpan.FromHours(interval);
}
else if(type == DateTimeIntervalType.Milliseconds)
{
span = TimeSpan.FromMilliseconds(interval);
}
else if(type == DateTimeIntervalType.Seconds)
{
span = TimeSpan.FromSeconds(interval);
}
else if(type == DateTimeIntervalType.Minutes)
{
span = TimeSpan.FromMinutes(interval);
}
else if(type == DateTimeIntervalType.Weeks)
{
span = TimeSpan.FromDays(7.0 * interval);
}
else if(type == DateTimeIntervalType.Months)
{
// Special case handling when current date points
// to the last day of the month
bool lastMonthDay = false;
if(date.Day == DateTime.DaysInMonth(date.Year, date.Month))
{
lastMonthDay = true;
}
// Add specified amount of months
date = date.AddMonths((int)Math.Floor(interval));
span = TimeSpan.FromDays(30.0 * ( interval - Math.Floor(interval) ));
// Check if last month of the day was used
if(lastMonthDay && span.Ticks == 0)
{
// Make sure the last day of the month is selected
int daysInMobth = DateTime.DaysInMonth(date.Year, date.Month);
date = date.AddDays(daysInMobth - date.Day);
}
}
else if(type == DateTimeIntervalType.Years)
{
date = date.AddYears((int)Math.Floor(interval));
span = TimeSpan.FromDays(365.0 * ( interval - Math.Floor(interval) ));
}
// Check if an absolute interval size must be returned
double result = date.Add(span).ToOADate() - current;
if(forceAbsInterval)
{
result = Math.Abs(result);
}
return result;
}
}
19
Source : RequestBot.cs
with GNU Lesser General Public License v3.0
from angturil
with GNU Lesser General Public License v3.0
from angturil
private void Awake()
{
DontDestroyOnLoad(gameObject);
Instance = this;
#if UNRELEASED
var startingmem = GC.GetTotalMemory(true);
//var folder = Path.Combine(Environment.CurrentDirectory, "userdata","streamcore");
//List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path
//List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
//DirectoryInfo di = new DirectoryInfo(folder);
//Dictionary<string, string> remap = new Dictionary<string, string>();
//foreach (var entry in listcollection.OpenList("all.list").list)
// {
// //Instance.QueueChatMessage($"Map {entry}");
// string[] remapparts = entry.Split('-');
// if (remapparts.Length == 2)
// {
// int o;
// if (Int32.TryParse(remapparts[1], out o))
// {
// try
// {
// remap.Add(remapparts[0], o.ToString("x"));
// }
// catch
// { }
// //Instance.QueueChatMessage($"Map {remapparts[0]} : {o.ToString("x")}");
// }
// }
//}
//Instance.QueueChatMessage($"Scanning lists");
//FullDirList(di, "*.deck");
//void FullDirList(DirectoryInfo dir, string searchPattern)
//{
// try
// {
// foreach (FileInfo f in dir.GetFiles(searchPattern))
// {
// var List = listcollection.OpenList(f.Name).list;
// for (int i=0;i<List.Count;i++)
// {
// if (remap.ContainsKey(List[i]))
// {
// //Instance.QueueChatMessage($"{List[i]} : {remap[List[i]]}");
// List[i] = remap[List[i]];
// }
// }
// listcollection.OpenList(f.Name).Writefile(f.Name);
// }
// }
// catch
// {
// Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
// return;
// }
//}
//NOTJSON.UNITTEST();
#endif
playedfilename = Path.Combine(Plugin.DataPath, "played.dat"); // Record of all the songs played in the current session
try
{
string filesToDelete = Path.Combine(Environment.CurrentDirectory, "FilesToDelete");
if (Directory.Exists(filesToDelete))
EmptyDirectory(filesToDelete);
try
{
DateTime LastBackup;
if (!DateTime.TryParse(RequestBotConfig.Instance.LastBackup,out LastBackup)) LastBackup=DateTime.MinValue;
TimeSpan TimeSinceBackup = DateTime.Now - LastBackup;
if (TimeSinceBackup > TimeSpan.FromHours(RequestBotConfig.Instance.SessionResetAfterXHours))
{
Backup();
}
}
catch(Exception ex)
{
Plugin.Log(ex.ToString());
Instance.QueueChatMessage("Failed to run Backup");
}
bool resetsession = true;
try
{
TimeSpan PlayedAge = GetFileAgeDifference(playedfilename);
if (PlayedAge < TimeSpan.FromHours(RequestBotConfig.Instance.SessionResetAfterXHours))
{
resetsession = false;
played = ReadJSON(playedfilename); // Read the songsplayed file if less than x hours have preplaceded
}
}
catch (Exception ex)
{
Plugin.Log(ex.ToString());
Instance.QueueChatMessage("Failed to clear played file");
}
if (RequestBotConfig.Instance.PPSearch) GetPPData(); // Start loading PP data
MapDatabase.LoadDatabase();
if (RequestBotConfig.Instance.LocalSearch) MapDatabase.LoadCustomSongs(); // This is a background process
if (resetsession==false || RequestBotConfig.Instance.PersistentRequestQueue) RequestQueue.Read(); // Might added the timespan check for this too. To be decided later.
RequestHistory.Read();
listcollection.OpenList("banlist.unique");
#if UNRELEASED
//GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
//GC.Collect();
//Instance.QueueChatMessage($"hashentries: {SongMap.hashcount} memory: {(GC.GetTotalMemory(false) - startingmem) / 1048576} MB");
#endif
listcollection.ClearOldList("duplicate.list", TimeSpan.FromHours(RequestBotConfig.Instance.SessionResetAfterXHours));
UpdateRequestUI();
InitializeCommands();
//EnhancedStreamChat.ChatHandler.ChatMessageFilters += MyChatMessageHandler; // TODO: Reimplement this filter maybe? Or maybe we put it directly into EnhancedStreamChat
COMMAND.CommandConfiguration();
RunStartupScripts();
ProcessRequestQueue();
RequestBotConfig.Instance.ConfigChangedEvent += OnConfigChangedEvent;
}
catch (Exception ex)
{
Plugin.Log(ex.ToString());
Instance.QueueChatMessage(ex.ToString());
}
}
19
Source : Startup.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// 注册App监控(搁置)
RegisterAppInsights(services);
#region 微软 Idenreplacedy 类库部分
// 添加 Microsoft.AspNetCore.Idenreplacedy.EnreplacedyFrameworkCore 服务
// ApplicationDbContext 上下文
services.AddDbContext<ApplicationDbContext>(options =>
// 配置地址
options.UseSqlServer(Configuration["ConnectionString"],
sqlServerOptionsAction: sqlOptions =>
{
// 迁移的应用
sqlOptions.Migrationsreplacedembly(typeof(Startup).GetTypeInfo().replacedembly.GetName().Name);
// 失败规则
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}));
// 添加用户角色配置
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>()
.AddEnreplacedyFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// 用户登录服务:Microsoft.Extensions.Idenreplacedy.Core包
services.AddTransient<ILoginService<ApplicationUser>, EFLoginService>();
// 跳转服务
services.AddTransient<IRedirectService, RedirectService>();
#endregion
#region 配置数据及保护数据部分
// 获取配置信息:对象方法
services.Configure<AppSettings>(Configuration);
// 获取配置信息:字节方法
if (Configuration.GetValue<string>("IsClusterEnv") == bool.TrueString)
{
// 数据保护
services.AddDataProtection(opts =>
{
opts.ApplicationDiscriminator = "eshop.idenreplacedy";
})
//Data Protection(数据安全)机制:为了确保Web应用敏感数据的安全存储,该机制提供了一个简单、基于非对称加密改进的、性能良好的、开箱即用的加密API用于数据保护。它不需要开发人员自行生成密钥,它会根据当前应用的运行环境,生成该应用独有的一个私钥。这在单一部署的情况下没有问题。所以在集群情况下,为了确保加密数据的互通,应用必须共享私钥。
//Microsoft.AspNetCore.DataProtection.StackExchangeRedis
.PersistKeysToRedis(ConnectionMultiplexer.Connect(Configuration["DPConnectionString"]), "DataProtection-Keys");
}
#endregion
#region 健康检查 服务部分
// 健康检查 Microsoft.Extensions.Diagnostics.HealthChecks
services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy())
// HealthChecks.SqlServer包
.AddSqlServer(Configuration["ConnectionString"],
name: "IdenreplacedyDB-check",
tags: new string[] { "IdenreplacedyDB" });
#endregion
#region Ids4 服务部分
var connectionString = Configuration["ConnectionString"];
var migrationsreplacedembly = typeof(Startup).GetTypeInfo().replacedembly.GetName().Name;
// 添加 IdenreplacedyServer4 服务,3.x版本
services.AddIdenreplacedyServer(x =>
{
x.IssuerUri = "null";
x.Authentication.CookieLifetime = TimeSpan.FromHours(2);
})
// 本地开发环境新增功能
.AddDevspacesIfNeeded(Configuration.GetValue("EnableDevspaces", false))
// 添加证书 idsrv3test.pfx 本地文件
.AddSigningCredential(Certificate.Get())
// 用户数据
.AddAspNetIdenreplacedy<ApplicationUser>()
// 配置数据
// ConfigurationDbContext 上下文
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
// sqlserver
builder.UseSqlServer(connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.Migrationsreplacedembly(migrationsreplacedembly);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
})
// 持久化授权数据
// PersistedGrantDbContext 上下文
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.Migrationsreplacedembly(migrationsreplacedembly);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
})
// 配置数据服务,获取请求上下文的数据
.Services.AddTransient<IProfileService, ProfileService>();
#endregion
// 添加mvc服务的三个子服务
services.AddControllers();
services.AddControllersWithViews();
services.AddRazorPages();
var container = new ContainerBuilder();
container.Populate(services);
// autofac 容器化
return new AutofacServiceProvider(container.Build());
}
19
Source : Startup.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var idenreplacedyUrl = configuration.GetValue<string>("IdenreplacedyUrl");
var callBackUrl = configuration.GetValue<string>("CallBackUrl");
// Add Authentication services
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(setup => setup.ExpireTimeSpan = TimeSpan.FromHours(2))
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = idenreplacedyUrl.ToString();
options.SignedOutRedirectUri = callBackUrl.ToString();
options.ClientId = "webhooksclient";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("webhooks");
});
return services;
}
19
Source : VideoCapture.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void DetectCapture(
XIVLog xivlog)
{
if (!xivlog.Log.StartsWith("00:") &&
!xivlog.Log.StartsWith("01:") &&
!xivlog.Log.StartsWith("02:") &&
!xivlog.Log.StartsWith("19:") &&
!xivlog.Log.StartsWith("21:"))
{
return;
}
// 攻略を開始した
var match = ContentStartLogRegex.Match(xivlog.Log);
if (match.Success)
{
this.contentName = match.Groups["content"]?.Value;
var contentName = !string.IsNullOrEmpty(this.contentName) ?
this.contentName :
ActGlobals.oFormActMain.CurrentZone;
if (Config.Instance.TryCountContentName != contentName ||
(DateTime.Now - Config.Instance.TryCountTimestamp) >=
TimeSpan.FromHours(Config.Instance.TryCountResetInterval))
{
this.TryCount = 0;
}
return;
}
// 攻略を終了した
match = ContentEndLogRegex.Match(xivlog.Log);
if (match.Success)
{
this.FinishRecording();
this.contentName = string.Empty;
WPFHelper.Invoke(() => replacedleCardView.ClosereplacedleCard());
return;
}
var isStart = StartCountdownRegex.IsMatch(xivlog.Log);
if (!isStart)
{
isStart = FeastStartRegex.IsMatch(xivlog.Log);
if (isStart)
{
this.inFeast = true;
this.contentName = ActGlobals.oFormActMain.CurrentZone;
if (Config.Instance.TryCountContentName != this.contentName ||
(DateTime.Now - Config.Instance.TryCountTimestamp) >=
TimeSpan.FromHours(Config.Instance.TryCountResetInterval))
{
this.TryCount = 0;
}
}
}
if (isStart ||
xivlog.Log.Contains("/xivlog rec"))
{
SystemSounds.Beep.Play();
this.deathCount = 0;
this.StartRecording();
return;
}
var isCancel = xivlog.Log.EndsWith("戦闘開始カウントがキャンセルされました。");
if (isCancel)
{
this.TryCount--;
}
if (isCancel ||
xivlog.Log.Contains("/xivlog stop") ||
StopVideoKeywords.Any(x => xivlog.Log.Contains(x)) ||
(this.inFeast && FeastEndRegex.IsMatch(xivlog.Log)))
{
this.FinishRecording();
SystemSounds.Beep.Play();
return;
}
// Player change
match = PlayerChangedLogRegex.Match(xivlog.Log);
if (match.Success)
{
this.defeatedLog = $"19:{match.Groups["player"]?.Value} was defeated";
return;
}
// Player defeated
if (xivlog.Log.StartsWith(this.defeatedLog))
{
this.deathCount++;
return;
}
}
19
Source : MeetingStartTime.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Sanitize()
{
if (StartTime.TotalHours > 24)
{
StartTime = TimeSpan.FromHours(24);
}
}
19
Source : TestAdaptiveTimer.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
[TestInitialize]
public void InitializeTests()
{
_dateTimeService = new MockDateTimeService();
_mtgStart = _theDate + TimeSpan.FromHours(19); // 7pm
_dateTimeService.Set(_mtgStart);
_items = GenerateTalkItems(_theDate);
var options = MockOptions.Create();
options.GenerateTimingReports = false;
options.MidWeekAdaptiveMode = AdaptiveMode.TwoWay;
options.MidWeekOrWeekend = MidWeekOrWeekend.MidWeek;
options.OperatingMode = OperatingMode.Automatic;
var optionsService = new Mock<IOptionsService>();
optionsService.Setup(o => o.Options).Returns(options);
optionsService.Setup(x => x.GetAdaptiveMode()).Returns(options.MidWeekAdaptiveMode);
_scheduleService = new Mock<ITalkScheduleService>();
_scheduleService.Setup(x => x.GetTalkScheduleItems()).Returns(_items);
_scheduleService.Setup(x => x.GetTalkScheduleItem(It.IsAny<int>())).Returns((int id) => _items.Single(y => y.Id == id));
_adaptiveTimerService = new AdaptiveTimerService(
optionsService.Object, _scheduleService.Object, _dateTimeService);
_adaptiveTimerService.SetMeetingStartTimeForTesting(_dateTimeService.UtcNow());
// complete most of the timers...
foreach (var item in _items)
{
if (item.Id == (int)TalkTypesAutoMode.LivingPart1)
{
break;
}
// each item exactly on time
item.CompletedTimeSecs = (int)item.ActualDuration.TotalSeconds;
}
}
19
Source : TestDateCalcs.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
[TestMethod]
public void TestNearest15Mins()
{
var tenAm = DateTime.Today + TimeSpan.FromHours(10);
var tenFifteenAm = DateTime.Today + TimeSpan.FromHours(10) + TimeSpan.FromMinutes(15);
var result = DateUtils.GetNearestQuarterOfAnHour(tenAm);
replacedert.AreEqual(result, tenAm);
var dt = tenAm.AddMinutes(5);
result = DateUtils.GetNearestQuarterOfAnHour(dt);
replacedert.AreEqual(result, tenAm);
dt = tenAm.AddMinutes(10);
result = DateUtils.GetNearestQuarterOfAnHour(dt);
replacedert.AreEqual(result, tenAm);
dt = tenAm.AddMinutes(11);
result = DateUtils.GetNearestQuarterOfAnHour(dt);
replacedert.AreEqual(result, tenFifteenAm);
}
See More Examples