Here are the examples of the csharp api System.TimeSpan.FromDays(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1480 Examples
19
Source : ConvertUtilTest.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestMethod]
public void IntStringToTimeSpan()
{
replacedert.AreEqual(TimeSpan.FromDays(122), ConvertUtil.GetTypedCellValue<TimeSpan>("122"));
}
19
Source : WorkSheet.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public void ReadWorkSheet()
{
FileStream instream = new FileStream(_worksheetPath + @"Worksheet.xlsx", FileMode.Open, FileAccess.ReadWrite);
using (ExcelPackage pck = new ExcelPackage(instream))
{
var ws = pck.Workbook.Worksheets["Perf"];
replacedert.AreEqual(ws.Cells["H6"].Formula, "B5+B6");
ws = pck.Workbook.Worksheets["Comment"];
var comment = ws.Cells["B2"].Comment;
replacedert.AreNotEqual(comment, null);
replacedert.AreEqual(comment.Author, "Jan Källman");
ws = pck.Workbook.Worksheets["Hidden"];
replacedert.AreEqual<eWorkSheetHidden>(ws.Hidden, eWorkSheetHidden.Hidden);
ws = pck.Workbook.Worksheets["VeryHidden"];
replacedert.AreEqual<eWorkSheetHidden>(ws.Hidden, eWorkSheetHidden.VeryHidden);
ws = pck.Workbook.Worksheets["RichText"];
replacedert.AreEqual("Room 02 & 03", ws.Cells["G1"].RichText.Text);
ws = pck.Workbook.Worksheets["HeaderImage"];
//replacedert.AreEqual(ws.HeaderFooter.Pictures.Count, 3);
ws = pck.Workbook.Worksheets["newsheet"];
replacedert.AreEqual(ws.Cells["F2"].Style.Font.UnderLine, true);
replacedert.AreEqual(ws.Cells["F2"].Style.Font.UnderLineType, ExcelUnderLineType.Double);
replacedert.AreEqual(ws.Cells["F3"].Style.Font.UnderLineType, ExcelUnderLineType.SingleAccounting);
replacedert.AreEqual(ws.Cells["F5"].Style.Font.UnderLineType, ExcelUnderLineType.None);
replacedert.AreEqual(ws.Cells["F5"].Style.Font.UnderLine, false);
replacedert.AreEqual(ws.Cells["T20"].GetValue<string>(), 0.396180555555556d.ToString(CultureInfo.CurrentCulture));
replacedert.AreEqual(ws.Cells["T20"].GetValue<int>(), 0);
replacedert.AreEqual(ws.Cells["T20"].GetValue<int?>(), 0);
replacedert.AreEqual(ws.Cells["T20"].GetValue<double>(), 0.396180555555556d);
replacedert.AreEqual(ws.Cells["T20"].GetValue<double?>(), 0.396180555555556d);
replacedert.AreEqual(ws.Cells["T20"].GetValue<decimal>(), 0.396180555555556m);
replacedert.AreEqual(ws.Cells["T20"].GetValue<decimal?>(), 0.396180555555556m);
replacedert.AreEqual(ws.Cells["T20"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["T20"].GetValue<bool?>(), true);
replacedert.AreEqual(ws.Cells["T20"].GetValue<DateTime>(), new DateTime(1899, 12, 30, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T20"].GetValue<DateTime?>(), new DateTime(1899, 12, 30, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T20"].GetValue<TimeSpan>(), new TimeSpan(693593, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T20"].GetValue<TimeSpan?>(), new TimeSpan(693593, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T20"].Text, "09:30:30");
replacedert.AreEqual(ws.Cells["T24"].GetValue<string>(), 1.39618055555556d.ToString(CultureInfo.CurrentCulture));
replacedert.AreEqual(ws.Cells["T24"].GetValue<int>(), 1);
replacedert.AreEqual(ws.Cells["T24"].GetValue<int?>(), 1);
replacedert.AreEqual(ws.Cells["T24"].GetValue<double>(), 1.39618055555556d);
replacedert.AreEqual(ws.Cells["T24"].GetValue<double?>(), 1.39618055555556d);
replacedert.AreEqual(ws.Cells["T24"].GetValue<decimal>(), 1.39618055555556m);
replacedert.AreEqual(ws.Cells["T24"].GetValue<decimal?>(), 1.39618055555556m);
replacedert.AreEqual(ws.Cells["T24"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["T24"].GetValue<bool?>(), true);
replacedert.AreEqual(ws.Cells["T24"].GetValue<DateTime>(), new DateTime(1899, 12, 31, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T24"].GetValue<DateTime?>(), new DateTime(1899, 12, 31, 9, 30, 30));
replacedert.AreEqual(ws.Cells["T24"].GetValue<TimeSpan>(), new TimeSpan(693593, 33, 30, 30));
replacedert.AreEqual(ws.Cells["T24"].GetValue<TimeSpan?>(), new TimeSpan(693593, 33, 30, 30));
replacedert.AreEqual(ws.Cells["T24"].Text, "09:30:30");
replacedert.AreEqual(ws.Cells["U20"].GetValue<string>(), "40179");
replacedert.AreEqual(ws.Cells["U20"].GetValue<int>(), 40179);
replacedert.AreEqual(ws.Cells["U20"].GetValue<int?>(), 40179);
replacedert.AreEqual(ws.Cells["U20"].GetValue<double>(), 40179d);
replacedert.AreEqual(ws.Cells["U20"].GetValue<double?>(), 40179d);
replacedert.AreEqual(ws.Cells["U20"].GetValue<decimal>(), 40179m);
replacedert.AreEqual(ws.Cells["U20"].GetValue<decimal?>(), 40179m);
replacedert.AreEqual(ws.Cells["U20"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["U20"].GetValue<bool?>(), true);
replacedert.AreEqual(ws.Cells["U20"].GetValue<DateTime>(), new DateTime(2010, 1, 1));
replacedert.AreEqual(ws.Cells["U20"].GetValue<DateTime?>(), new DateTime(2010, 1, 1));
replacedert.AreEqual(ws.Cells["U20"].Text, "2010-01-01");
replacedert.AreEqual(ws.Cells["V20"].GetValue<string>(), "102");
replacedert.AreEqual(ws.Cells["V20"].GetValue<int>(), 102);
replacedert.AreEqual(ws.Cells["V20"].GetValue<int?>(), 102);
replacedert.AreEqual(ws.Cells["V20"].GetValue<double>(), 102d);
replacedert.AreEqual(ws.Cells["V20"].GetValue<double?>(), 102d);
replacedert.AreEqual(ws.Cells["V20"].GetValue<decimal>(), 102m);
replacedert.AreEqual(ws.Cells["V20"].GetValue<decimal?>(), 102m);
replacedert.AreEqual(ws.Cells["V20"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["V20"].GetValue<bool?>(), true);
replacedert.AreEqual(ws.Cells["V20"].GetValue<DateTime>(), new DateTime(1900, 4, 11));
replacedert.AreEqual(ws.Cells["V20"].GetValue<DateTime?>(), new DateTime(1900, 4, 11));
replacedert.AreEqual(ws.Cells["V20"].Text,
$"$102{CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator}00");
replacedert.AreEqual(ws.Cells["W20"].GetValue<string>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<int>(), 0);
replacedert.AreEqual(ws.Cells["W20"].GetValue<int?>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<double>(), 0d);
replacedert.AreEqual(ws.Cells["W20"].GetValue<double?>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<decimal>(), 0m);
replacedert.AreEqual(ws.Cells["W20"].GetValue<decimal?>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<bool>(), false);
replacedert.AreEqual(ws.Cells["W20"].GetValue<bool?>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<DateTime>(), DateTime.MinValue);
replacedert.AreEqual(ws.Cells["W20"].GetValue<DateTime?>(), null);
replacedert.AreEqual(ws.Cells["W20"].GetValue<TimeSpan>(), TimeSpan.Zero);
replacedert.AreEqual(ws.Cells["W20"].GetValue<TimeSpan?>(), null);
replacedert.AreEqual(ws.Cells["W20"].Text, string.Empty);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<string>(), "True");
replacedert.AreEqual(ws.Cells["Y20"].GetValue<int>(), 1);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<int?>(), 1);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<double>(), 1d);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<double?>(), 1d);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<decimal>(), 1m);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<decimal?>(), 1m);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["Y20"].GetValue<bool?>(), true);
replacedert.IsInstanceOfType(GetValueException<DateTime>(ws.Cells["Y20"]), typeof(InvalidCastException));
replacedert.IsInstanceOfType(GetValueException<DateTime?>(ws.Cells["Y20"]), typeof(InvalidCastException));
replacedert.IsInstanceOfType(GetValueException<TimeSpan>(ws.Cells["Y20"]), typeof(InvalidCastException));
replacedert.IsInstanceOfType(GetValueException<TimeSpan?>(ws.Cells["Y20"]), typeof(InvalidCastException));
replacedert.AreEqual(ws.Cells["Z20"].GetValue<string>(), "Text2");
replacedert.IsInstanceOfType(GetValueException<int>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<int?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<double>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<double?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<decimal>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<decimal?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<bool>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<bool?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<DateTime>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<DateTime?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<TimeSpan>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<TimeSpan?>( ws.Cells["Z20"]), typeof(FormatException));
replacedert.AreEqual(ws.Cells["Z20"].Text, "Text2");
// even though value is set as integer, it is stored/exposed by EPPlust as double; feature?
//replacedert.IsInstanceOfType(ws.Cells["X19"].Value, typeof(int));
replacedert.AreEqual(ws.Cells["X19"].GetValue<string>(), "210");
replacedert.AreEqual(ws.Cells["X19"].GetValue<int>(), 210);
replacedert.AreEqual(ws.Cells["X19"].GetValue<int?>(), 210);
replacedert.AreEqual(ws.Cells["X19"].GetValue<double>(), 210d);
replacedert.AreEqual(ws.Cells["X19"].GetValue<double?>(), 210d);
replacedert.AreEqual(ws.Cells["X19"].GetValue<decimal>(), 210m);
replacedert.AreEqual(ws.Cells["X19"].GetValue<decimal?>(), 210m);
replacedert.AreEqual(ws.Cells["X19"].GetValue<bool>(), true);
replacedert.AreEqual(ws.Cells["X19"].GetValue<bool?>(), true);
// double is converted to DateTime and TimeSpan, but value is meaningless
replacedert.IsNull(GetValueException<DateTime>( ws.Cells["X19"]));
replacedert.IsNull(GetValueException<DateTime?>( ws.Cells["X19"]));
replacedert.IsNull(GetValueException<TimeSpan>( ws.Cells["X19"]));
replacedert.IsNull(GetValueException<TimeSpan?>( ws.Cells["X19"]));
replacedert.AreEqual(ws.Cells["X19"].Text, "210");
replacedert.IsInstanceOfType(ws.Cells["AA19"].Value, typeof(string));
replacedert.AreEqual(ws.Cells["AA19"].GetValue<string>(), "210");
replacedert.AreEqual(ws.Cells["AA19"].GetValue<int>(), 210);
replacedert.AreEqual(ws.Cells["AA19"].GetValue<int?>(), 210);
replacedert.AreEqual(ws.Cells["AA19"].GetValue<double>(), 210d);
replacedert.AreEqual(ws.Cells["AA19"].GetValue<double?>(), 210d);
replacedert.AreEqual(ws.Cells["AA19"].GetValue<decimal>(), 210m);
replacedert.AreEqual(ws.Cells["AA19"].GetValue<decimal?>(), 210m);
replacedert.IsInstanceOfType(GetValueException<bool>( ws.Cells["AA19"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<bool?>( ws.Cells["AA19"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<DateTime>( ws.Cells["AA19"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<DateTime?>( ws.Cells["AA19"]), typeof(FormatException));
replacedert.AreEqual(TimeSpan.FromDays(210), ws.Cells["AA19"].GetValue<TimeSpan>());
replacedert.AreEqual(TimeSpan.FromDays(210), ws.Cells["AA19"].GetValue<TimeSpan?>());
replacedert.AreEqual(ws.Cells["AA19"].Text, "210");
// blank string produces null for nullable primitive types and conversion to non-nullable types throws FormatException
replacedert.IsInstanceOfType(ws.Cells["AA18"].Value, typeof(string));
replacedert.IsInstanceOfType(GetValueException<int>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<double>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<decimal>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<bool>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<DateTime>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsInstanceOfType(GetValueException<TimeSpan>( ws.Cells["AA18"]), typeof(FormatException));
replacedert.IsNull(GetValueException<int?>( ws.Cells["AA18"]));
replacedert.IsNull(GetValueException<double?>( ws.Cells["AA18"]));
replacedert.IsNull(GetValueException<decimal?>( ws.Cells["AA18"]));
replacedert.IsNull(GetValueException<bool?>( ws.Cells["AA18"]));
replacedert.IsNull(GetValueException<DateTime?>( ws.Cells["AA18"]));
replacedert.IsNull(GetValueException<TimeSpan?>( ws.Cells["AA18"]));
replacedert.AreEqual(ws.Cells["AA18"].Text, " ");
}
instream.Close();
}
19
Source : MiddlewareHealthChecksAppMetricsBuilderExtensionsTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_override_settings_from_configuration()
{
var options = new HealthEndpointsOptions();
var provider = SetupServicesAndConfiguration(
o =>
{
o.HealthEndpointEnabled = true;
o.Timeout = TimeSpan.FromDays(1);
});
Action resolveOptions = () => { options = provider.GetRequiredService<IOptions<HealthEndpointsOptions>>().Value; };
resolveOptions.Should().NotThrow();
options.HealthEndpointEnabled.Should().Be(true);
options.PingEndpointEnabled.Should().Be(false);
options.Timeout.Should().Be(TimeSpan.FromDays(1));
}
19
Source : HealthReportingBuilderTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_use_reporter_of_type_and_override_flushinterval()
{
// Arrange
var builder = new HealthBuilder().Report.Using<TestReporter>(reportInterval: TimeSpan.FromDays(1));
// Act
var metrics = builder.Build();
var reporter = (metrics.Reporters as HealthReporterCollection)?.GetType<TestReporter>();
// replacedert
reporter?.ReportInterval.Should().Be(TimeSpan.FromDays(1));
}
19
Source : GroupAppService.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
public async Task<RemotingResult> ScanJoinAsync(string code, Guid employeeId, string employeeName)
{
if (code == null) throw new ArgumentNullException(nameof(code));
if (employeeId == Guid.Empty) throw new ArgumentException("must not be empty", nameof(employeeId));
var splited = code.Split(',');
if (splited.Length != 2) return RemotingResult.Fail(1);
if (!Guid.TryParse(splited[0], out Guid id)) return RemotingResult.Fail(1);
if (!Guid.TryParse(splited[1], out Guid _)) return RemotingResult.Fail(1);
var originalFingerprint = await _simpleKeyValueService.CheckAndGet(SKVContainer_ScanJoinCode,
id.ToString("N"), TimeSpan.FromDays(1));
if (splited[1] != originalFingerprint) return RemotingResult.Fail(1);
using (var db = new ServiceDbContext(_dbOptions))
{
using (var tx = db.Database.BeginTransaction())
{
try
{
var enreplacedy = await db.Groups.Include(o => o.Members)
.Where(o => o.Type == GroupType.CustomChat)
.FirstOrDefaultAsync(o => o.Id == id);
if (enreplacedy == null)
return RemotingResult.Fail(2);
if (enreplacedy.Members.Exists(o => o.EmployeeId == employeeId))
return RemotingResult.Fail(3);
enreplacedy.Members.Add(new GroupMember
{
EmployeeId = employeeId,
GroupId = id,
Joined = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
await _busMs.Publish(new GroupMembersUpdated { Id = enreplacedy.Id });
await _busMs.Publish(new GroupNotified
{
Id = enreplacedy.Id,
Notifies = new List<EventNotifyDto>
{
new EventNotifyDto
{
Target = NotifyTargetType.Conversation,
TargetId = enreplacedy.Id.ToString(),
Created = DateTimeOffset.UtcNow,
Text = employeeName,
TargetCategory = (int)GroupEventNotifyType.ParticipantAdded
}
}
});
tx.Commit();
return RemotingResult.Success();
}
catch (Exception ex)
{
tx.Rollback();
_logger.Error(ex, "UpdateAsync Transaction rollback");
return RemotingResult.Fail();
}
}
}
}
19
Source : EventGridPublisherBuilderTests.cs
with MIT License
from arcus-azure
with MIT License
from arcus-azure
[Fact]
public void WithExponentialRetryWithCircuitBroker_NegativeCircuitBrokenDuration_ShouldFailWithArgumentOutOfRangeException()
{
// Arrange
var negativeInterval = TimeSpan.FromDays(-1);
// replacedert
replacedert.Throws<ArgumentOutOfRangeException>(
() => CreateEventGridBuilder()
.WithExponentialRetry<Exception>(3)
.WithCircuitBreaker<Exception>(
exceptionsAllowedBeforeBreaking: 10,
durationOfBreak: negativeInterval));
}
19
Source : ProductionServerCertificates.cs
with MIT License
from ardalis
with MIT License
from ardalis
private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//see: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate.getexpirationdatestring?view=netcore-3.1#remarks
//Make sure we parse the DateTime.Parse(expirationdate) the same as GetExpirationDateString() does.
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var expirationDate = DateTime.Parse(certificate.GetExpirationDateString(), CultureInfo.InvariantCulture);
if (expirationDate - DateTime.Today < TimeSpan.FromDays(30))
{
throw new Exception("Time to renew the certificate!");
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
throw new Exception("Cert policy errors: " + sslPolicyErrors.ToString());
}
}
19
Source : TimeSpanResolverPack.cs
with MIT License
from areller
with MIT License
from areller
[RedILResolve(typeof(FromMethodResolver), (double) 86400000)]
public static TimeSpan FromDays(double value) => TimeSpan.FromDays(value);
19
Source : PostTimeConverter.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
public object Convert(object value, Type targetType, object parameter, string culture)
{
var date = (DateTime)value;
var hours = (DateTime.Now.ToUniversalTime() - date).TotalHours;
if (date.Date == DateTime.Today)
return date.ToString("t");
if (DateTime.Today - date.Date == TimeSpan.FromDays(1))
return $"{Resources.GetStringByKey("Yesterday").ToLower()} {date.ToString(Resources.GetStringByKey("Post_ShortTimeFormat"))}";
return date.ToString(Resources.GetStringByKey("Post_FullTimeFormat"));
}
19
Source : TimeFormattingExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static string SimpleFormat(this TimeSpan value)
{
bool negative = value < TimeSpan.Zero;
if (negative)
value = value.Negate();
string result;
if (value < TimeSpan.FromSeconds(1))
return "now";
if (value < TimeSpan.FromMinutes(1))
result = $"{value.Seconds}s";
else if (value < TimeSpan.FromHours(1))
result = $"{value.Minutes}min";
else if (value < TimeSpan.FromDays(1))
result = $"{value.Hours}h";
else if (value < TimeSpan.FromDays(7))
result = $"{value.Days}d";
else
result = $"{value.Days / 7}w";
if (negative)
result += " ago";
return result;
}
19
Source : RangeHeaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task HEADIfRangeWithOldDateShouldServeFullContent()
{
TestServer server = TestServer.Create(app => app.UseFileServer());
HttpResponseMessage original = await server.HttpClient.GetAsync("http://localhost/SubFolder/Ranges.txt");
var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/Ranges.txt");
req.Headers.Add("If-Range", original.Content.Headers.LastModified.Value.Subtract(TimeSpan.FromDays(1)).ToString("r"));
req.Headers.Add("Range", "bytes=0-10");
HttpResponseMessage resp = await server.HttpClient.SendAsync(req);
replacedert.Equal(HttpStatusCode.OK, resp.StatusCode);
replacedert.Null(resp.Content.Headers.ContentRange);
replacedert.Equal(62, resp.Content.Headers.ContentLength);
replacedert.Equal(string.Empty, await resp.Content.ReadreplacedtringAsync());
}
19
Source : RangeHeaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task IfRangeWithOldDateShouldServeFullContent()
{
TestServer server = TestServer.Create(app => app.UseFileServer());
HttpResponseMessage original = await server.HttpClient.GetAsync("http://localhost/SubFolder/Ranges.txt");
var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/Ranges.txt");
req.Headers.Add("If-Range", original.Content.Headers.LastModified.Value.Subtract(TimeSpan.FromDays(1)).ToString("r"));
req.Headers.Add("Range", "bytes=0-10");
HttpResponseMessage resp = await server.HttpClient.SendAsync(req);
replacedert.Equal(HttpStatusCode.OK, resp.StatusCode);
replacedert.Null(resp.Content.Headers.ContentRange);
replacedert.Equal(62, resp.Content.Headers.ContentLength);
replacedert.Equal("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", await resp.Content.ReadreplacedtringAsync());
}
19
Source : CustomPolicyProviderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task MinimumAge10WorksIfOldEnough()
{
// Arrange & Act
var signIn = await SignIn(Client, "Dude", DateTime.Now.Subtract(TimeSpan.FromDays(365 * 20)).ToShortDateString());
replacedert.Equal(HttpStatusCode.OK, signIn.StatusCode);
var response = await Client.GetAsync("/Home/MinimumAge10");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Contains("Welcome, Dude", content);
replacedert.Contains("Welcome to a page restricted to users 10 or older", content);
}
19
Source : CustomPolicyProviderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task MinimumAge10FailsIfNotOldEnough()
{
// Arrange & Act
var signIn = await SignIn(Client, "Dude", DateTime.Now.Subtract(TimeSpan.FromDays(365 * 5)).ToShortDateString());
replacedert.Equal(HttpStatusCode.OK, signIn.StatusCode);
var response = await Client.GetAsync("/Home/MinimumAge10");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Contains("Access Denied: Dude is not authorized to view this page.", content);
}
19
Source : CustomPolicyProviderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task MinimumAge50WorksIfOldEnough()
{
// Arrange & Act
var signIn = await SignIn(Client, "Dude", DateTime.Now.Subtract(TimeSpan.FromDays(365 * 55)).ToShortDateString());
replacedert.Equal(HttpStatusCode.OK, signIn.StatusCode);
var response = await Client.GetAsync("/Home/MinimumAge50");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Contains("Welcome, Dude", content);
replacedert.Contains("Welcome to a page restricted to users 50 or older", content);
}
19
Source : CustomPolicyProviderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task MinimumAge50FailsIfNotOldEnough()
{
// Arrange & Act
var signIn = await SignIn(Client, "Dude", DateTime.Now.Subtract(TimeSpan.FromDays(365 * 20)).ToShortDateString());
replacedert.Equal(HttpStatusCode.OK, signIn.StatusCode);
var response = await Client.GetAsync("/Home/MinimumAge50");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Contains("Access Denied: Dude is not authorized to view this page.", content);
}
19
Source : UpdaterModule.cs
with GNU General Public License v3.0
from AutoDarkMode
with GNU General Public License v3.0
from AutoDarkMode
private void Check()
{
try
{
TimeSpan PollingCooldownTimeSpan = TimeSpan.FromDays(builder.Config.Updater.DaysBetweenUpdateCheck);
DateTime nextUpdate = builder.UpdaterData.LastCheck.Add(PollingCooldownTimeSpan);
if (DateTime.Now >= nextUpdate || (firstRun && builder.Config.Updater.CheckOnStart) || checkFailed)
{
//Logger.Debug("performing update check");
firstRun = false;
checkFailed = false;
_ = UpdateHandler.CheckNewVersion();
ApiResponse versionCheck = UpdateHandler.UpstreamResponse;
// check if a new version is available upstream
if (versionCheck.StatusCode == StatusCode.New)
{
ApiResponse creplacedeUpdater = UpdateHandler.CreplacedeUpdater();
// will preplaced through the update message if auto updater can be used
if (creplacedeUpdater.StatusCode == StatusCode.New)
{
// if mode is not silent, or auto install is disabled, show the notification to prompt the user
if (!builder.Config.Updater.Silent || !builder.Config.Updater.AutoInstall)
{
ToastHandler.InvokeUpdateToast();
}
if (builder.Config.Updater.AutoInstall)
{
Task.Run(() => UpdateHandler.Update()).Wait();
}
}
// display notification without update options if unavailable
else if (creplacedeUpdater.StatusCode == StatusCode.UnsupportedOperation || creplacedeUpdater.StatusCode == StatusCode.Disabled)
{
ToastHandler.InvokeUpdateToast(creplacedeUpdater: false);
}
}
else if (versionCheck.StatusCode == StatusCode.Err && versionCheck.Details != null && versionCheck.Details.Equals("WebException"))
{
Logger.Warn("rescheduling update check on next timer tick");
checkFailed = true;
}
}
else
{
Logger.Debug($"Next update check scheduled: {nextUpdate}");
}
}
catch (Exception ex)
{
Logger.Error(ex, "error while running update checker:");
}
}
19
Source : LikenessSourceTest.cs
with MIT License
from AutoFixture
with MIT License
from AutoFixture
[Fact]
public void ToLikenessWillReturnCorrectResult()
{
// Fixture setup
var expectedTimeSpan = TimeSpan.FromDays(1);
var sut = new LikenessSource<TimeSpan>(expectedTimeSpan);
// Exercise system
var result = sut.OfLikeness<string>();
// Verify outcome
replacedert.Equal(expectedTimeSpan, result.Value);
// Teardown
}
19
Source : Remove-S3MultipartUpload-Cmdlet.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
protected override void ProcessRecord()
{
base.ProcessRecord();
if (!ConfirmShouldProceed(this.Force.IsPresent, this.BucketName, "Remove-S3MultipartUploads"))
return;
DateTime initDate;
if (string.Equals(this.ParameterSetName, AbsoluteParameterSetName, StringComparison.OrdinalIgnoreCase))
initDate = InitiatedDate;
else
initDate = DateTime.Now - TimeSpan.FromDays(DaysBefore);
var context = new CmdletContext
{
BucketName = this.BucketName,
InitiatedDate = initDate
};
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
19
Source : LetsEncryptCertificateFetcher.cs
with BSD 3-Clause "New" or "Revised" License
from ayende
with BSD 3-Clause "New" or "Revised" License
from ayende
private async Task FetchCertificateFromLetsEncryptAsync()
{
_timer = new Timer(Renew, null, TimeSpan.FromDays(1), Timeout.InfiniteTimeSpan);
var challengerResponder = new LetEncryptHttpChallengerResponder();
var host = new WebHostBuilder()
.UseKestrel(options =>
{
options.Listen(_address, 80);
})
.UseSetting(WebHostDefaults.ApplicationKey, GetType().FullName)
.ConfigureServices(services =>
{
services.AddSingleton(typeof(IStartup),
challengerResponder);
}).Build();
var task = host.RunAsync();
using (host)
using (var client = new AcmeClient(WellKnownServers.LetsEncrypt))
{
// Create new registration
var account = await client.NewRegistraton("mailto:" + _email);
// Accept terms of services
account.Data.Agreement = account.GetTermsOfServiceUri();
await client.UpdateRegistration(account);
// Initialize authorization
var authz = await client.NewAuthorization(new AuthorizationIdentifier
{
Type = AuthorizationIdentifierTypes.Dns,
Value = _domain
});
// Comptue key authorization for http-01
var httpChallengeInfo = authz.Data.Challenges.First(c => c.Type == ChallengeTypes.Http01);
var keyAuthString = client.ComputeKeyAuthorization(httpChallengeInfo);
challengerResponder.ChallengeResponse = keyAuthString;
var httpChallenge = await client.CompleteChallenge(httpChallengeInfo);
// Check authorization status (use the proper challenge to check Authorization State)
authz = await client.GetAuthorization(httpChallenge.Location); // or dnsChallenge.Location
while (authz.Data.Status == EnreplacedyStatus.Pending)
{
// Wait for ACME server to validate the identifier
await Task.Delay(250);
authz = await client.GetAuthorization(httpChallenge.Location);
}
if (authz.Data.Status != EnreplacedyStatus.Valid)
throw new InvalidOperationException("Failed to authorize certificate: " + authz.Data.Status);
// Create certificate
var csr = new CertificationRequestBuilder();
csr.AddName("CN", _domain);
var cert = await client.NewCertificate(csr);
// Export Pfx
var pfxBuilder = cert.ToPfx();
var pfx = pfxBuilder.Build(_domain + " cert", "");
_certificate = new X509Certificate2(pfx);
_setCachedCertificate?.Invoke(_domain, pfx);
}
await task;
}
19
Source : WaveTest.cs
with MIT License
from azist
with MIT License
from azist
[Run]
public void Action_GetSetTimeSpan()
{
var initTs = TimeSpan.FromDays(10);
using (var wc = CreateWebClient())
{
var values = new NameValueCollection();
values.Add("ts", initTs.replacedtring());
byte[] bytes = wc.UploadValues(INTEGRATION_HTTP_ADDR + "GetSetTimeSpan", values);
string str = GetUTF8StringWOBOM(bytes);
var gotTs = TimeSpan.Parse(str);
Aver.AreEqual(initTs.Add(TimeSpan.FromDays(1)), gotTs);
}
}
19
Source : WaveForm.cs
with MIT License
from azist
with MIT License
from azist
public void Action_GetSetTimeSpan(WebClient wc)
{
var initTs = TimeSpan.FromDays(10);
//using (var wc = CreateWebClient())
{
var values = new NameValueCollection();
values.Add("ts", initTs.replacedtring());
byte[] bytes = wc.UploadValues(m_ServerURI + "GetSetTimeSpan", values);
string str = GetUTF8StringWOBOM(bytes);
var gotTs = TimeSpan.Parse(str);
if (initTs.Add(TimeSpan.FromDays(1)) != gotTs) throw new Exception();
}
}
19
Source : SerializerForm.cs
with MIT License
from azist
with MIT License
from azist
private Person2 make()
{
if (cnt>2) return null;
cnt++;
var p1 = new Person2{ Name = "Kumir Da", Age = 22 , PointA = new Point(25,36)};
//p1.IntArray = new int[3];
//p1.IntArray[0] = 11;
//p1.IntArray[1] = 22;
//p1.IntArray[2] = 33;
// p1.StringArray = new string[] {"aaa", "bovin", "zomama"};
//p1.StringArray2D = new string[2,3];
// p1.StringArray2D[1,1] = "Kolya";
// p1.StringArray2D[0,2] = "Sima";
//p1.IntArray3D = new int[2,2,4];
// p1.IntArray3D[0,0,0] = 180;
// p1.IntArray3D[1,1,3] = -11;
p1.ObjArray = new object[150];
p1.ObjArray[12] = 12;
p1.ObjArray[13] = true;
p1.ObjArray[14] = App.LocalizedTime;
p1.IntList.Add(12);
p1.IntList.Add(19);
p1.IntList.Add(-1890);
p1.IntList.Add(0);
p1.IntList.Add(991);
p1.Data1 = "ya loshad!";
p1.Data2 = TimeSpan.FromHours(12);
p1.Kozel1.Certified = true;
p1.Kozel1.KozelGrade = 789;
p1.Kozel1.Owner = new Person2{ Name = "Kozlopas", Age = 48 };
p1.Kozel2 = new Kozel{ Certified = false, KozelGrade = 2, Owner = new Person2{Name="Soloviev", Age = 98}};
p1.Father = new Person2{ Name = "Dodik Butcer", Age = 120 };
p1.Mother = new Person2{ Name = "Feiga Svinarenko", Age = 95, IsHappy = true, MarriageDate = App.LocalizedTime };
p1.Father.Mother = new Person2{Name = "Zlata Butcer", Age = 230, Father = p1};
p1.Sibling1 = new Person2{Name = "Cathy", Age = 17, IsHappy = true, MarriageDate = App.LocalizedTime, Data1 = 12};
p1.Sibling2 = new Person2{Name = "Jimmy", Age = 34, IsHappy = true, MarriageDate = App.LocalizedTime, Data1 = 212};
p1.Sibling3 = new Person2{Name = "Bob", Age = 7, IsHappy = true, MarriageDate = App.LocalizedTime, Data1 = 32};
p1.Sibling4 = new Person2{Name = "Karl", Age = 21, IsHappy = true, MarriageDate = App.LocalizedTime, Data1 = -432};
p1.Sibling5 = new Person2{Name = "Oleg", Age = 27, IsHappy = true, MarriageDate = App.LocalizedTime, Data1 = 552};
p1.Sibling1.Data1 = make();
p1.Sibling1.Data2 = p1;
p1.Sibling1.Father = new Person2{Name="David"};
p1.Sibling1.Father.Data1 = 123;
p1.Sibling1.Father.Data2 = TimeSpan.FromDays(12.2);
p1.Sibling1.Father.Data1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!";
p1.Sibling1.Father.Data2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
cnt--;
return p1;
}
19
Source : MiscUtilsTest.cs
with MIT License
from azist
with MIT License
from azist
private void checkDayOfWeek(DateTime now, DayOfWeek dayOfWeek)
{
var day = now.RoundToWeekDay(dayOfWeek);
var dt = (day - now.Date);
Aver.IsTrue(day.DayOfWeek == dayOfWeek && (TimeSpan.FromDays(0) <= dt) && (dt <= TimeSpan.FromDays(6)));
}
19
Source : MiscUtilsTest.cs
with MIT License
from azist
with MIT License
from azist
private void checkNextDayOfWeek(DateTime now, DayOfWeek dayOfWeek)
{
var day = now.RoundToNextWeekDay(dayOfWeek);
var dt = (day - now.Date);
Aver.IsTrue(day.DayOfWeek == dayOfWeek && (TimeSpan.FromDays(0) < dt) && (dt <= TimeSpan.FromDays(7)));
}
19
Source : IntegrationTester.cs
with MIT License
from azist
with MIT License
from azist
[Action]
public string GetSetTimeSpan(TimeSpan ts)
{
return ts.Add(TimeSpan.FromDays(1)).ToString();
}
19
Source : PODTests.cs
with MIT License
from azist
with MIT License
from azist
[Run]
public void RootPrimitiveWriteRead_timespan()
{
var originalData = TimeSpan.FromDays(12.4321);
var doc = new PortableObjectDoreplacedent(originalData);
var convertedData = doc.ToOriginalObject();
Aver.AreObjectsEqual(originalData, convertedData);
}
19
Source : Hydrant.cs
with GNU Affero General Public License v3.0
from b11p
with GNU Affero General Public License v3.0
from b11p
public void Start()
{
var mc = new MemoryCache(new MemoryCacheOptions());
var slidingExpiration = TimeSpan.FromDays(2);
_listener.MessageEvent += async (api, message) =>
{
// Workaround for go-cqhttp repeatedly post private message.
if (message is PrivateMessage p)
{
var cached = mc.GetOrCreate(p.MessageId, e =>
{
e.SetSlidingExpiration(slidingExpiration);
return p;
});
if (cached != p)
return;
}
// Message monitors
_ = _messageMonitorList.ForEachAsync(async m =>
{
using var scope = _serviceProvider.CreateScope();
try
{
var monitor = CreateServiceInstance<IMessageMonitor>(m.GetType(), scope);
await monitor.OnMessageAsync(message, api).ConfigureAwait(false);
}
catch (ExecutingException)
{
// ignored
}
catch (Exception e)
{
//_logger.LogException(e);
LogException(GetServiceName(m), "Monitor 的异常。", e);
}
});
// Commands
using var scope = _serviceProvider.CreateScope();
IMessageCommand? hit = default;
try
{
IMessageCommand? last = null;
try
{
hit = _messageCommandList
.Select(c => CreateServiceInstance<IMessageCommand>(c.GetType(), scope))
.FirstOrDefault(c => (last = c).ShouldResponse(message));
}
catch (Exception e)
{
//_logger.LogException(e);
LogException(GetServiceName(last), "ShouldResponse 方法引发了一个异常", e);
return;
}
var task = hit?.ProcessAsync(message, api);
if (task != null)
await task;
}
catch (ExecutingException e)
{
if (!string.IsNullOrEmpty(e.Message))
await api.SendMessageAsync(
endpoint: message.Endpoint,
message: e.Message
);
if (e.InnerException != null)
{
//_logger.LogException(e.InnerException);
LogException(GetServiceName(hit), "包含内部异常的执行异常", e.InnerException);
}
}
catch (Exception e) //when (_isInitialized == 0) // 暂时不会执行。
{
LogException(GetServiceName(hit), "有一些不好的事发生了。", e);
try
{
var name = GetServiceName(hit);
var hTask = ExceptionCaught_Command?.Invoke(name, e, api, message);
if (hTask != null)
await hTask;
}
catch (Exception he)
{
LogException("Exception handling", null, he);
}
}
};
// 跑定期任务
if (_regularTasks.Count > 0)
{
_plan.Start();
}
}
19
Source : RetriveRecommendationData.cs
with GNU Affero General Public License v3.0
from b11p
with GNU Affero General Public License v3.0
from b11p
private async Task Retrive()
{
var mode = Mode.Standard;
var userList = await _newbieContext.UserSnapshots.Where(s => s.Mode == mode).Select(s => new { s.UserId, s.Mode }).Distinct().ToListAsync().ConfigureAwait(false);
queueCount = userList.Count;
errorCount = 0;
var taskList = userList.Select(async u =>
{
try
{
IEnumerable<UserBest> bests = await _dataProvider.GetUserBestRetryAsync(u.UserId, u.Mode).ConfigureAwait(false);
if (bests?.All(b => b.Date < DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(31))) != false)
{// must have bp updated in recent 31 days.
return Array.Empty<RecommendationEntry>();
}
// only get bps in recent half year.
var filteredBest = bests.Select((b, i) => (b, i)).Where(x => x.b.Date >= DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(186))).ToList();
return (IList<RecommendationEntry>)
(from x1 in filteredBest
from x2 in filteredBest
where x1.b.Date > x2.b.Date
select new RecommendationEntry
{
Mode = u.Mode,
Left = RecommendationBeatmapId.Create(x1.b, u.Mode),
Recommendation = RecommendationBeatmapId.Create(x2.b, u.Mode),
RecommendationDegree = Math.Pow(0.95, x1.i + x2.i - 2),
}).ToList();
}
catch (Exception e)
{
var v = Interlocked.Increment(ref errorCount);
if (v <= 1)
{
await _api.SendMessageAsync(_context.Endpoint, e.ToString()).ConfigureAwait(false);
}
}
finally
{
Interlocked.Decrement(ref queueCount);
}
return Array.Empty<RecommendationEntry>();
});
var r = await Task.WhenAll(taskList).ConfigureAwait(false);
var expanded = r.SelectMany(e => e)
.OrderBy(e => ((long)e.Left.GetHashCode() << 32) | (e.Recommendation.GetHashCode() & 0xffffffff))
.ToList();
await _api.SendMessageAsync(_context.Endpoint, $"展开完成,共{expanded.Count}项。").ConfigureAwait(false);
var recent = expanded.FirstOrDefault();
var degree = 0.0;
var recommendationList = new List<RecommendationEntry>();
foreach (var current in expanded)
{
if ((current.Left, current.Recommendation) == (recent!.Left, recent.Recommendation))
{
degree += current.RecommendationDegree;
}
else
{
recommendationList.Add(new RecommendationEntry
{
Mode = mode,
Left = recent.Left,
Recommendation = recent.Recommendation,
RecommendationDegree = degree,
});
degree = 0;
recent = current;
}
}
var recommendations = recommendationList.ToArray();
//await _newbieContext.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
//{
// await using var transaction = await _newbieContext.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable).ConfigureAwait(false);
//var oldData = await _newbieContext.Recommendations.ToListAsync().ConfigureAwait(false);
//_newbieContext.Recommendations.RemoveRange(oldData);
//await _newbieContext.SaveChangesAsync().ConfigureAwait(false);
for (int i = 0; i * 10000 < recommendations.Length; i++)
{
// 不这么干不行,因为 EF Core 追踪实体需要消耗大量内存。
// 现在这样可以把同时追踪的实体数限制在一万,消耗大约 600M 内存。
var toAdd = (i + 1) * 10000 > recommendations.Length
? recommendations[(i * 10000)..]
: recommendations[(i * 10000)..((i + 1) * 10000)];
_newbieContext.Recommendations.AddRange(toAdd);
await _newbieContext.SaveChangesAsync().ConfigureAwait(false);
var changedEntriesCopy = _newbieContext.ChangeTracker.Entries()
.Where(e => e.State == EnreplacedyState.Added ||
e.State == EnreplacedyState.Modified ||
e.State == EnreplacedyState.Deleted)
.ToList();
foreach (var entry in changedEntriesCopy)
entry.State = EnreplacedyState.Detached;
}
//_newbieContext.Recommendations.AddRange(recommendationList);
//await _newbieContext.SaveChangesAsync().ConfigureAwait(false);
// await transaction.CommitAsync().ConfigureAwait(false);
//}).ConfigureAwait(false);
}
19
Source : QueryTrigger.cs
with GNU Affero General Public License v3.0
from b11p
with GNU Affero General Public License v3.0
from b11p
public async Task ProcessAsync(MessageContext context, HttpApiClient api)
{
Mode? mode = default(Mode);
try
{
if (!string.IsNullOrWhiteSpace(ModeString))
{
mode = ModeExtensions.Parse(ModeString);
}
}
catch
{
// Ignore when the mode string is invalid.
return;
}
Message message;
if (QQId != default)
{
var bindingInfo = await NewbieContext.Bindings.Where(b => b.UserId == QQId).FirstOrDefaultAsync().ConfigureAwait(false);
if (bindingInfo is null)
{
await api.SendMessageAsync(context.Endpoint, "未绑定 osu! 账号。").ConfigureAwait(false);
return;
}
var osuId = bindingInfo.OsuId;
message = await QueryHelper.QueryByUserId(osuId, mode).ConfigureAwait(false);
}
else if (!string.IsNullOrEmpty(Name))
{
message = await QueryHelper.QueryByUserName(Name, mode).ConfigureAwait(false);
}
else
{
return;
}
object sendResponse = null;
if (!_memoryCache.TryGetValue(SendingFailureCacheKey, out int t) || t < Threshold)
sendResponse = await api.SendMessageAsync(context.Endpoint, message).ConfigureAwait(false);
if (sendResponse is null)
{
// 可能会假失败,即消息发出去了,但检测到失败。
//await api.SendMessageAsync(context.Endpoint, $"检测到发送失败,消息长度为{message.Raw.Length},[调试]将转换成 base64 发送。").ConfigureAwait(false);
//await api.SendMessageAsync(context.Endpoint, Convert.ToBase64String(Encoding.UTF8.GetBytes(message.Raw))).ConfigureAwait(false);
// 记录发送失败次数。72小时内失败2次即转图。
// 不是完全线程安全。
t = _memoryCache.Set(SendingFailureCacheKey, t + 1, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(3),
Priority = CacheItemPriority.NeverRemove,
SlidingExpiration = TimeSpan.FromDays(1),
});
var text = message.Sections[0].Data["text"];
using var sr = new System.IO.StringReader(text);
var lines = new List<string>();
while (sr.ReadLine() is string line)
{
// 分行发送发送失败的消息
//await api.SendMessageAsync(context.Endpoint, line).ConfigureAwait(false);
lines.Add(line);
}
//lines.Add(string.Empty);
//lines.Add("// 有会 html/css 的帮我弄好看点吗? 斜杠可怜");
using var page = await Chrome.OpenNewPageAsync().ConfigureAwait(false);
await page.SetViewportAsync(new ViewPortOptions
{
DeviceScaleFactor = 3,
Width = 360,
Height = 202,
}).ConfigureAwait(false);
var style = "font-family: 'Source Han Sans CN', sans-serif;";
await page.SetContentAsync($@"<div lang=""zh-CN"" style=""{style}"">{string.Join("<br>", lines.Select(HttpUtility.HtmlEncode))}</div>").ConfigureAwait(false);
var data = await page.ScreenshotDataAsync(new ScreenshotOptions
{
FullPage = true,
}).ConfigureAwait(false);
await api.SendMessageAsync(context.Endpoint, Message.ByteArrayImage(data)).ConfigureAwait(false);
}
}
19
Source : ConfigurationExtensions.cs
with MIT License
from bamotav
with MIT License
from bamotav
private static void AddDashboardRouteToEmbeddedResource(string route, string contentType, string resourceName)
=> DashboardRoutes.Routes.Add(route, new ContentDispatcher(contentType, resourceName, TimeSpan.FromDays(1)));
19
Source : Startup.cs
with MIT License
from baotoq
with MIT License
from baotoq
public void ConfigureServices(IServiceCollection services)
{
var rootConfiguration = CreateRootConfiguration();
services.AddSingleton(rootConfiguration);
// Register DbContexts for IdenreplacedyServer and Idenreplacedy
services.RegisterDbContexts<AdminIdenreplacedyDbContext, IdenreplacedyServerConfigurationDbContext, IdenreplacedyServerPersistedGrantDbContext, IdenreplacedyServerDataProtectionDbContext>(Configuration);
// Save data protection keys to db, using a common application name shared between Admin and STS
services.AddDataProtection<IdenreplacedyServerDataProtectionDbContext>(Configuration);
// Add email senders which is currently setup for SendGrid and SMTP
services.AddEmailSenders(Configuration);
// Add services for authentication, including Idenreplacedy model and external providers
services.AddAuthenticationServices<AdminIdenreplacedyDbContext, UserIdenreplacedy, UserIdenreplacedyRole>(Configuration);
services.AddIdenreplacedyServer<IdenreplacedyServerConfigurationDbContext, IdenreplacedyServerPersistedGrantDbContext, UserIdenreplacedy>(Configuration);
// Add HSTS options
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(365);
});
// Add all dependencies for Asp.Net Core Idenreplacedy in MVC - these dependencies are injected into generic Controllers
// Including settings for MVC and Localization
// If you want to change primary keys or use another db model for Asp.Net Core Idenreplacedy:
services.AddMvcWithLocalization<UserIdenreplacedy, string>(Configuration);
// Add authorization policies for MVC
services.AddAuthorizationPolicies(rootConfiguration);
services.AddIdSMonitoring<IdenreplacedyServerConfigurationDbContext, IdenreplacedyServerPersistedGrantDbContext, AdminIdenreplacedyDbContext, IdenreplacedyServerDataProtectionDbContext>(Configuration);
}
19
Source : CocktailsManager.cs
with MIT License
from BaristaStudio
with MIT License
from BaristaStudio
void AddToBarrel(List<replacedtail> replacedtails)
{
if (Barrel.Current.Exists(FavoritesListKey))
Barrel.Current.Empty(FavoritesListKey);
Barrel.Current.Add(FavoritesListKey, replacedtails, TimeSpan.FromDays(3));
}
19
Source : Startup.cs
with GNU General Public License v3.0
from berkansasmaz
with GNU General Public License v3.0
from berkansasmaz
public void ConfigureServices(IServiceCollection services) {
services.AddDbContextPool < MLDBContext > (
options => options.UseSqlServer("Server=localhost,1433;Initial Catalog=MLHackathonServer; User= sa; Preplacedword=Berkan8946.")
);
services
.AddDefaultIdenreplacedy <MLUser> ()
.AddRoles<MLUserRole>()
.AddEnreplacedyFrameworkStores < MLDBContext > ()
.AddDefaultTokenProviders();
// Add framework services.
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//https://docs.microsoft.com/en-us/ASPNET/Core/security/authentication/idenreplacedy?view=aspnetcore-2.2&tabs=visual-studio
services.Configure < IdenreplacedyOptions > (options => {
// Preplacedword settings.
options.Preplacedword.RequireDigit = true;
options.Preplacedword.RequireLowercase = true;
options.Preplacedword.RequireNonAlphanumeric = true;
options.Preplacedword.RequireUppercase = true;
options.Preplacedword.RequiredLength = 6;
options.Preplacedword.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
services.ConfigureApplicationCookie(options => {
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(15);
options.Cookie.Name = "mlhackathonserver-auth";
options.LoginPath = "/Idenreplacedy/Account/Login";
options.AccessDeniedPath = "/Idenreplacedy/Account/AccessDenied";
options.SlidingExpiration = true;
});
}
19
Source : Startup.cs
with MIT License
from BerkEmreCabuk
with MIT License
from BerkEmreCabuk
public void ConfigureServices(IServiceCollection services)
{
#region Authentication
var appSettingsSection = Configuration.GetSection("Idenreplacedy");
services.Configure<IdenreplacedySettingModel>(appSettingsSection);
var idenreplacedyModel = appSettingsSection.Get<IdenreplacedySettingModel>();
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(idenreplacedyModel.SecretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = idenreplacedyModel.Iss,
ValidateAudience = true,
ValidAudience = idenreplacedyModel.Aud,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromDays(1),
RequireExpirationTime = true,
};
services.AddAuthentication(cfg =>
{
cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.TokenValidationParameters = tokenValidationParameters;
});
#endregion
services.AddDbContext<DotNetConfDbContext>(options => options.UseInMemoryDatabase(databaseName: "DotNetConfDb"));
services.AddMediatR(typeof(CreateUserCommand).GetTypeInfo().replacedembly);
#region Services Register
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IService, Service>();
#endregion
#region AutoMapper
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfile());
});
var mapper = config.CreateMapper();
services.AddSingleton(mapper);
#endregion
#region ApiVersioning & Swagger
services.AddApiVersioning(
options =>
{
options.ReportApiVersions = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
//header version örneği
//options.ApiVersionReader = new HeaderApiVersionReader("api-version");
});
services.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubsreplaceduteApiVersionInUrl = true;
});
services.AddSwaggerGen(
options =>
{
options.OperationFilter<SwaggerDefaultValues>();
options.EnableAnnotations();
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
In = ParameterLocation.Header,
Scheme = "Bearer",
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
services.AddSingleton<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
#endregion
#region CORS Enable
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetPreflightMaxAge(System.TimeSpan.FromMinutes(60))
.Build();
});
});
#endregion
#region Fluent Validation
services.AddControllers()
.AddNewtonsoftJson(setupAction => new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
})
.AddFluentValidation(validationConfig => validationConfig.RegisterValidatorsFromreplacedembly(replacedembly.Getreplacedembly(typeof(CreateUserValidator))));
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = c =>
{
var messages = new List<string>();
foreach (var errors in c.ModelState.Values.Where(x => x.Errors.Count > 0).Select(x => x.Errors))
{
messages.AddRange(errors.Select(x => x.ErrorMessage).ToList());
}
throw new UnprocessableException("Request Model Invalid or Missing", messages);
};
});
#endregion
}
19
Source : Program.cs
with GNU General Public License v3.0
from Bililive
with GNU General Public License v3.0
from Bililive
internal static int RunWpfReal()
{
var cancel = new CancellationTokenSource();
var token = cancel.Token;
try
{
SleepBlocker.Start();
var app = new App();
app.InitializeComponent();
app.DispatcherUnhandledException += App_DispatcherUnhandledException;
updateTask = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
await update.UpdateAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromDays(1), token).ConfigureAwait(false);
}
});
return app.Run();
}
finally
{
cancel.Cancel();
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
update.WaitForUpdatesOnShutdownAsync().GetAwaiter().GetResult();
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits
}
}
19
Source : HttpClientDownloadWithProgress.cs
with MIT License
from bitbeans
with MIT License
from bitbeans
public async Task StartDownload()
{
_httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1), DefaultRequestVersion = new Version(2, 0) };
using var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead);
await DownloadFileFromHttpResponseMessage(response);
}
19
Source : NonAuthTests.cs
with MIT License
from blackboxlogic
with MIT License
from blackboxlogic
[TestMethod]
public async Task TestNotes()
{
var notes = await client.GetNotes(NoteBounds);
replacedert.IsTrue(notes?.Length > 0);
replacedert.IsTrue(notes[0].Id.HasValue);
var noteId = notes[0].Id.Value;
var note = await client.GetNote(noteId);
replacedert.IsTrue(note?.Id == noteId);
var feed = await client.GetNotesRssFeed(NoteBounds);
replacedert.IsNotNull(feed);
var node = await GetFirstNodeInWashington();
await client.QueryNotes("ThisIsANote", null, null, null, null, null, null);
await client.QueryNotes("ThisIsANote", node.UserId, null, null, null, null, null);
await client.QueryNotes("ThisIsANote", null, node.UserName, null, null, null, null);
await client.QueryNotes("ThisIsANote", null, null, 100, null, null, null);
await client.QueryNotes("ThisIsANote", null, null, null, 1, null, null);
await client.QueryNotes("ThisIsANote", null, null, null, null, DateTime.Now.Subtract(TimeSpan.FromDays(100)), null);
await client.QueryNotes("ThisIsANote", null, null, null, null, null, DateTime.Now.Subtract(TimeSpan.FromDays(2)));
var newNote = await client.CreateNote(10.1f, 10.2f, "HelloWorld");
replacedert.IsTrue(newNote?.Comments?.Comments?.FirstOrDefault()?.Text == "HelloWorld");
replacedert.IsTrue(newNote?.Comments?.Comments?.FirstOrDefault()?.Action == Note.Comment.CommentAction.Opened);
replacedert.IsTrue(newNote?.Comments?.Comments?.FirstOrDefault()?.UserId == null);
replacedert.AreEqual(Note.NoteStatus.Open, newNote?.Status);
}
19
Source : CalendarDay.razor.cs
with MIT License
from BlazorFluentUI
with MIT License
from BlazorFluentUI
private void GenerateWeeks()
{
DateTime date = new(NavigatedDate.Year, NavigatedDate.Month, 1);
DateTime todaysDate = DateTime.Now;
Weeks = new List<List<DayInfo>>();
// cycle backwards to get first day of week
while (date.DayOfWeek != FirstDayOfWeek)
date -= TimeSpan.FromDays(1);
// a flag to indicate whether all days of the week are in the month
bool isAllDaysOfWeekOutOfMonth = false;
// in work week view we want to select the whole week
//DateRangeType selecteDateRangeType = DateRangeType == DateRangeType.WorkWeek ? DateRangeType.Week : DateRangeType;
DateRangeType selecteDateRangeType = DateRangeType;
List<DateTime>? selectedDates = SelectedDate == null ? new List<DateTime>() : DateUtilities.GetDateRangeArray((DateTime)SelectedDate, selecteDateRangeType, FirstDayOfWeek, WorkWeekDays);
if (DateRangeType != DateRangeType.Day)
{
selectedDates = GetBoundedDateRange(selectedDates, MinDate, MaxDate);
}
bool shouldGetWeeks = true;
for (int weekIndex = 0; shouldGetWeeks; weekIndex++)
{
List<DayInfo> week = new();
isAllDaysOfWeekOutOfMonth = true;
for (int dayIndex = 0; dayIndex < 7; dayIndex++)
{
DateTime originalDate = new(date.Year, date.Month, date.Day);
DayInfo? dayInfo = new()
{
Key = date.ToString(),
Date = date.Date.ToString("D"),
OriginalDate = originalDate,
WeekIndex = weekIndex,
IsInMonth = date.Month == NavigatedDate.Month,
IsToday = DateTime.Compare(DateTime.Now.Date, originalDate) == 0,
IsSelected = IsInDateRangeArray(date, selectedDates),
IsHighlightedOnHover = IsInWorkweekRange(date),
OnSelected = () => OnSelectDateInternal(originalDate, false),
IsInBounds =
(DateTime.Compare(MinDate, date) < 1) &&
(DateTime.Compare(date, MaxDate) < 1) &&
!GetIsRestrictedDate(date)
};
week.Add(dayInfo);
if (dayInfo.IsInMonth)
isAllDaysOfWeekOutOfMonth = false;
date = date.AddDays(1);
}
// We append the condition of the loop depending upon the ShowSixWeeksByDefault parameter.
shouldGetWeeks = ShowSixWeeksByDefault ? !isAllDaysOfWeekOutOfMonth || weekIndex <= 5 : !isAllDaysOfWeekOutOfMonth;
if (shouldGetWeeks)
Weeks.Add(week);
}
}
19
Source : Startup.cs
with Apache License 2.0
from bluedoctor
with Apache License 2.0
from bluedoctor
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
19
Source : Startup.cs
with MIT License
from bluetianx
with MIT License
from bluetianx
private DefaultTusConfiguration CreateTusConfiguration(IServiceProvider serviceProvider)
{
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Startup>();
// Change the value of EnableOnAuthorize in appsettings.json to enable or disable
// the new authorization event.
//var enableAuthorize = _configuration.GetValue<bool>("EnableOnAuthorize");
if (!Directory.Exists("tusfiles"))
{
Directory.CreateDirectory("tusfiles");
}
return new DefaultTusConfiguration
{
UrlPath = "/files",
Store = new TusDiskStore(@"tusfiles"),
// Set an expiration time where incomplete files can no longer be updated.
// This value can either be absolute or sliding.
// Absolute expiration will be saved per file on create
// Sliding expiration will be saved per file on create and updated on each patch/update.
Expiration = new AbsoluteExpiration(TimeSpan.FromDays(1))
};
}
19
Source : MovieBulkImportModule.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
private Response Search()
{
if (Request.Query.Id == 0)
{
//Todo error handling
}
RootFolder rootFolder = _rootFolderService.Get(Request.Query.Id);
int page = Request.Query.page;
int per_page = Request.Query.per_page;
int min = (page - 1) * per_page;
int max = page * per_page;
var unmapped = rootFolder.UnmappedFolders.OrderBy(f => f.Name).ToList();
int total_count = unmapped.Count;
if (Request.Query.total_entries.HasValue)
{
total_count = Request.Query.total_entries;
}
max = total_count >= max ? max : total_count;
var paged = unmapped.GetRange(min, max-min);
var mapped = paged.Select(f =>
{
Core.Tv.Movie m = null;
var mappedMovie = _mappedMovies.Find(f.Name);
if (mappedMovie != null)
{
return mappedMovie;
}
var parsedreplacedle = Parser.ParseMoviePath(f.Name, false);
if (parsedreplacedle == null)
{
m = new Core.Tv.Movie
{
replacedle = f.Name.Replace(".", " ").Replace("-", " "),
Path = f.Path,
};
}
else
{
m = new Core.Tv.Movie
{
replacedle = parsedreplacedle.Moviereplacedle,
Year = parsedreplacedle.Year,
ImdbId = parsedreplacedle.ImdbId,
Path = f.Path
};
}
var files = _diskScanService.GetVideoFiles(f.Path);
var decisions = _importDecisionMaker.GetImportDecisions(files.ToList(), m, true);
var decision = decisions.Where(d => d.Approved && !d.Rejections.Any()).FirstOrDefault();
if (decision != null)
{
var local = decision.LocalMovie;
m.MovieFile = new LazyLoaded<MovieFile>(new MovieFile
{
Path = local.Path,
Edition = local.ParsedMovieInfo.Edition,
Quality = local.Quality,
MediaInfo = local.MediaInfo,
ReleaseGroup = local.ParsedMovieInfo.ReleaseGroup,
RelativePath = f.Path.GetRelativePath(local.Path)
});
}
mappedMovie = _searchProxy.MapMovieToTmdbMovie(m);
if (mappedMovie != null)
{
mappedMovie.Monitored = true;
_mappedMovies.Set(f.Name, mappedMovie, TimeSpan.FromDays(2));
return mappedMovie;
}
return null;
});
return new PagingResource<MovieResource>
{
Page = page,
PageSize = per_page,
SortDirection = SortDirection.Ascending,
SortKey = Request.Query.sort_by,
TotalRecords = total_count - mapped.Where(m => m == null).Count(),
Records = MapToResource(mapped.Where(m => m != null)).ToList()
}.AsResponse();
}
19
Source : NzbgetProxy.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public string GetVersion(NzbgetSettings settings)
{
var response = ProcessRequest<string>(settings, "version");
_versionCache.Set(settings.Host + ":" + settings.Port, response, TimeSpan.FromDays(1));
return response;
}
19
Source : NewznabCapabilitiesProvider.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public NewznabCapabilities GetCapabilities(NewznabSettings indexerSettings)
{
var key = indexerSettings.ToJson();
//_capabilitiesCache.Clear(); I am an idiot, i think
var capabilities = _capabilitiesCache.Get(key, () => FetchCapabilities(indexerSettings), TimeSpan.FromDays(7));
return capabilities;
}
19
Source : TorrentRssParserFactory.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public TorrentRssParser GetParser(TorrentRssIndexerSettings indexerSettings)
{
var key = indexerSettings.ToJson();
var parserSettings = _settingsCache.Get(key, () => DetectParserSettings(indexerSettings), TimeSpan.FromDays(7));
if (parserSettings.UseEZTVFormat)
{
return new EzrssTorrentRssParser();
}
else
{
return new TorrentRssParser
{
UseGuidInfoUrl = false,
ParseSeedersInDescription = parserSettings.ParseSeedersInDescription,
UseEnclosureUrl = parserSettings.UseEnclosureUrl,
UseEnclosureLength = parserSettings.UseEnclosureLength,
ParseSizeInDescription = parserSettings.ParseSizeInDescription,
SizeElementName = parserSettings.SizeElementName
};
}
}
19
Source : Startup.cs
with Apache License 2.0
from bosima
with Apache License 2.0
from bosima
private void AddLimitForDifferentUser(IServiceCollection app)
{
app.AddRateLimit(new InProcessFixedWindowAlgorithm(
new[] {
new FixedWindowRule()
{
Id = "1",
ExtractTarget = context =>
{
// replaceduming that the user ID is preplaceded from the header, it needs to be obtained according to the actual situation
return (context as HttpContext).Request.GetTypedHeaders().Get<string>("userId");
},
CheckRuleMatching = context =>
{
// replaceduming that the user type is preplaceded from the header, it may actually need to be queried according to the user Id
// 0 free users 1 charged users
int userType = (context as HttpContext).Request.GetTypedHeaders().Get<int>("userType");
if(userType==0){
return true;
}
return false;
},
Name="Free user rate limit rules",
LimitNumber=100,
StatWindow=TimeSpan.FromDays(1),
StartTimeType=StartTimeType.FromNaturalPeriodBeign
},
new FixedWindowRule()
{
Id = "2",
ExtractTarget = context =>
{
return (context as HttpContext).Request.GetTypedHeaders().Get<string>("userId");
},
CheckRuleMatching = context =>
{
int userType = (context as HttpContext).Request.GetTypedHeaders().Get<int>("userType");
if(userType==1){
return true;
}
return false;
},
Name="Charged user rate limit rules",
LimitNumber=1000000,
StatWindow=TimeSpan.FromDays(1),
StartTimeType=StartTimeType.FromNaturalPeriodBeign
}
}),
new HttpErrorResponse()
{
BuildHttpContent = (context, ruleCheckResult) =>
{
return "The number of queries exceeds the maximum limit of the day.";
}
},
new HttpInvokeInterceptor()
{
OnTriggered = (context, ruleCheckResult) =>
{
Console.WriteLine("Rate Limit Alarm!!!");
}
}
);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Days(this double days)
{
return TimeSpan.FromDays(days);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Days(this int days, TimeSpan offset)
{
return TimeSpan.FromDays(days).Add(offset);
}
19
Source : ServiceWrapper.cs
with GNU General Public License v2.0
from bp2008
with GNU General Public License v2.0
from bp2008
private static void scheduler()
{
try
{
while (true)
{
try
{
// Calculate the next SunEvent
SunEvent nextEvent = null;
DahuaSunriseSunsetConfig cfg = new DahuaSunriseSunsetConfig();
cfg.Load();
DateTime rise, set;
bool timeZoneAndLongitudeAreCompatible;
SunHelper.Calc(cfg.lareplacedude, cfg.longitude, out rise, out set, out timeZoneAndLongitudeAreCompatible, cfg.sunriseOffsetHours, cfg.sunsetOffsetHours);
if (!timeZoneAndLongitudeAreCompatible)
{
Logger.Debug("Pausing scheduler for 1 day due to incompatible time zone and longitude. Please fix the problem and restart the service.");
Thread.Sleep(TimeSpan.FromDays(1));
continue;
}
if (rise < set)
nextEvent = new SunEvent(rise, true);
else if (set < rise)
nextEvent = new SunEvent(set, false);
else
nextEvent = new SunEvent(rise, false); // Rise and set are at the same time ... lets just call it a sunset.
// Now we know when the next event is and what type it is, so we know what profile the cameras should be now.
if (nextEvent.rise)
{
// Next event is a sunrise, which means it is currently Night.
TriggerSunsetActions(nextEvent.time);
}
else
{
// Next event is a sunset, which means it is currently Day.
TriggerSunriseActions(nextEvent.time);
}
while (DateTime.Now <= nextEvent.time)
Thread.Sleep(1000);
}
catch (ThreadAbortException) { throw; }
catch (Exception ex)
{
Logger.Debug(ex);
Thread.Sleep(1000);
}
}
}
catch (ThreadAbortException) { }
catch (Exception ex) { Logger.Debug(ex); }
}
See More Examples