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 : NotificationManager.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool Allow()
{
if (!_liveMode)
{
return false;
}
lock (_sync)
{
var now = DateTime.UtcNow;
if (now > _resetTime)
{
_count = 0;
// rate limiting set at 30/hour
_resetTime = now.Add(TimeSpan.FromHours(1));
}
if (_count < RateLimit)
{
_count++;
return true;
}
return false;
}
}
19
Source : GoodTilDateTimeInForce.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public DateTime GetForexOrderExpiryDateTime(Order order)
{
var cutOffTimeZone = TimeZones.NewYork;
var cutOffTimeSpan = TimeSpan.FromHours(17);
var expiryTime = Expiry.Date.Add(cutOffTimeSpan);
if (order.Time.Date == Expiry.Date)
{
// expiry date same as order date
var orderTime = order.Time.ConvertFromUtc(cutOffTimeZone);
if (orderTime.TimeOfDay > cutOffTimeSpan)
{
// order submitted after 5 PM, expiry on next date
expiryTime = expiryTime.AddDays(1);
}
}
return expiryTime.ConvertToUtc(cutOffTimeZone);
}
19
Source : IndexManager.cs
with MIT License
from capricornus-platform
with MIT License
from capricornus-platform
private string GetOrCreateIndex(string index, Func<string, bool> predicate, Action<string> factory)
{
if (_memoryCache.TryGetValue(index, out _))
{
return index;
}
if (!predicate(index))
{
factory(index);
}
_memoryCache.Set<bool>(index, true, TimeSpan.FromHours(1));
return index;
}
19
Source : OutboxEnqueueTests.cs
with MIT License
from cfrenzel
with MIT License
from cfrenzel
[Fact]
public async Task Should_set_delayed_dispatch()
{
var start = DateTime.UtcNow;
using (var scope = NewScope())
{
var db = scope.ServiceProvider.GetService<ApplicationDbContext>();
var outboxSession = new OutboxSession<ApplicationDbContext>(_fixture.Outbox, db);
await outboxSession.Dispatch(_fixture.Message.MessageType, _fixture.MessageBytes, null, null, new OutboxDispatchOptions()
{
Delay = TimeSpan.FromHours(1)
});
await db.SaveChangesAsync();
}
using (var scope = NewScope())
{
var db = scope.ServiceProvider.GetService<ApplicationDbContext>();
var outboxMessages = db.Set<OutboxMessage>()
.Include(x => x.MessageData)
.OrderBy(x => x.CreatedAtUtc)
.AsNoTracking()
.ToList();
var m = outboxMessages.Last();
m.PriorityDateUtc.ShouldBeInRange(start.AddMinutes(60), DateTime.UtcNow.AddMinutes(65));
}
}
19
Source : UtxoReferee.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public async Task<BannedUtxo> TryGetBannedAsync(OutPoint outpoint, bool notedToo)
{
if (BannedUtxos.TryGetValue(outpoint, out BannedUtxo bannedElem))
{
int maxBan = (int)TimeSpan.FromHours(RoundConfig.DosDurationHours).TotalMinutes;
int banLeftMinutes = maxBan - (int)bannedElem.BannedRemaining.TotalMinutes;
if (banLeftMinutes > 0)
{
if (bannedElem.IsNoted)
{
if (notedToo)
{
return new BannedUtxo(bannedElem.Utxo, bannedElem.Severity, bannedElem.TimeOfBan, true, bannedElem.BannedForRound);
}
else
{
return null;
}
}
else
{
return new BannedUtxo(bannedElem.Utxo, bannedElem.Severity, bannedElem.TimeOfBan, false, bannedElem.BannedForRound);
}
}
else
{
await UnbanAsync(outpoint).ConfigureAwait(false);
}
}
return null;
}
19
Source : BlockchainController.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
private async Task<StatusResponse> FetchStatusAsync()
{
StatusResponse status = new StatusResponse();
// Updating the status of the filters.
if (DateTimeOffset.UtcNow - Global.IndexBuilderService.LastFilterBuildTime > FilterTimeout)
{
// Checking if the last generated filter is created for one of the last two blocks on the blockchain.
var lastFilter = Global.IndexBuilderService.GetLastFilter();
var lastFilterHash = lastFilter.Header.BlockHash;
var bestHash = await RpcClient.GetBestBlockHashAsync();
var lastBlockHeader = await RpcClient.GetBlockHeaderAsync(bestHash);
var prevHash = lastBlockHeader.HashPrevBlock;
if (bestHash == lastFilterHash || prevHash == lastFilterHash)
{
status.FilterCreationActive = true;
}
}
else
{
status.FilterCreationActive = true;
}
// Updating the status of CoinJoin
var validInterval = TimeSpan.FromSeconds(Global.Coordinator.RoundConfig.InputRegistrationTimeout * 2);
if (validInterval < TimeSpan.FromHours(1))
{
validInterval = TimeSpan.FromHours(1);
}
if (DateTimeOffset.UtcNow - Global.Coordinator.LastSuccessfulCoinJoinTime < validInterval)
{
status.CoinJoinCreationActive = true;
}
return status;
}
19
Source : MemoryTests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[Fact]
public async Task CacheBasicBehaviorAsync()
{
var invoked = 0;
string ExpensiveComputation(string argument)
{
invoked++;
return "Hello " + argument;
}
var cache = new MemoryCache(new MemoryCacheOptions());
var expireKey1 = new CancellationTokenSource();
var result0 = await cache.AtomicGetOrCreateAsync(
"key1",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
entry.AddExpirationToken(new CancellationChangeToken(expireKey1.Token));
return Task.FromResult(ExpensiveComputation("World!"));
});
var result1 = await cache.AtomicGetOrCreateAsync(
"key2",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Lurking Wife!"));
});
var result2 = await cache.AtomicGetOrCreateAsync(
"key1",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("World!"));
});
replacedert.Equal(result0, result2);
replacedert.NotEqual(result0, result1);
replacedert.Equal(2, invoked);
// Make sure key1 expired.
expireKey1.Cancel();
var result3 = await cache.AtomicGetOrCreateAsync(
"key1",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Foo!"));
});
var result4 = await cache.AtomicGetOrCreateAsync(
"key2",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Bar!"));
});
replacedert.Equal(result1, result4);
replacedert.NotEqual(result0, result3);
replacedert.Equal(3, invoked);
}
19
Source : MemoryTests.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
[Fact]
public async Task MultiplesCachesAsync()
{
var invoked = 0;
string ExpensiveComputation(string argument)
{
invoked++;
return "Hello " + argument;
}
var cache1 = new MemoryCache(new MemoryCacheOptions());
var cache2 = new MemoryCache(new MemoryCacheOptions());
var result0 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("World!"));
});
var result1 = await cache2.AtomicGetOrCreateAsync(
"the-same-other-key",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Lurking Wife!"));
});
var result2 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("World!"));
});
replacedert.Equal(result0, result2);
replacedert.Equal(2, invoked);
// Make sure AtomicGetOrCreateAsync doesn't fail because another cache is disposed.
cache2.Dispose();
var result3 = await cache1.AtomicGetOrCreateAsync(
"the-same-key",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Foo!"));
});
replacedert.Equal("Hello World!", result3);
replacedert.Equal(2, invoked);
// Make sure cache2 call will fail.
await replacedert.ThrowsAsync<ObjectDisposedException>(async () => await cache2.AtomicGetOrCreateAsync(
"the-same-key",
(entry) =>
{
entry.SetAbsoluteExpiration(TimeSpan.FromHours(10));
return Task.FromResult(ExpensiveComputation("Foo!"));
}));
replacedert.Equal(2, invoked);
}
19
Source : UtcOffsetTypeTests.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
[Fact]
protected void UtcOffset_ExpectIsUtcOffsetToMatch()
{
// arrange
ScalarType scalar = CreateType<UtcOffsetType>();
var valueSyntax = TimeSpan.FromHours(12);
// act
var result = scalar.IsInstanceOfType(valueSyntax);
// replacedert
replacedert.True(result);
}
19
Source : HttpsServer.cs
with MIT License
from chronoxor
with MIT License
from chronoxor
public void AddStaticContent(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null)
{
timeout ??= TimeSpan.FromHours(1);
bool Handler(FileCache cache, string key, byte[] value, TimeSpan timespan)
{
HttpResponse header = new HttpResponse();
header.SetBegin(200);
header.SetContentType(Path.GetExtension(key));
header.SetHeader("Cache-Control", $"max-age={timespan.Seconds}");
header.SetBody(value);
return cache.Add(key, header.Cache.Data, timespan);
}
Cache.InsertPath(path, prefix, filter, timeout.Value, Handler);
}
19
Source : GetToken.cs
with MIT License
from clemensv
with MIT License
from clemensv
[FunctionName("GetToken")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] TokenRequestData input, TraceWriter log)
{
// pick up config
var serviceBusNamespace = GetSetting("ServiceBusNamespace");
if (serviceBusNamespace == null)
{
log.Error(@"ServiceBusNamespace not configured");
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Bad internal configuration") };
}
int serviceBusTokenTimeout;
if (!int.TryParse(GetSetting("ServiceBusTokenTimeoutSecs"), out serviceBusTokenTimeout))
{
serviceBusTokenTimeout = (int)TimeSpan.FromHours(8).TotalSeconds;
}
// check the given inputs
var path = input.Path;
if (string.IsNullOrWhiteSpace(input.Permission))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Missing permission and/or path") };
}
if (string.IsNullOrWhiteSpace(path))
{
path = "/";
}
// get the key config for the desired permission
string requestedPermission = input.Permission.ToLowerInvariant();
if (await IsCallerAuthorizedAsync(serviceBusNamespace, path, requestedPermission, ClaimsPrincipal.Current, log))
{
var permissionRule = GetPermissionRule(requestedPermission);
if (permissionRule == null)
{
log.Error($"Permission rule {requestedPermission} is invalid");
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Bad internal configuration") };
}
// issue the token
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(permissionRule.Item1, permissionRule.Item2);
UriBuilder enreplacedyUri = new UriBuilder("http", serviceBusNamespace, -1, input.Path);
var token = await tokenProvider.GetWebTokenAsync(enreplacedyUri.ToString(), requestedPermission, false, TimeSpan.FromMinutes(10));
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(token) };
}
else
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
19
Source : SubtotalSummaryFuncTests.cs
with MIT License
from ClosedXML
with MIT License
from ClosedXML
[Fact]
public void SumTimeSpanTest()
{
var sum = new SubtotalSummaryFunc("sum", 1);
Expression<Func<Test, object>> e = o => o.val;
sum.GetCalculateDelegate = type => (e.Compile());
sum.DataSource = new DataSource(new object[] { new Test(TimeSpan.FromHours(1)), new Test(TimeSpan.FromHours(2)), new Test(TimeSpan.FromHours(3)) });
sum.Calculate(sum.DataSource).Should().Be(TimeSpan.FromHours(6));
}
19
Source : SubtotalSummaryFuncTests.cs
with MIT License
from ClosedXML
with MIT License
from ClosedXML
[Fact]
public void AverageTimeSpanTest()
{
var sum = new SubtotalSummaryFunc("average", 1);
Expression<Func<Test, object>> e = o => o.val;
sum.GetCalculateDelegate = type => (e.Compile());
sum.DataSource = new DataSource(new object[] { new Test(TimeSpan.FromHours(1)), new Test(TimeSpan.FromHours(2)), new Test(TimeSpan.FromHours(3)) });
sum.Calculate(sum.DataSource).Should().Be(TimeSpan.FromHours(2));
}
19
Source : AmqpTest.cs
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
[Fact]
public void AmqpNormalizesTimestampsToUtc()
{
var cloudEvent = new CloudEvent
{
Type = "com.github.pull.create",
Source = new Uri("https://github.com/cloudevents/spec/pull/123"),
Id = "A234-1234-1234",
// 2018-04-05T18:31:00+01:00 => 2018-04-05T17:31:00Z
Time = new DateTimeOffset(2018, 4, 5, 18, 31, 0, TimeSpan.FromHours(1)),
DataContentType = MediaTypeNames.Text.Xml,
Data = "<much wow=\"xml\"/>"
};
var message = cloudEvent.ToAmqpMessage(ContentMode.Binary, new JsonEventFormatter());
var encodedAmqpMessage = message.Encode();
var message1 = Message.Decode(encodedAmqpMessage);
var receivedCloudEvent = message1.ToCloudEvent(new JsonEventFormatter());
replacedertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
}
19
Source : JsonEventFormatterTest.cs
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
[Fact]
public void EncodeStructuredModeMessage_V1Attributes()
{
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Data = "text", // Just so that it's reasonable to have a DataContentType
DataContentType = "text/plain",
DataSchema = new Uri("https://data-schema"),
Id = "event-id",
Source = new Uri("https://event-source"),
Subject = "event-subject",
Time = new DateTimeOffset(2021, 2, 19, 12, 34, 56, 789, TimeSpan.FromHours(1)),
Type = "event-type"
};
var encoded = new JsonEventFormatter().EncodeStructuredModeMessage(cloudEvent, out var contentType);
replacedert.Equal("application/cloudevents+json; charset=utf-8", contentType.ToString());
JObject obj = ParseJson(encoded);
var replacederter = new JTokenreplacederter
{
{ "data", JTokenType.String, "text" },
{ "datacontenttype", JTokenType.String, "text/plain" },
{ "dataschema", JTokenType.String, "https://data-schema" },
{ "id", JTokenType.String, "event-id" },
{ "source", JTokenType.String, "https://event-source" },
{ "specversion", JTokenType.String, "1.0" },
{ "subject", JTokenType.String, "event-subject" },
{ "time", JTokenType.String, "2021-02-19T12:34:56.789+01:00" },
{ "type", JTokenType.String, "event-type" },
};
replacederter.replacedertProperties(obj, replacedertCount: true);
}
19
Source : JsonEventFormatterTest.cs
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
[Fact]
public void EncodeStructuredModeMessage_V1Attributes()
{
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Data = "text", // Just so that it's reasonable to have a DataContentType
DataContentType = "text/plain",
DataSchema = new Uri("https://data-schema"),
Id = "event-id",
Source = new Uri("https://event-source"),
Subject = "event-subject",
Time = new DateTimeOffset(2021, 2, 19, 12, 34, 56, 789, TimeSpan.FromHours(1)),
Type = "event-type"
};
var encoded = new JsonEventFormatter().EncodeStructuredModeMessage(cloudEvent, out var contentType);
replacedert.Equal("application/cloudevents+json; charset=utf-8", contentType.ToString());
JsonElement obj = ParseJson(encoded);
var replacederter = new JsonElementreplacederter
{
{ "data", JsonValueKind.String, "text" },
{ "datacontenttype", JsonValueKind.String, "text/plain" },
{ "dataschema", JsonValueKind.String, "https://data-schema" },
{ "id", JsonValueKind.String, "event-id" },
{ "source", JsonValueKind.String, "https://event-source" },
{ "specversion", JsonValueKind.String, "1.0" },
{ "subject", JsonValueKind.String, "event-subject" },
{ "time", JsonValueKind.String, "2021-02-19T12:34:56.789+01:00" },
{ "type", JsonValueKind.String, "event-type" },
};
replacederter.replacedertProperties(obj, replacedertCount: true);
}
19
Source : TimestampsTest.cs
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
[Theory]
[InlineData("", 0)]
[InlineData(".0", 0)]
[InlineData(".1", 1_000_000)]
[InlineData(".12", 1_200_000)]
[InlineData(".123", 1_230_000)]
[InlineData(".1234", 1_234_000)]
[InlineData(".12345", 1_234_500)]
[InlineData(".123456", 1_234_560)]
[InlineData(".1234567", 1_234_567)]
// We truncate nanoseconds to the tick
[InlineData(".12345678", 1_234_567)]
[InlineData(".123456789", 1_234_567)]
// (Realistically we're unlikely to get any values with greater precision than nanoseconds, but
// we might as well test it.)
[InlineData(".12345678912345", 1_234_567)]
public void Parse_Success_VaryingFractionalSeconds(string fractionalPart, int expectedTicks)
{
string text = $"2021-01-18T14:52:01{fractionalPart}+05:00";
DateTimeOffset expected = new DateTimeOffset(2021, 1, 18, 14, 52, 1, 0, TimeSpan.FromHours(5))
.AddTicks(expectedTicks);
replacedertParseSuccess(expected, text);
}
19
Source : DocumentAppService.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
protected virtual async Task<DoreplacedentWithDetailsDto> GetDoreplacedentWithDetailsDtoAsync(
Project project,
string doreplacedentName,
string languageCode,
string version)
{
version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version;
var cacheKey = $"Doreplacedent@{project.ShortName}#{languageCode}#{doreplacedentName}#{version}";
async Task<DoreplacedentWithDetailsDto> GetDoreplacedentAsync()
{
Logger.LogInformation($"Not found in the cache. Requesting {doreplacedentName} from the store...");
var store = _doreplacedentStoreFactory.Create(project.DoreplacedentStoreType);
var doreplacedent = await store.GetDoreplacedentAsync(project, doreplacedentName, languageCode, version);
Logger.LogInformation($"Doreplacedent retrieved: {doreplacedentName}");
return CreateDoreplacedentWithDetailsDto(project, doreplacedent);
}
if (Debugger.IsAttached)
{
return await GetDoreplacedentAsync();
}
return await DoreplacedentCache.GetOrAddAsync(
cacheKey,
GetDoreplacedentAsync,
() => new DistributedCacheEntryOptions
{
//TODO: Configurable?
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2),
SlidingExpiration = TimeSpan.FromMinutes(30)
}
);
}
19
Source : ProjectAppService.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
private async Task<LanguageConfig> GetLanguageListInternalAsync(string shortName, string version)
{
var project = await _projectRepository.GetByShortNameAsync(shortName);
var store = _doreplacedentStoreFactory.Create(project.DoreplacedentStoreType);
async Task<LanguageConfig> GetLanguagesAsync()
{
return await store.GetLanguageListAsync(project, version);
}
return await LanguageCache.GetOrAddAsync(
project.ShortName,
GetLanguagesAsync,
() => new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24)
}
);
}
19
Source : DocumentAppService.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public async Task<DoreplacedentResourceDto> GetResourceAsync(GetDoreplacedentResourceInput input)
{
var project = await _projectRepository.GetAsync(input.ProjectId);
var cacheKey = $"Resource@{project.ShortName}#{input.LanguageCode}#{input.Name}#{input.Version}";
input.Version = string.IsNullOrWhiteSpace(input.Version) ? project.LatestVersionBranchName : input.Version;
async Task<DoreplacedentResourceDto> GetResourceAsync()
{
var store = _doreplacedentStoreFactory.Create(project.DoreplacedentStoreType);
var doreplacedentResource = await store.GetResource(project, input.Name, input.LanguageCode, input.Version);
return ObjectMapper.Map<DoreplacedentResource, DoreplacedentResourceDto>(doreplacedentResource);
}
if (Debugger.IsAttached)
{
return await GetResourceAsync();
}
return await ResourceCache.GetOrAddAsync(
cacheKey,
GetResourceAsync,
() => new DistributedCacheEntryOptions
{
//TODO: Configurable?
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6),
SlidingExpiration = TimeSpan.FromMinutes(30)
}
);
}
19
Source : ProjectAppService.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public async Task<ListResultDto<VersionInfoDto>> GetVersionsAsync(string shortName)
{
var project = await _projectRepository.GetByShortNameAsync(shortName);
var versions = await _versionCache.GetOrAddAsync(
project.ShortName,
() => GetVersionsAsync(project),
() => new DistributedCacheEntryOptions
{
//TODO: Configurable?
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12),
SlidingExpiration = TimeSpan.FromMinutes(60)
}
);
return new ListResultDto<VersionInfoDto>(
ObjectMapper.Map<List<VersionInfo>, List<VersionInfoDto>>(versions)
);
}
19
Source : TypeCacheConfigurationServiceTests.cs
with MIT License
from Color-Chan
with MIT License
from Color-Chan
[Test]
public void Should_throw_ArgumentOutOfRangeException_on_add_cache_config()
{
// Arrange
var typeCache = new TypeCacheConfigurationService(new OptionsWrapper<CacheConfiguration>(new CacheConfiguration()));
// Act & replacedert
replacedert.Throws<ArgumentOutOfRangeException>(() => typeCache.AddCacheConfig<string>(TimeSpan.FromDays(1), TimeSpan.FromHours(1)));
}
19
Source : StoryModel.cs
with MIT License
from CommunityToolkit
with MIT License
from CommunityToolkit
static string GetAgeOfStory(DateTimeOffset storyCreatedAt)
{
var timespanSinceStoryCreated = DateTimeOffset.UtcNow - storyCreatedAt;
return timespanSinceStoryCreated switch
{
TimeSpan storyAge when storyAge < TimeSpan.FromHours(1) => $"{Math.Ceiling(timespanSinceStoryCreated.TotalMinutes)} minutes",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(1) && storyAge < TimeSpan.FromHours(2) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hour",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(2) && storyAge < TimeSpan.FromHours(24) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hours",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(24) && storyAge < TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} day",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} days",
_ => string.Empty,
};
19
Source : TimeService.cs
with GNU General Public License v3.0
from control-net
with GNU General Public License v3.0
from control-net
public async Task SetUtcOffsetForUserAsync(DateTime userTime, MiunieUser user, MiunieChannel channel)
{
var offset = TimeSpan.FromHours(userTime.Hour - _dateTime.UtcNow.Hour);
user.UtcTimeOffset = offset;
_users.StoreUser(user);
await _messages.SendMessageAsync(channel, PhraseKey.TIME_NEW_OFFSET_SET);
}
19
Source : TimeService.cs
with GNU General Public License v3.0
from control-net
with GNU General Public License v3.0
from control-net
public async Task SetUtcOffsetForUserByAdminAsync(DateTime userTime, MiunieUser user, MiunieChannel channel)
{
var offset = TimeSpan.FromHours(userTime.Hour - _dateTime.UtcNow.Hour);
user.UtcTimeOffset = offset;
_users.StoreUser(user);
await _messages.SendMessageAsync(channel, PhraseKey.TIME_NEW_OFFSET_SET_ADMIN, user.Name);
}
19
Source : TimeServiceTests.cs
with GNU General Public License v3.0
from control-net
with GNU General Public License v3.0
from control-net
[Fact]
public async Task CorrectOffset_ShouldOutputCorrectTime()
{
var channel = CreateTestChannel();
var user = CreateUserWithOffset(TimeSpan.FromHours(2));
SetCurrentTime(new DateTime(2020, 2, 21, 20, 30, 0));
var expectedTime = new DateTime(2020, 2, 21, 22, 30, 0);
await _service.OutputCurrentTimeForUserAsync(user, channel);
replacedertCorrectTimeInfoSent(expectedTime);
replacedertNoOtherMessages();
}
19
Source : TimeServiceTests.cs
with GNU General Public License v3.0
from control-net
with GNU General Public License v3.0
from control-net
[Fact]
public async Task SettingNewOffset_ShouldSaveAndOutputInfo()
{
SetCurrentTime(new DateTime(2020, 2, 22, 10, 59, 4));
var channel = CreateTestChannel();
var user = CreateUserWithoutOffset();
var enteredDateTime = new DateTime(1, 1, 1, 8, 0, 0);
var expectedOffset = TimeSpan.FromHours(-2);
await _service.SetUtcOffsetForUserAsync(enteredDateTime, user, channel);
replacedertOffsetChangedInfoSent();
replacedertUserWithOffsetSaved(expectedOffset);
replacedertNoOtherMessages();
}
19
Source : HangFireSetup.cs
with Apache License 2.0
from CoreUnion
with Apache License 2.0
from CoreUnion
public static void AddHangFireSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
//注册Hangfire定时任务
var isEnabledRedis = AppSettingsConstVars.RedisUseTimedTask;
if (isEnabledRedis)
{
services.AddHangfire(x => x.UseRedisStorage(AppSettingsConstVars.RedisConfigConnectionString));
}
else
{
string dbTypeString = AppSettingsConstVars.DbDbType;
if (dbTypeString == DbType.MySql.ToString())
{
services.AddHangfire(x => x.UseStorage(new MySqlStorage(AppSettingsConstVars.DbSqlConnection, new MySqlStorageOptions
{
TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事务隔离级别。默认是读取已提交。
QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。
JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。
CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。
PrepareSchemaIfNecessary = true, //- 如果设置为true,则创建数据库表。默认是true。
DashboardJobListLimit = 50000, //- 仪表板作业列表限制。默认值为50000。
TransactionTimeout = TimeSpan.FromMinutes(1), //- 交易超时。默认为1分钟。
TablesPrefix = "Hangfire" //- 数据库中表的前缀。默认为none
})));
}
else if (dbTypeString == DbType.SqlServer.ToString())
{
services.AddHangfire(x => x.UseSqlServerStorage(AppSettingsConstVars.DbSqlConnection));
}
}
services.AddHangfireServer(options =>
{
options.Queues = new[] { [email protected](), GlobalEnumVars.HangFireQueuesConfig.apis.ToString(), GlobalEnumVars.HangFireQueuesConfig.web.ToString(), GlobalEnumVars.HangFireQueuesConfig.recurring.ToString() };
options.ServerTimeout = TimeSpan.FromMinutes(4);
options.SchedulePollingInterval = TimeSpan.FromSeconds(15);//秒级任务需要配置短点,一般任务可以配置默认时间,默认15秒
options.ShutdownTimeout = TimeSpan.FromMinutes(30); //超时时间
options.WorkerCount = Math.Max(Environment.ProcessorCount, 20); //工作线程数,当前允许的最大线程,默认20
});
}
19
Source : GitFileHistoryTest.cs
with MIT License
from corgibytes
with MIT License
from corgibytes
[Fact]
public void Dates()
{
var rubyFixturePath = Fixtures.Path("ruby", "nokotest");
var history = new GitFileHistory(rubyFixturePath, "Gemfile.lock");
var expectedDates = new List<DateTimeOffset>() {
new(2017, 01, 01, 00, 01, 29, TimeSpan.FromHours(-8)),
new(2018, 01, 01, 00, 00, 59, TimeSpan.FromHours(-8)),
new(2019, 01, 01, 00, 00, 46, TimeSpan.FromHours(-8))
};
19
Source : LibYearCalculatorTest.cs
with MIT License
from corgibytes
with MIT License
from corgibytes
[Fact]
public void ComputeAsOfOtherEdgeCase()
{
BuildBundlerManifestWithMiniPortileAndNokogiri();
var results = _calculator.ComputeAsOf(
new DateTimeOffset(2018, 02, 01, 00, 00, 00, TimeSpan.FromHours(-5))
);
replacedert.Equal(0.361, results.Total, 3);
replacedert.Equal(0.0, results["mini_portile2"].Value, 3);
replacedert.Equal("2.3.0", results["mini_portile2"].LatestVersion);
replacedert.False(results["mini_portile2"].UpgradeAvailable);
replacedert.Equal(0.361, results["nokogiri"].Value, 3);
replacedert.Equal("1.8.2", results["nokogiri"].LatestVersion);
replacedert.True(results["nokogiri"].UpgradeAvailable);
}
19
Source : LibYearCalculatorTest.cs
with MIT License
from corgibytes
with MIT License
from corgibytes
[Fact]
public void ComputeAsOfWithLatestVersionBeingPreReleaseVersion()
{
BuildBundlerManifest(new Dictionary<string, string>
{
{"google-protobuf", "3.10.0.rc.1"}
});
var results = _calculator.ComputeAsOf(
new DateTimeOffset(2019, 11, 25, 00, 00, 00, TimeSpan.FromHours(-5))
);
replacedert.Equal(0.214, results.Total, 3);
replacedert.Equal(0.214, results["google-protobuf"].Value, 3);
replacedert.Equal("3.10.0.rc.1", results["google-protobuf"].Version);
replacedert.Equal(
new DateTimeOffset(2019, 09, 05, 19, 43, 14, TimeSpan.Zero),
results["google-protobuf"].PublishedAt
);
replacedert.Equal("3.11.0.rc.2", results["google-protobuf"].LatestVersion);
replacedert.Equal(
new DateTimeOffset(2019, 11, 23, 00, 10, 38, TimeSpan.Zero),
results["google-protobuf"].LatestPublishedAt
);
replacedert.True(results["google-protobuf"].UpgradeAvailable);
}
19
Source : JsonTextReader.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
private TimeSpan ReadOffset(string offsetText)
{
bool negative = (offsetText[0] == '-');
int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
int minutes = 0;
if (offsetText.Length >= 5)
minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
if (negative)
offset = offset.Negate();
return offset;
}
19
Source : TmdbTrailerChannel.cs
with GNU General Public License v3.0
from crobibero
with GNU General Public License v3.0
from crobibero
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
yield return new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerStartup
};
yield return new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerDaily,
TimeOfDayTicks = TimeSpan.FromHours(4).Ticks
};
}
19
Source : SunriseSunset.cs
with GNU General Public License v3.0
from cumulusmx
with GNU General Public License v3.0
from cumulusmx
private static string HrsMinSec(double t)
{
//
// takes a time as a decimal number of hours between 0 and 23.9999...
// and returns a string with the time in hhmmss format
//
TimeSpan ts = TimeSpan.FromHours(t);
var hour = ts.Hours;
var min = ts.Minutes;
var sec = ts.Seconds;
//double hour = (int)Math.Floor(t);
//double min = (int)Math.Floor((t - hour) * 60 + 0.5);
return (hour.ToString("00") + min.ToString("00") + sec.ToString("00"));
//return "0000";
}
19
Source : GnssProductUrlsBulder.cs
with GNU Lesser General Public License v3.0
from czsgeo
with GNU Lesser General Public License v3.0
from czsgeo
public void SetTemplates(Time timeUtc)
{
var hours = timeUtc.Hour + timeUtc.Minute / 60.0;
if (hours < 6.1) // 当天尚未更新,回滚到前一天
{
var models = new List<string>()
{
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_18.sp3.Z",
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_12.sp3.Z",
};
var lstDay = timeUtc - TimeSpan.FromHours(24);
var dic = ELMarkerReplaceService.GetTimeKeyWordDictionary(lstDay);
var elService = new Gdp.ELMarkerReplaceService(dic);
var urls = elService.Get(models);
this.UrlTemplates[SatelliteType.G] = urls;
}
else if (hours < 12.1)
{
var models = new List<string>()
{
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_18.sp3.Z",
};
var lstDay = timeUtc - TimeSpan.FromHours(24);
var dic = ELMarkerReplaceService.GetTimeKeyWordDictionary(lstDay);
var elService = new Gdp.ELMarkerReplaceService(dic);
var urls = elService.Get(models);
urls.Add("ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_00.sp3.Z");
this.UrlTemplates[SatelliteType.G] = urls;
}
else if (hours < 18.1)
{
this.UrlTemplates[SatelliteType.G] = new List<string>()
{
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_12.sp3.Z",
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_00.sp3.Z",
};
}
else
{
this.UrlTemplates[SatelliteType.G] = new List<string>()
{
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_18.sp3.Z",
"ftp://cddis.gsfc.nasa.gov/pub/gps/products/{GpsWeek}/igu{GpsWeek}{DayOfWeek}_12.sp3.Z",
};
}
}
19
Source : StartupOptionPanel.cs
with MIT License
from dahall
with MIT License
from dahall
private void taskIdleDurationCheck_CheckedChanged(object sender, EventArgs e)
{
if (!onreplacedignment)
{
taskIdleDurationCombo.Value = TimeSpan.FromMinutes(10);
taskIdleWaitTimeoutCombo.Value = TimeSpan.FromHours(1);
td.Settings.RunOnlyIfIdle = taskIdleDurationCheck.Checked;
}
UpdateIdleSettingsControls();
}
19
Source : TaskService.cs
with MIT License
from dahall
with MIT License
from dahall
public Task AddTask([NotNull] string path, QuickTriggerType trigger, [NotNull] string exePath, string arguments = null, string userId = null, string preplacedword = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null)
{
// Create a trigger based on quick trigger
Trigger newTrigger;
switch (trigger)
{
case QuickTriggerType.Boot:
newTrigger = new BootTrigger();
break;
case QuickTriggerType.Idle:
newTrigger = new IdleTrigger();
break;
case QuickTriggerType.Logon:
newTrigger = new LogonTrigger();
break;
case QuickTriggerType.TaskRegistration:
newTrigger = new RegistrationTrigger();
break;
case QuickTriggerType.Hourly:
newTrigger = new DailyTrigger { Repereplacedion = new RepereplacedionPattern(TimeSpan.FromHours(1), TimeSpan.FromDays(1)) };
break;
case QuickTriggerType.Daily:
newTrigger = new DailyTrigger();
break;
case QuickTriggerType.Weekly:
newTrigger = new WeeklyTrigger();
break;
case QuickTriggerType.Monthly:
newTrigger = new MonthlyTrigger();
break;
default:
throw new ArgumentOutOfRangeException(nameof(trigger), trigger, null);
}
return AddTask(path, newTrigger, new ExecAction(exePath, arguments), userId, preplacedword, logonType, description);
}
19
Source : TriggerEditDialog.cs
with MIT License
from dahall
with MIT License
from dahall
private void delayCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (!onreplacedignment)
{
delaySpan.Enabled = delayCheckBox.Checked;
delaySpan.Value = delayCheckBox.Checked ? TimeSpan.FromHours(1) : TimeSpan.Zero;
}
}
19
Source : HomePanel.cs
with MIT License
from dahall
with MIT License
from dahall
private void EventStatusUpdate()
{
label4.Text = "Reading data...";
statusListView.Items.Clear();
statusListView.Groups.Clear();
statusListView.UseWaitCursor = true;
var span = TimeSpan.Zero;
switch (comboBox1.SelectedIndex)
{
case 0:
span = TimeSpan.FromHours(1);
break;
case 1:
span = TimeSpan.FromDays(1);
break;
case 2:
span = TimeSpan.FromDays(7);
break;
case 3:
span = TimeSpan.FromDays(30);
break;
}
if (currentEventTaskId != null)
CancelAsync(currentEventTaskId);
EventStatusGetAsync(span, currentEventTaskId = Guid.NewGuid());
/*statusBackgroundWorker.CancelAsync();
while (statusBackgroundWorker.IsBusy)
System.Threading.Thread.Sleep(250);
statusBackgroundWorker.RunWorkerAsync(comboBox1.SelectedIndex);*/
}
19
Source : TaskServiceCronExt.cs
with MIT License
from dahall
with MIT License
from dahall
private static IEnumerable<Trigger> ProcessCronTimes(CronExpression cron, Trigger baseTrigger)
{
// Sequential hours, every minute
// "* * * * *"
// "* 2-6 * * *"
if (cron.Minutes.FullRange && (cron.Hours.IsEvery || cron.Hours.IsRange))
{
System.Diagnostics.Debug.WriteLine("Minutes.FullRange && (Hours.IsEvery || Hours.IsRange)");
yield return MakeTrigger(
new TimeSpan(cron.Hours.FirstValue, 0, 0),
TimeSpan.FromMinutes(cron.Minutes.Increment),
TimeSpan.FromHours(cron.Hours.Duration));
}
// Non-sequential hours, every minute
// "* 3,5,6 * * *"
// "* 3-15/3 * * *"
else if (cron.Minutes.FullRange && (cron.Hours.IsList || cron.Hours.IsIncr))
{
System.Diagnostics.Debug.WriteLine("Minutes.FullRange && (Hours.IsList || Hours.IsIncr)");
foreach (var h in cron.Hours.Values)
{
yield return MakeTrigger(
new TimeSpan(h, 0, 0),
TimeSpan.FromMinutes(cron.Minutes.Increment),
TimeSpan.FromHours(1));
}
}
// Non-repeating minutes, every hour
// "3,6 * * * *" Every hour starting at 12:03 and 12:06
// "3-33 * * * *"
// "3-33/6 * * * *"
// "3,6 * 3-5 * *"
// "3-33 3-5 * * *"
// "3-33/6 3-5 * * *"
else if (!cron.Minutes.FullRange && (cron.Hours.IsEvery || cron.Hours.IsRange))
{
System.Diagnostics.Debug.WriteLine("!Minutes.FullRange && (Hours.IsEvery || Hours.IsRange)");
foreach (var m in cron.Minutes.Values)
{
yield return MakeTrigger(
new TimeSpan(cron.Hours.FirstValue, m, 0),
TimeSpan.FromHours(1),
TimeSpan.FromHours(cron.Hours.Duration));
}
}
// Sequential or repeating minutes, and non-sequential hours
else if ((cron.Minutes.IsRange || cron.Minutes.IsIncr) && (cron.Hours.IsList || cron.Hours.IsIncr))
{
System.Diagnostics.Debug.WriteLine("(Minutes.IsRange || Minutes.IsIncr) && (Hours.IsList || Hours.IsIncr)");
foreach (var h in cron.Hours.Values)
{
yield return MakeTrigger(
new TimeSpan(h, cron.Minutes.FirstValue, 0),
TimeSpan.FromMinutes(cron.Minutes.Increment),
TimeSpan.FromMinutes(cron.Minutes.Duration));
}
}
// Non-sequential, hours and minutes
// "3,6 3,6 * * *" Every day at 3:03, 3:06, 6:03 and 6:06
// "3/6 3/6 * * *" Every day at 3:03, 3:06, 6:03 and 6:06
else
{
System.Diagnostics.Debug.WriteLine("Minutes.IsList && (Hours.IsIncr || Hours.IsList)");
foreach (var h in cron.Hours.Values)
foreach (var m in cron.Minutes.Values)
yield return MakeTrigger(new TimeSpan(h, m, 0));
}
Trigger MakeTrigger(TimeSpan start, TimeSpan interval = default, TimeSpan duration = default)
{
var newTr = (Trigger)baseTrigger.Clone();
newTr.StartBoundary = newTr.StartBoundary.Date + start;
if (interval != default)
{
newTr.Repereplacedion.Interval = interval;
newTr.Repereplacedion.Duration = duration;
}
return newTr;
}
}
19
Source : Program.cs
with MIT License
from dahall
with MIT License
from dahall
internal static void LongTest(TaskService ts, TextWriter output, params string[] arg)
{
var user = WindowsIdenreplacedy.GetCurrent().Name;
var ver = ts.HighestSupportedVersion;
var isV12 = ver >= new Version(1, 2);
var isV13 = ver >= new Version(1, 3);
var isV14 = ver >= new Version(1, 4);
output.WriteLine($"Highest version: {ver}, Library version {TaskService.LibraryVersion}");
output.WriteLine("Server: {0} ({1}); User: {2}\\{3}", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected", ts.UserAccountDomain, ts.UserName);
output.WriteLine("Running tasks:");
try
{
foreach (var rt in ts.GetRunningTasks(true))
{
if (rt == null) continue;
output.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State);
if (ver.Minor > 0)
output.WriteLine(" Current Action: " + rt.CurrentAction);
}
}
catch (Exception ex) { output.WriteLine(" " + ex.Message); }
var filter = arg.Length > 0 ? arg[0] : string.Empty;
var tf = ts.RootFolder;
var tasks = tf.GetTasks(new Wildcard(filter));
output.WriteLine("\nRoot folder tasks matching \"{1}\" ({0}):", tasks.Count, filter);
foreach (var t in tasks)
try
{
output.WriteLine("+ {0}, {1} ({2}) - {3}; Actions:{4}; Triggers:{5}", t.Name, t.Definition.RegistrationInfo.Author, t.State, t.Definition.Settings.Compatibility, t.Definition.Actions.Count, t.Definition.Triggers.Count);
foreach (var trg in t.Definition.Triggers)
output.WriteLine(" + {0}", trg);
foreach (var act in t.Definition.Actions)
output.WriteLine(" = {0}", act);
}
catch { }
output.WriteLine("\n***Finding defrag task***");
var ft = ts.FindTask("*defrag*");
if (ft != null)
output.WriteLine("Defrag task found at " + ft.Path);
else
output.WriteLine("Defrag task not found.");
var tfs = tf.SubFolders;
if (tfs.Count > 0)
{
output.WriteLine("\nSub folders:");
try
{
foreach (var sf in tfs)
output.WriteLine("+ {0}", sf.Path);
}
catch (Exception ex)
{
output.WriteLine(ex.ToString());
}
}
if (isV12)
{
output.WriteLine("\n***Checking folder retrieval***");
try
{
const string testFolder = "David's TestFolder";
try { tf.CreateFolder(testFolder); }
catch (COMException cex) { if (cex.ErrorCode != -2147024713) throw; }
var sub = tf.SubFolders[testFolder];
output.WriteLine("\nSubfolder path: " + sub.Path);
try
{
ts.AddTask(testFolder + @"\MyTask", new DailyTrigger(), new ExecAction("notepad"));
output.WriteLine(" - Tasks: " + sub.Tasks.Count);
sub.DeleteTask("MyTask");
}
catch (Exception ex)
{
output.WriteLine(ex.ToString());
}
tf.DeleteFolder(testFolder);
}
catch (NotSupportedException) { }
catch (Exception ex)
{
output.WriteLine(ex.ToString());
}
}
output.WriteLine("\n***Checking task creation***");
try
{
var td = ts.NewTask();
td.Data = "Your data";
//td.Principal.UserId = "SYSTEM";
//td.Principal.LogonType = TaskLogonType.ServiceAccount;
td.Principal.Id = "Author";
td.Principal.LogonType = isV12 ? TaskLogonType.S4U : TaskLogonType.InteractiveToken;
td.RegistrationInfo.Author = "dahall";
td.RegistrationInfo.Description = "Does something";
td.RegistrationInfo.Doreplacedentation = "Don't pretend this is real.";
td.RegistrationInfo.Source = "Test App";
td.RegistrationInfo.URI = "test://app";
td.RegistrationInfo.Version = new Version(0, 9);
td.Settings.DisallowStartIfOnBatteries = true;
td.Settings.Enabled = false;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero; // FromHours(2);
td.Settings.Hidden = false;
td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20);
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10);
td.Settings.Priority = ProcessPriorityClreplaced.Normal;
td.Settings.RunOnlyIfIdle = true;
td.Settings.RunOnlyIfNetworkAvailable = true;
td.Settings.StopIfGoingOnBatteries = true;
if (isV12)
{
td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
td.RegistrationInfo.SecurityDescriptorSddlForm = "D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)";
//td.Settings.AllowDemandStart = false;
td.Settings.AllowHardTerminate = false;
td.Settings.Compatibility = TaskCompatibility.V2;
td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
td.Settings.StartWhenAvailable = true;
td.Settings.WakeToRun = true;
td.Settings.RestartCount = 5;
td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
//td.Settings.NetworkSettings.Id = new Guid("{99AF272D-BC5B-4F64-A5B7-8688392C13E6}");
}
if (isV13)
{
td.Settings.Compatibility = TaskCompatibility.V2_1;
td.Settings.DisallowStartOnRemoteAppSession = true;
td.Settings.UseUnifiedSchedulingEngine = false;
/*td.Principal.ProcessTokenSidType = TaskProcessTokenSidType.Unrestricted;
td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeBackupPrivilege);
td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeDebugPrivilege);
td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeImpersonatePrivilege);
output.Write("Priv: ");
//output.Write(td.Principal.RequiredPrivileges[0]);
foreach (TaskPrincipalPrivilege item in td.Principal.RequiredPrivileges)
output.Write(item.ToString() + ", ");
output.WriteLine();*/
}
if (isV14)
{
td.Settings.Compatibility = TaskCompatibility.V2_2;
td.Settings.Volatile = true;
if (td.Principal.LogonType == TaskLogonType.ServiceAccount)
{
td.Settings.MaintenanceSettings.Exclusive = true;
td.Settings.MaintenanceSettings.Period = TimeSpan.FromDays(5);
td.Settings.MaintenanceSettings.Deadline = TimeSpan.FromDays(15);
}
}
// Setup Triggers
if (isV12)
{
var bTrigger = td.Triggers.Add(new BootTrigger { Enabled = false }); //(BootTrigger)td.Triggers.AddNew(TaskTriggerType.Boot);
bTrigger.Delay = TimeSpan.FromMinutes(5);
}
var dTrigger = td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
if (isV12)
{
dTrigger.RandomDelay = TimeSpan.FromHours(2);
var eTrigger = td.Triggers.Add(new EventTrigger());
eTrigger.Subscription = "<QueryList><Query Id=\"0\" Path=\"Security\"><Select Path=\"Security\">*[System[Provider[@Name='VSSAudit'] and EventID=25]]</Select></Query></QueryList>";
eTrigger.ValueQueries.Add("Name", "Value");
eTrigger.ValueQueries["Name"] = "NewValue";
td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.ConsoleConnect, user));
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.ConsoleDisconnect));
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.RemoteConnect));
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.RemoteDisconnect));
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.SessionLock, user));
td.Triggers.Add(new SessionStateChangeTrigger(TaskSessionStateChangeType.SessionUnlock));
}
td.Triggers.Add(new IdleTrigger());
var lTrigger = td.Triggers.Add(new LogonTrigger());
if (isV12)
{
lTrigger.Delay = TimeSpan.FromMinutes(15);
lTrigger.UserId = user;
lTrigger.Repereplacedion.Interval = TimeSpan.FromSeconds(1000);
}
var mTrigger = td.Triggers.Add(new MonthlyTrigger());
mTrigger.DaysOfMonth = new[] { 3, 6, 10, 18 };
mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
if (isV12) mTrigger.RunOnLastDayOfMonth = true;
mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);
var mdTrigger = td.Triggers.Add(new MonthlyDOWTrigger());
mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
if (isV12) mdTrigger.RunOnLastWeekOfMonth = true;
mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;
var tTrigger = td.Triggers.Add(new TimeTrigger());
tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
if (isV12)
{
tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(19);
tTrigger.Id = "Time test";
}
tTrigger.Repereplacedion = new RepereplacedionPattern(TimeSpan.FromMinutes(17), TimeSpan.FromMinutes(21), true);
var wTrigger = td.Triggers.Add(new WeeklyTrigger());
wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
wTrigger.WeeksInterval = 3;
// Setup Actions
td.Actions.PowerShellConversion = PowerShellActionPlatformOption.All;
td.Actions.Add("notepad.exe", "c:\\test.log");
if (isV12 || (td.Actions.PowerShellConversion & PowerShellActionPlatformOption.Version1) != 0)
{
td.Actions.Context = "Author";
if (td.Principal.LogonType == TaskLogonType.InteractiveToken || td.Principal.LogonType == TaskLogonType.Group || td.Principal.LogonType == TaskLogonType.S4U)
td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
var email = new EmailAction("Testing", "[email protected]", "[email protected]", "You've got mail.", "mail.myisp.com")
{
Id = "Email",
Attachments = new object[] { (string)new TemporaryScopedFile() },
Priority = MailPriority.High
};
td.Actions.Add(email);
email = (EmailAction)td.Actions["Email"];
email.To = "[email protected]";
//email.HeaderFields.Add("Precedence", "bulk");
//email.HeaderFields["Importance"] = "low";
td.Actions.Add(new ComHandlerAction(new Guid("{BF300543-7BA5-4C17-A318-9BBDB7429A21}"), @"C:\Users\dahall\Doreplacedents\Visual Studio 2010\Projects\TaskHandlerProxy\TaskHandlerSample\bin\Release\TaskHandlerSample.dll|TaskHandlerSample.TaskHandler|MoreData"));
}
td.Actions[0] = new ExecAction("notepad.exe", "c:\\test2.log");
// Validate and Register task
WriteXml(td, "PreRegTest");
td.Validate(true);
var t = tf.RegisterTaskDefinition("Test1", td);
WriteXml(t);
// Try copying it
var td2 = ts.NewTask();
td2.Actions.PowerShellConversion = td.Actions.PowerShellConversion;
td2.Triggers.AddRange(td.Triggers.ToArray());
td2.Actions.AddRange(td.Actions.ToArray());
var t2 = tf.RegisterTaskDefinition("Test2", td2, TaskCreation.CreateOrUpdate, user, null, TaskLogonType.InteractiveToken);
WriteXml(t2.Definition, "ReRegTest");
tf.DeleteTask("Test2");
/*// Create raw task for V1 test with cleared and added actions
td2 = ts.NewTask();
td2.Actions.Clear();
System.Diagnostics.Debug.replacedert(td2.Actions.Count == 0);
td2.Triggers.Add(new TimeTrigger(DateTime.Now.AddDays(1)));
td2.Actions.Add("calc");
System.Diagnostics.Debug.replacedert(td2.Actions.Count == 1);
t2 = tf.RegisterTaskDefinition("Test2", td2);
tf.DeleteTask("Test2");*/
}
catch (Exception ex)
{
output.WriteLine(ex.ToString());
return;
}
// Display results
var runningTask = tf.Tasks["Test1"];
if (isV12 || (runningTask.Definition.Actions.PowerShellConversion & PowerShellActionPlatformOption.Version1) != 0)
Debug.replacedert(runningTask.Definition.Actions.Count == 4);
else
Debug.replacedert(runningTask.Definition.Actions.Count == 1);
WriteXml(runningTask.Definition, "RunRegTest");
output.WriteLine("\nNew task will next run at " + runningTask.NextRunTime);
var times = runningTask.GetRunTimes(DateTime.Now, DateTime.Now + TimeSpan.FromDays(7));
if (times.Length > 0)
{
output.WriteLine("\nNew task will run at the following times over the next week:");
foreach (var dt in times)
output.WriteLine(" {0}", dt);
}
output.WriteLine("\nNew task triggers:");
for (var i = 0; i < runningTask.Definition.Triggers.Count; i++)
output.WriteLine(" {0}: {1}", i, runningTask.Definition.Triggers[i]);
output.WriteLine("\nNew task actions:");
for (var i = 0; i < runningTask.Definition.Actions.Count; i++)
output.WriteLine(" {0}: {1}", i, runningTask.Definition.Actions[i]);
// Loop through event logs for this task and find action completed events newest to oldest
if (isV12)
{
output.WriteLine("\nTask history enumeration:");
var log = new TaskEventLog(@"\Microsoft\Windows\Autochk\Proxy", new[] { 201 }, DateTime.Now.AddDays(-7)) { EnumerateInReverse = false };
foreach (var ev in log)
output.WriteLine(" Completed action '{0}' ({2}) at {1}.", ev.DataValues["ActionName"], ev.TimeCreated.Value, ev.DataValues["ResultCode"]);
}
// Run ComHandler
//TaskService.RunComHandlerActionAsync(new Guid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"), i => output.WriteLine("Com task complete."), "5", 120000, (p, s) => output.WriteLine($"Com task running: {p}% complete = {s}"));
if (arg.Length > 0 && arg[0] == "new")
// Show on new editor
new TaskOptionsEditor(runningTask).ShowDialog();
else
// Show on traditional editor
DisplayTask(runningTask, true);
tf.DeleteTask("Test1");
}
19
Source : TimeSpan2.cs
with MIT License
from dahall
with MIT License
from dahall
public static TimeSpan2 FromHours(double value) => new TimeSpan2(TimeSpan.FromHours(value));
19
Source : ReflectionExtensionsTests.cs
with MIT License
from dahall
with MIT License
from dahall
[Test()]
public void InvokeMethodRetTest()
{
var dt = DateTime.Today;
replacedert.That(dt.InvokeMethod<long>("ToBinary"), Is.Not.EqualTo(0));
replacedert.That(dt.InvokeMethod<DateTime>("AddHours", (double)1), Is.EqualTo(dt + TimeSpan.FromHours(1)));
replacedert.That(dt.InvokeMethod<long>("ToBinary", Type.EmptyTypes, null), Is.Not.EqualTo(0));
replacedert.That(dt.InvokeMethod<DateTime>("AddHours", new[] { typeof(double) }, new object[] { 1f }), Is.EqualTo(dt + TimeSpan.FromHours(1)));
replacedert.That(() => dt.InvokeMethod<long>("ToBin"), Throws.Exception);
replacedert.That(() => dt.InvokeMethod<long>("ToBinary", 1), Throws.Exception);
replacedert.That(() => dt.InvokeMethod<DateTime>("ToBinary", 1), Throws.Exception);
replacedert.That(() => dt.InvokeMethod<TimeSpan>("Subtract", new[] { typeof(long) }, new object[] { 1 }), Throws.ArgumentException);
replacedert.That(() => dt.InvokeMethod<TimeSpan>("Subtract", new[] { typeof(DateTime) }, new object[] { 1 }), Throws.ArgumentException);
replacedert.That(() => dt.InvokeMethod<long>("Subtract", new[] { typeof(DateTime) }, new object[] { DateTime.Now }), Throws.ArgumentException);
}
19
Source : ReflectionExtensionsTests.cs
with MIT License
from dahall
with MIT License
from dahall
[Test()]
public void InvokeMethodTypeTest()
{
var dt = typeof(DateTime);
replacedert.That(dt.InvokeMethod<long>(new object[] { 2017, 1, 1 }, "ToBinary"), Is.Not.EqualTo(0));
replacedert.That(dt.InvokeMethod<DateTime>(new object[] { 2017, 1, 1 }, "AddHours", (double)1), Is.EqualTo(new DateTime(2017, 1, 1) + TimeSpan.FromHours(1)));
}
19
Source : DateTimeConverter.cs
with MIT License
from dahomey-technologies
with MIT License
from dahomey-technologies
private bool TryRead(ReadOnlySpan<byte> buffer, out DateTime value)
{
if (!TryReadInt32(ref buffer, 4, out int year))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)'-'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int month))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)'-'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int day))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)'T'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int hours))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)':'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int minutes))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)':'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int seconds))
{
value = default;
return false;
}
int milliseconds = 0;
if (TryReadByte(ref buffer, (byte)'.'))
{
if (!TryReadInt32(ref buffer, 1, out int digit))
{
value = default;
return false;
}
milliseconds = digit;
while (TryReadInt32(ref buffer, 1, out digit))
{
milliseconds = milliseconds * 10 + digit;
}
}
// unspecified time zone => replacedume local
if (buffer.IsEmpty)
{
value = new DateTime(year, month, day, hours, minutes, seconds, milliseconds, DateTimeKind.Local);
}
// UTC
else if (TryReadByte(ref buffer, (byte)'Z'))
{
value = new DateTime(year, month, day, hours, minutes, seconds, milliseconds, DateTimeKind.Utc);
}
// Other time zones => convert to local
else
{
bool negative;
if (TryReadByte(ref buffer, (byte)'-'))
{
negative = true;
}
else if (TryReadByte(ref buffer, (byte)'+'))
{
negative = false;
}
else
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int offsetHours))
{
value = default;
return false;
}
if (!TryReadByte(ref buffer, (byte)':'))
{
value = default;
return false;
}
if (!TryReadInt32(ref buffer, 2, out int offsetMinutes))
{
value = default;
return false;
}
if (negative)
{
offsetHours = -offsetHours;
offsetMinutes = -offsetMinutes;
}
DateTimeOffset offset = new DateTimeOffset(
year, month, day, hours, minutes, seconds, milliseconds,
TimeSpan.FromHours(offsetHours) + TimeSpan.FromMinutes(offsetMinutes));
value = offset.LocalDateTime;
}
return true;
}
19
Source : AddIdentity.cs
with MIT License
from damikun
with MIT License
from damikun
public static IServiceCollection AddIdenreplacedyConfiguration(
this IServiceCollection serviceCollection) {
// cookie options
serviceCollection.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
options.DefaultSignOutScheme = "oidc";
})
.AddCookie("cookie", options =>
{
// set session lifetime
options.ExpireTimeSpan = TimeSpan.FromHours(8);
// sliding or absolute
options.SlidingExpiration = false;
// host prefixed cookie name
options.Cookie.Name = "__SPA_FF";
// strict SameSite handling
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
// confidential client using code flow + PKCE
options.ClientId = "spa";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.ResponseMode = "query";
options.MapInboundClaims = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
// request scopes + refresh tokens
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("api");
options.Scope.Add("offline_access");
});
return serviceCollection;
}
19
Source : RefreshLibraryTask.cs
with MIT License
from danieladov
with MIT License
from danieladov
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
// Run this task every 24 hours
return new[] {
new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
};
}
19
Source : ThemeSongsTasks.cs
with MIT License
from danieladov
with MIT License
from danieladov
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
// Run this task every 24 hours
yield return new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerInterval,
IntervalTicks = TimeSpan.FromHours(24).Ticks
};
}
19
Source : ThemeSongsTasks.cs
with MIT License
from danieladov
with MIT License
from danieladov
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
// Run this task every 24 hours
yield return new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerInterval,
IntervalTicks = TimeSpan.FromHours(24).Ticks
};
}
19
Source : ReminderService.cs
with GNU Affero General Public License v3.0
from Daniele122898
with GNU Affero General Public License v3.0
from Daniele122898
private async void CheckReminders(object _)
{
// Change it since this might take a while or introduce some kind of lag
// so we dont accidentally want to have multiple instances running at the same time
_timer.Change(TimeSpan.FromHours(1), TimeSpan.FromHours(1));
try
{
using var scope = _scopeFactory.CreateScope();
var reminderRepo = scope.ServiceProvider.GetRequiredService<IReminderRepository>();
var reminders = await reminderRepo.GetAllRemindersThatAreDue().ConfigureAwait(false);
if (reminders == null || reminders.Count == 0) return;
// Otherwise work through the reminders
// User a for loop because it's faster than a foreach :)
for (int i = 0; i < reminders.Count; i++)
{
var reminder = reminders[i];
var user = await _userService.GetOrSetAndGet(reminder.UserId).ConfigureAwait(false);
if (!user.HasValue) continue;
try
{
var channel = await user.Some().GetOrCreateDMChannelAsync().ConfigureAwait(false);
if (channel == null) return;
var eb = new EmbedBuilder()
{
Color = SoraSocketCommandModule.Purple,
replacedle = "⏰ Reminder!",
Description = reminder.Message
};
await channel.SendMessageAsync(embed: eb.Build()).ConfigureAwait(false);
}
catch (Exception)
{
// This is probably due to the user not accepting DMs.
// not worth handling or doing anything about
// Like to have it here to be more explicit when reading the code. Just preference :)
// ReSharper disable once RedundantJumpStatement
continue;
}
}
// remove all the reminders
var reminderIds = reminders.Select(x => x.Id).ToList();
await reminderRepo.RemoveReminders(reminderIds).ConfigureAwait(false);
}
catch (Exception e)
{
_log.LogError(e, "Failed to send or manipulate reminders!");
}
finally
{
_timer.Change(TimeSpan.FromMinutes(TIMER_INTERVAL_MINS),
TimeSpan.FromMinutes(TIMER_INTERVAL_MINS));
}
}
See More Examples