Here are the examples of the csharp api System.DateTime.AddHours(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1095 Examples
19
View Source File : CSRedisClientKeyTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void ExpireAt() {
replacedert.True(rds.MSet("TestExpireAt_null1", base.Null, "TestExpireAt_string1", base.String, "TestExpireAt_bytes1", base.Bytes, "TestExpireAt_clreplaced1", base.Clreplaced));
replacedert.True(rds.ExpireAt("TestExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
replacedert.InRange(rds.Ttl("TestExpireAt_null1"), 9, 20);
replacedert.True(rds.ExpireAt("TestExpireAt_string1", DateTime.UtcNow.AddHours(1)));
replacedert.InRange(rds.Ttl("TestExpireAt_string1"), 60 * 60 - 10, 60 * 60 + 10);
}
19
View Source File : CSRedisClientKeyTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void PExpireAt() {
replacedert.True(rds.MSet("TestPExpireAt_null1", base.Null, "TestPExpireAt_string1", base.String, "TestPExpireAt_bytes1", base.Bytes, "TestPExpireAt_clreplaced1", base.Clreplaced));
replacedert.True(rds.ExpireAt("TestPExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
replacedert.InRange(rds.PTtl("TestPExpireAt_null1"), 9000, 20000);
replacedert.True(rds.ExpireAt("TestPExpireAt_string1", DateTime.UtcNow.AddHours(1)));
replacedert.InRange(rds.PTtl("TestPExpireAt_string1"), 1000 * 60 * 60 - 10000, 1000 * 60 * 60 + 10000);
}
19
View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void ExpireAt()
{
cli.MSet("TestExpireAt_null1", base.Null, "TestExpireAt_string1", base.String, "TestExpireAt_bytes1", base.Bytes, "TestExpireAt_clreplaced1", base.Clreplaced);
replacedert.True(cli.ExpireAt("TestExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
replacedert.InRange(cli.Ttl("TestExpireAt_null1"), 9, 20);
replacedert.True(cli.ExpireAt("TestExpireAt_string1", DateTime.UtcNow.AddHours(1)));
replacedert.InRange(cli.Ttl("TestExpireAt_string1"), 60 * 60 - 10, 60 * 60 + 10);
}
19
View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void PExpireAt()
{
cli.MSet("TestPExpireAt_null1", base.Null, "TestPExpireAt_string1", base.String, "TestPExpireAt_bytes1", base.Bytes, "TestPExpireAt_clreplaced1", base.Clreplaced);
replacedert.True(cli.ExpireAt("TestPExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
replacedert.InRange(cli.PTtl("TestPExpireAt_null1"), 9000, 20000);
replacedert.True(cli.ExpireAt("TestPExpireAt_string1", DateTime.UtcNow.AddHours(1)));
replacedert.InRange(cli.PTtl("TestPExpireAt_string1"), 1000 * 60 * 60 - 10000, 1000 * 60 * 60 + 10000);
}
19
View Source File : NpcEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task Handle(ChatWithNpcEvent message, CancellationToken cancellationToken)
{
var playerId = message.PlayerId;
var npcId = message.NpcId;
await _redisDb.StringSet<int>(string.Format(RedisKey.ChatWithNpc, playerId, npcId), 1, DateTime.Now.AddDays(30));
await _redisDb.StringSet<int>(string.Format(RedisKey.ChatWithNpcLike, playerId, npcId), 1, DateTime.Now.AddHours(1));
}
19
View Source File : TokenManager.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string CreateSession(Sys_Users userInfo, SourceType source, int hours)
{
var userSession = Guid.NewGuid().ToString().ToUpper();
//判断用户是否只允许等于一次
if (userInfo.OneSession)
{
RemoveAllSession(userInfo.UserID);
}
var expireTime = DateTime.Now.AddHours(hours);
var timeSpan = new TimeSpan(hours, 0, 0);
//将 Session 添加用户 Session 列表
RedisServer.Session.HSet(userInfo.UserID, userSession, expireTime);
RedisServer.Session.Expire(userInfo.UserID, timeSpan);
//设置 Session 信息
var userSessionVM = new UserSessionVM()
{
UserID = userInfo.UserID,
UserName = userInfo.UserName,
NickName = userInfo.NickName,
Email = userInfo.Email,
Sex = userInfo.Sex,
AvatarUrl = userInfo.AvatarUrl,
QQ = userInfo.QQ,
Phone = userInfo.Phone,
ProvinceID = userInfo.ProvinceID,
Province = userInfo.Province,
CityID = userInfo.CityID,
City = userInfo.City,
CountyID = userInfo.CountyID,
County = userInfo.County,
Address = userInfo.Address,
Remark = userInfo.Remark,
IdenreplacedyCard = userInfo.IdenreplacedyCard,
Birthday = userInfo.Birthday,
CreateTime = userInfo.CreateTime,
Enabled = userInfo.Enabled,
OneSession = userInfo.OneSession,
Source = source.ToString(),
KeepHours = hours,
Administrator = userInfo.Administrator,
UserPower = _usersService.GetUserPowers(userInfo.UserID),
UserRelation = _usersService.GetUserRelation(userInfo.UserID),
};
RedisServer.Session.HSet(userSession, "UserInfo", userSessionVM);
RedisServer.Session.Expire(userSession, timeSpan);
//添加在线记录表
_onlineService.Add(new Sys_Online()
{
SessionID = userSession,
UserID = userInfo.UserID,
Source = source.ToString(),
IPAddress = _accessor.HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString(),
LoginTime = DateTime.Now,
UpdateTime = DateTime.Now
});
_usersService.Update(m => m.UserID == userInfo.UserID, m => new Sys_Users { LastLoginTime = DateTime.Now });
return userSession;
}
19
View Source File : Job1TimedService.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
private void RemoveExpiredSession(string source, int hours)
{
using (var scope = _serviceProvider.CreateScope())
{
var _onlineService = scope.ServiceProvider.GetService<ISysOnlineService>();
DateTime expireTime = DateTime.Now.AddHours(-hours);
var usersExpired = _onlineService.GetWhere(m => m.UpdateTime < expireTime && m.Source == source);
foreach (var session in usersExpired)
{
//删除 Session
RedisServer.Session.Del(session.SessionID);
//删除用户 Session 列表中的 Session
RedisServer.Session.HDel(session.UserID, session.SessionID);
_onlineService.Delete(session.SessionID);
}
}
}
19
View Source File : PlayerCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(InitGameCommand command, CancellationToken cancellationToken)
{
_logger.LogDebug($"Handle InitGameCommand:{JsonConvert.SerializeObject(command)}");
var playerId = command.PlayerId;
if (playerId <= 0)
{
await _bus.RaiseEvent(new DomainNotification($"请重新进入!"));
return Unit.Value;
}
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
return Unit.Value;
}
var room = await _roomDomainService.Get(player.RoomId);
if (room == null)
{
await _bus.RaiseEvent(new DomainNotification("房间不存在!"));
return Unit.Value;
}
player.LastDate = DateTime.Now;
await _cache.GetOrCreateAsync(CacheKey.IsActivityIn24Hours, async x => {
x.AbsoluteExpiration = DateTime.UtcNow.AddHours(24);
Random random = new Random();
player.Kar = random.Next(1, 100);
return await Task.FromResult(true);
});
player.Computed();
await _playerDomainService.Update(player);
if (await Commit())
{
await _bus.RaiseEvent(new InitGameEvent(player)).ConfigureAwait(false);
await _bus.RaiseEvent(new PlayerInRoomEvent(player, room)).ConfigureAwait(false);
}
return Unit.Value;
}
19
View Source File : TokenManager.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public void UpdateSession(string userSession)
{
DateTime lastUpdateTime = _memoryCache.Get<DateTime>(userSession);
if (Convert.ToDateTime(lastUpdateTime).AddMinutes(2) < DateTime.Now)
{
// 记录本次更新时间
_memoryCache.Set(userSession, DateTime.Now);
if (!string.IsNullOrEmpty(userSession))
{
//更新在线用户记录最后操作时间
_onlineService.Update(m => m.SessionID == userSession, m => new Sys_Online() { UpdateTime = DateTime.Now });
//根据 Session 取出 UserInfo
var userInfo = GetSessionItem<UserSessionVM>(userSession, "UserInfo");
var expireTime = DateTime.Now.AddHours(userInfo.KeepHours);
var timeSpan = new TimeSpan(userInfo.KeepHours, 0, 0);
//更新 Session 列表中的 Session 过期时间
RedisServer.Session.HSet(userInfo.UserID, userSession, expireTime);
//更新 Session 列表过期时间
RedisServer.Session.Expire(userInfo.UserID, timeSpan);
//更新 Session 过期时间
RedisServer.Session.Expire(userSession, timeSpan);
}
}
}
19
View Source File : SetPlayerInfo.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private ModelStatus setPlayerInfo(ModelPlayerInfo packet, ServiceContext context)
{
lock (context.Player)
{
var data = Repository.GetData;
if (context.Player.Public.EnablePVP != packet.EnablePVP)
{
if (context.Player.TimeChangeEnablePVP >= DateTime.UtcNow)
{
return new ModelStatus()
{
Status = 1,
Message = "You can’t change the status of PVP yet",
};
}
context.Player.TimeChangeEnablePVP = DateTime.UtcNow.AddHours(24);
context.Player.Public.EnablePVP = packet.EnablePVP;
}
context.Player.Public.AboutMyText = packet.AboutMyTextBox;
context.Player.Public.EMail = packet.EMail;
context.Player.Public.DiscordUserName = packet.DiscordUserName;
context.Player.SettingDelaySaveGame = packet.DelaySaveGame;
}
return new ModelStatus();
}
19
View Source File : PlayerServer.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public bool GetKeyReconnect()
{
if ((DateTime.UtcNow - KeyReconnectTime).TotalMinutes < 30
&& !string.IsNullOrEmpty(KeyReconnect1))
return false;
KeyReconnectTime = DateTime.UtcNow;
var rnd = new Random((int)(DateTime.UtcNow.Ticks & int.MaxValue));
var key = "o6*#fn`~ыggTgj0&9 gT54Qa[g}t,23rfr4*vcx%%4/\"d!2" + rnd.Next(int.MaxValue).ToString()
+ DateTime.UtcNow.Date.AddHours(DateTime.UtcNow.Hour).ToBinary().ToString()
+ Public.Login;
var hash = new CryptoProvider().GetHash(key);
KeyReconnect2 = KeyReconnect1;
KeyReconnect1 = hash;
return true;
}
19
View Source File : UserStatsGetterTests.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
[TestMethod]
public async Task UsersCountOverToday_ThereIsDescreteData_ShouldReturn24Element()
{
var userRepo = new Mock<IRepository<string, AppUser>>();
var getter = new UserStatsGetter(userRepo.Object);
var users = new List<AppUser>
{
new AppUser
{
CreatedAt= DateTime.UtcNow.AddHours(-2),
},
new AppUser
{
CreatedAt= DateTime.UtcNow.AddHours(-2),
},
new AppUser
{
CreatedAt= DateTime.UtcNow.AddHours(-1),
},
};
userRepo.Setup(u => u.Table).Returns(users.AsQueryable());
var result = await getter.GetUsersCountOverToday();
replacedert.IsTrue(result.Count == 24);
}
19
View Source File : UserStatsGetter.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<List<int>> GetUsersCountOverToday()
{
// This will resolve to MM/DD/YYYY 00:00:00
var startDate = DateTime.UtcNow.Date;
// This will resolve to MM/DD+1/YYYY 00:00:00
var endDate = DateTime.UtcNow.Date.AddDays(1);
var usersHourly = (from u in _usersRepo.Table
where u.CreatedAt >= startDate && u.CreatedAt <= endDate
group u by new
{
u.CreatedAt.Date,
u.CreatedAt.Hour
} into g
select new
{
Count = g.Count(),
Date = g.Key.Date,
Hour = g.Key.Hour
}).ToList();
var usersHourlyFormated = usersHourly.Select(u => new
{
Count = u.Count,
DateTime = new DateTime(u.Date.Year, u.Date.Month, u.Date.Day, u.Hour, 0, 0)
}).ToList();
var hours = Enumerable.Range(0, 24).Select(offset =>
{
var dateTime = startDate.AddHours(offset);
return dateTime;
}).ToList();
hours.ForEach(hour =>
{
if (!usersHourlyFormated.Any(u => u.DateTime == hour))
{
usersHourlyFormated.Add(new
{
Count = 0,
DateTime = hour
});
}
});
usersHourlyFormated = usersHourlyFormated.OrderBy(u => u.DateTime).ToList();
var stats = usersHourlyFormated.Select(u => u.Count).ToList();
return stats;
}
19
View Source File : CreateRegistrationCommandHandler.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<CommandResult<CreateRegistrationResultDto>> Handle(CreateRegistrationCommand request, CancellationToken cancellationToken)
{
ErrorMessage ObjectNotAvailable = new ErrorMessage
{
ErrorCode = "TRANSACTION.OBJECT.RESERVE.NOT.AVAILABLE",
Message = "This object is not available",
StatusCode = System.Net.HttpStatusCode.BadRequest
};
var user = await _userDataManager.AddCurrentUserIfNeeded();
if (user.Login == null)
{
return new ErrorMessage()
{
ErrorCode = "TRANSACTION.OBJECT.RESERVE.NOT.AUTHORIZED",
Message = "You are not authorized to do this operation",
StatusCode = System.Net.HttpStatusCode.Unauthorized
}.ToCommand<CreateRegistrationResultDto>();
}
var @object = await _objectsRepo.GetObjectAsync(request.ObjectId);
if (@object is null)
{
return new ErrorMessage()
{
ErrorCode = "TRANSACTION.OBJECT.RESERVE.NOT.EXISTS",
Message = "The object specified does not exists",
StatusCode = System.Net.HttpStatusCode.BadRequest
}.ToCommand<CreateRegistrationResultDto>();
}
// Should Not Return and is not taken right now
if ([email protected])
{
var receivings = from receiving in _objectReceiving.Table
where receiving.ObjectRegistration.ObjectId == @object.OfferedObjectId
select receiving;
// If The object has receiving and all of them has returnings
if (receivings.Any(r => r.ObjectReturning == null))
{
return ObjectNotAvailable.ToCommand<CreateRegistrationResultDto>();
}
}
// See Previous registrations
var existingRegistrations = from registration in _registrationsRepo.Table
where registration.RecipientLogin.UserId == user.User.UserId && registration.ObjectId == @object.OfferedObjectId
select registration;
// If The user taken and has this object OR If the user has another registeration pending receiving
if (existingRegistrations.Any(reg => reg.ObjectReceiving == null || reg.ObjectReceiving.ObjectReturning == null))
{
return ObjectNotAvailable.ToCommand<CreateRegistrationResultDto>();
}
TimeSpan? shouldReturnItAfter;
if (@object.ShouldReturn)
{
// If the object should return but the user has not specified the time he should return the object
if (!request.ShouldReturnAfter.HasValue)
{
return new ErrorMessage
{
ErrorCode = "TRANSACTION.OBJECT.RESERVE.SHOULDRETURN.NULL",
Message = "Please specify when you will return this object",
StatusCode = System.Net.HttpStatusCode.BadRequest
}.ToCommand<CreateRegistrationResultDto>();
}
if (@object.HourlyCharge.HasValue)
{
shouldReturnItAfter = new TimeSpan(request.ShouldReturnAfter.Value, 0, 0);
}
else
{
if (request.ShouldReturnAfter > maximumHoursForFreeLending)
shouldReturnItAfter = new TimeSpan(maximumHoursForFreeLending, 0, 0);
else
shouldReturnItAfter = new TimeSpan(request.ShouldReturnAfter.Value, 0, 0);
}
}
else
{
shouldReturnItAfter = null;
}
var registrationModel = new ObjectRegistration
{
ObjectRegistrationId = Guid.NewGuid(),
RegisteredAtUtc = DateTime.UtcNow,
ExpiresAtUtc = DateTime.UtcNow.AddHours(maximumHoursForReservationExpiration),
ObjectId = @object.OfferedObjectId,
Status = ObjectRegistrationStatus.OK,
RecipientLoginId = user.Login.LoginId,
ShouldReturnItAfter = shouldReturnItAfter,
};
_registrationsRepo.Add(registrationModel);
await _registrationsRepo.SaveChangesAsync();
var integrationEvent = new NewRegistrationIntegrationEvent()
{
Id = Guid.NewGuid(),
OccuredAt = registrationModel.RegisteredAtUtc,
ObjectId = @object.OriginalObjectId,
RecipiantId = user.User.UserId.ToString(),
ShouldReturn = @object.ShouldReturn,
RegisteredAt = registrationModel.RegisteredAtUtc,
RegistrationId = registrationModel.ObjectRegistrationId
};
// Broadcast an event;
_eventBus.Publish(integrationEvent);
var token = await _transactionTokenManager.GenerateToken(registrationModel.ObjectRegistrationId, TokenType.Receiving);
var dto = new CreateRegistrationResultDto
{
ObjectId = registrationModel.Object.OriginalObjectId,
RegistrationId = registrationModel.ObjectRegistrationId,
ShouldBeReturnedAfterReceving = registrationModel.ShouldReturnItAfter,
RegistrationExpiresAtUtc = registrationModel.ExpiresAtUtc,
RegistrationToken = new RegistrationTokenResultDto
{
RegistrationToken = token.Token,
CreatedAtUtc = token.IssuedAtUtc,
UseBeforeUtc = token.UseBeforeUtc
}
};
return new CommandResult<CreateRegistrationResultDto>(dto);
}
19
View Source File : AllRegistrationQueryHandler.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
private static ReturnStatus GetReturnStatus(ObjectRegistration registration)
{
if (registration.Status == ObjectRegistrationStatus.Canceled)
{
return ReturnStatus.NotTakenYet;
}
if (registration.ObjectReceiving is null)
{
return ReturnStatus.NotTakenYet;
}
if (registration.ObjectReceiving.ObjectReturning is object)
{
return ReturnStatus.Returned;
}
// it is free object
if (!registration.ShouldReturnItAfter.HasValue)
{
return ReturnStatus.NotDueYet;
}
if (registration.ObjectReceiving.ReceivedAtUtc.Add(registration.ShouldReturnItAfter.Value) <= DateTime.UtcNow)
{
return ReturnStatus.NotDueYet;
}
if (registration.ObjectReceiving.ReceivedAtUtc.Add(registration.ShouldReturnItAfter.Value) > DateTime.UtcNow.AddHours(24))
{
return ReturnStatus.PossibleTheft;
}
if (registration.ObjectReceiving.ReceivedAtUtc.Add(registration.ShouldReturnItAfter.Value) > DateTime.UtcNow)
{
return ReturnStatus.Delayed;
}
return ReturnStatus.Returned;
}
19
View Source File : TransactionStatsQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<TransactionTodayStatsDto> Handle(TransactionStatsOverTodayQuery request, CancellationToken cancellationToken)
{
// This will resolve to MM/DD/YYYY 00:00:00
var startDate = DateTime.UtcNow.Date;
// This will resolve to MM/DD+1/YYYY 00:00:00
var endDate = DateTime.UtcNow.Date.AddDays(1);
var transesHourly = (from r in _receivingsRepo.Table
where r.ReceivedAtUtc >= startDate && r.ReceivedAtUtc <= endDate
group r by new
{
r.ReceivedAtUtc.Date,
r.ReceivedAtUtc.Hour,
} into g
select new
{
Count = g.Count(),
Date = g.Key.Date,
Hour = g.Key.Hour
});
var transesHourlyFormated = transesHourly.Select(r => new
{
r.Count,
DateTime = new DateTime(r.Date.Year, r.Date.Month, r.Date.Day, r.Hour, 0, 0)
}).ToList();
var hours = Enumerable.Range(0, 24).Select(offset =>
{
var dateTime = startDate.AddHours(offset);
return dateTime;
}).ToList();
hours.ForEach(hour =>
{
if (!transesHourlyFormated.Any(t => t.DateTime == hour))
{
transesHourlyFormated.Add(new
{
Count = 0,
DateTime = hour
});
}
});
transesHourlyFormated = transesHourlyFormated.OrderBy(t => t.DateTime).ToList();
var stats = transesHourlyFormated.Select(t => t.Count).ToList();
var transactions = from r in _registrationsRepo.Table
where r.ShouldReturnItAfter.HasValue && r.Status == ObjectRegistrationStatus.OK
select r;
var late = transactions
.AsEnumerable()
.Count(r => r.ObjectReceiving != null &&
r.ObjectReceiving.ObjectReturning != null &&
(r.ObjectReceiving.ReceivedAtUtc + r.ShouldReturnItAfter.Value) > r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));
var notReturned = transactions.Count(r => r.ObjectReceiving != null && r.ObjectReceiving.ObjectReturning == null);
var onTime = transactions
.AsEnumerable()
.Count(r => r.ObjectReceiving != null &&
r.ObjectReceiving.ObjectReturning != null &&
r.ObjectReceiving.ReceivedAtUtc.Add(r.ShouldReturnItAfter.Value) <= r.ObjectReceiving.ObjectReturning.ReturnedAtUtc.AddMinutes(30));
return new TransactionTodayStatsDto
{
LateReturn = late,
NotReturnedYet = notReturned,
OnTimeReturn = onTime,
TransactionsOverToday = stats
};
}
19
View Source File : HeatMapWithTextInCellsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public override string FormatLabel(IComparable dataValue)
{
var h = (int) Math.Ceiling(dataValue.ToDouble());
var dt = new DateTime(2000, 1, 1, 1, 0, 0);
try
{
dt = dt.AddHours(h);
}
catch (ArgumentOutOfRangeException)
{
dt = h < 0 ? DateTime.MinValue : DateTime.MaxValue;
}
return dt.ToString("hh:mm tt", new CultureInfo("en-US"));
}
19
View Source File : UniformHeatmapAndPaletteProvider.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private IDataSeries CreateSeries()
{
double angle = Math.Round(Math.PI * 2 * 1 / 30, 3);
int w = 300, h = 200;
var data = new double[h, w];
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
var v = (1 + Math.Round(Math.Sin(x * 0.04 + angle), 3)) * 50 + (1 + Math.Round(Math.Sin(y * 0.1 + angle), 3)) * 50 * (1 + Math.Round(Math.Sin(angle * 2), 3));
var cx = 150; var cy = 100;
var r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
var exp = Math.Max(0, 1 - r * 0.008);
data[y, x] = (v * exp + _random.NextDouble() * 50);
}
var xStart = new DateTime(2017, 1, 13, 0, 0, 0);
var xStep = DateTime.MinValue.AddDays(1).AddHours(6).AddMinutes(30);
return new UniformHeatmapDataSeries<DateTime, int, double>(data, xStart, xStep, 0, 2) { SeriesName = "UniformHeatmap" };
}
19
View Source File : MixedCharts.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void MixedCharts_OnLoaded(object sender, RoutedEventArgs e)
{
var leftDataSeries0 = new UniformXyDataSeries<double>();
var leftDataSeries1 = new UniformXyDataSeries<double>();
var rightDataSeries0 = new XyDataSeries<DateTime, double>();
var rightDataSeries1 = new XyDataSeries<DateTime, double>();
var random = new Random();
for (int i = 0; i < 20; i++)
{
leftDataSeries0.Append(random.Next(10));
leftDataSeries1.Append(random.Next(10));
rightDataSeries0.Append(DateTime.Now.AddHours(i), random.Next(10));
rightDataSeries1.Append(DateTime.Now.AddHours(i), random.Next(10));
}
sciChart.RenderableSeries[0].DataSeries = leftDataSeries0;
sciChart.RenderableSeries[1].DataSeries = leftDataSeries1;
sciChart.RenderableSeries[2].DataSeries = rightDataSeries0;
sciChart.RenderableSeries[3].DataSeries = rightDataSeries1;
sciChart.ZoomExtents();
}
19
View Source File : SentinelCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("ban", AccessLevel.Sentinel, CommandHandlerFlag.None, 4,
"Bans the specified player account.",
"[accountname] [days] [hours] [minutes] (reason)\n"
+ "This command bans the specified player account for the specified time. This player will not be able to enter the game with any character until the time expires.\n"
+ "Example: @ban AccountName 0 0 5\n"
+ "Example: @ban AccountName 1 0 0 banned 1 day because reasons\n")]
public static void HandleBanAccount(Session session, params string[] parameters)
{
// usage: @ban < acct > < days > < hours > < minutes >
// This command bans the specified player account for the specified time.This player will not be able to enter the game with any character until the time expires.
// @ban - Bans the specified player account.
var accountName = parameters[0];
var banDays = parameters[1];
var banHours = parameters[2];
var banMinutes = parameters[3];
var banReason = string.Empty;
if (parameters.Length > 4)
{
var parametersAfterBanParams = "";
for (var i = 4; i < parameters.Length; i++)
{
parametersAfterBanParams += parameters[i] + " ";
}
parametersAfterBanParams = parametersAfterBanParams.Trim();
banReason = parametersAfterBanParams;
}
var account = DatabaseManager.Authentication.GetAccountByName(accountName);
if (account == null)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Cannot ban \"{accountName}\" because that account cannot be found in database. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
return;
}
if (!double.TryParse(banDays, out var days) || days < 0)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Days must not be less than 0.", ChatMessageType.Broadcast);
return;
}
if (!double.TryParse(banHours, out var hours) || hours < 0)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Hours must not be less than 0.", ChatMessageType.Broadcast);
return;
}
if (!double.TryParse(banMinutes, out var minutes) || minutes < 0)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Minutes must not be less than 0.", ChatMessageType.Broadcast);
return;
}
var bannedOn = DateTime.UtcNow;
var banExpires = DateTime.UtcNow.AddDays(days).AddHours(hours).AddMinutes(minutes);
var bannedBy = 0u;
if (session != null)
{
bannedBy = session.AccountId;
}
account.BannedTime = bannedOn;
account.BanExpireTime = banExpires;
account.BannedByAccountId = bannedBy;
if (!string.IsNullOrWhiteSpace(banReason))
account.BanReason = banReason;
DatabaseManager.Authentication.UpdateAccount(account);
// Boot the player
if (NetworkManager.Find(accountName) != null)
{
var bootArgs = new List<string> { "account" };
if (!string.IsNullOrWhiteSpace(banReason))
{
bootArgs.Add($"{accountName},");
bootArgs.Add(banReason);
}
else
bootArgs.Add(accountName);
HandleBoot(session, bootArgs.ToArray());
}
var banText = $"Banned account {accountName} for {days} days, {hours} hours and {minutes} minutes.{(!string.IsNullOrWhiteSpace(banReason) ? $" Reason: {banReason}" : "")}";
CommandHandlerHelper.WriteOutputInfo(session, banText, ChatMessageType.Broadcast);
PlayerManager.BroadcastToAuditChannel(session?.Player, banText);
}
19
View Source File : AopCacheAttribute.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private DateTime GetCacheNewTime(CacheTimeType type, int length)
{
if (length <= 0) return DateTime.MaxValue;
var limitTime = DateTime.Now;
switch (type)
{
case CacheTimeType.Day:
limitTime = limitTime.AddDays(length);
break;
case CacheTimeType.Hour:
limitTime = limitTime.AddHours(length);
break;
case CacheTimeType.Minute:
limitTime = limitTime.AddMinutes(length);
break;
case CacheTimeType.Second:
limitTime = limitTime.AddSeconds(length);
break;
}
return limitTime;
}
19
View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private DateTime Increase(int selstart, int value)
{
DateTime retval = (ParseDateText(false) ?? SelectedDate);
try
{
switch (DateFormat.Substring(selstart, 1))
{
case "h":
case "H":
retval = retval.AddHours(value);
break;
case "y":
retval = retval.AddYears(value);
break;
case "M":
retval = retval.AddMonths(value);
break;
case "m":
retval = retval.AddMinutes(value);
break;
case "d":
retval = retval.AddDays(value);
break;
case "s":
retval = retval.AddSeconds(value);
break;
}
}
catch (ArgumentException ex)
{
//Catch dates with year over 9999 etc, dont throw
}
return retval;
}
19
View Source File : IdeaForumDataAdapterFactory.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IIdeaForumDataAdapter CreateIdeaForumDataAdapter(Enreplacedy ideaForum, string filter, string timeSpan, int? status = 1)
{
IIdeaForumDataAdapter ideaForumDataAdapter = null;
if (string.Equals(filter, "new", StringComparison.InvariantCultureIgnoreCase))
{
ideaForumDataAdapter = new IdeaForumByNewDataAdapter(ideaForum);
}
else
{
ideaForumDataAdapter = this.IsIdeasPreRollup()
? this.CreateIdeaDataAdapterPreRollup(ideaForum, filter)
: this.CreateIdeaDataAdapter(ideaForum, filter);
}
ideaForumDataAdapter.MinDate = timeSpan == "this-year" ? DateTime.UtcNow.AddYears(-1).Date
: timeSpan == "this-month" ? DateTime.UtcNow.AddMonths(-1).Date
: timeSpan == "this-week" ? DateTime.UtcNow.AddDays(-7).Date
: timeSpan == "today" ? DateTime.UtcNow.AddHours(-24)
: (DateTime?)null;
ideaForumDataAdapter.Status = status != (int?)IdeaStatus.Any ? status : null;
return ideaForumDataAdapter;
}
19
View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static DateTime? DateAddHours(DateTime? date, double value)
{
return date.HasValue
? date.Value.AddHours(value)
: (DateTime?)null;
}
19
View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static DateTime Round(this DateTime d, RoundTo to)
{
var floor = Floor(d, to);
if (to == RoundTo.Second && d.Millisecond >= 500) return floor.AddSeconds(1);
if (to == RoundTo.Minute && d.Second >= 30) return floor.AddMinutes(1);
if (to == RoundTo.Hour && d.Minute >= 30) return floor.AddHours(1);
if (to == RoundTo.Day && d.Hour >= 12) return floor.AddDays(1);
if (to == RoundTo.Month && d.Day >= DateTime.DaysInMonth(d.Year, d.Month) / 2) return floor.AddMonths(1);
return d;
}
19
View Source File : ChatAuthController.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetTokenString(IList<Claim> claims)
{
string tokenString = null;
using (var cryptoServiceProvider = GetCryptoProvider(true))
{
string issuer = PortalSettings.Instance.DomainName;
string audience = string.Empty;
DateTime notBefore = DateTime.Now;
DateTime expires = notBefore.AddHours(1);
var tokenHandler = new JwtSecurityTokenHandler();
var signingCredentials = new SigningCredentials(new RsaSecurityKey(cryptoServiceProvider),
SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
// need to explicitly add "iat" claim
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var iat = Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(notBefore) - unixEpoch).TotalSeconds - 1);
claims.Add(new Claim("iat", iat.ToString(), ClaimValueTypes.Integer));
var header = new JwtHeader(signingCredentials);
var payload = new JwtPayload(issuer, audience, claims, notBefore, expires);
// Need to adjust this because Claim clreplaced ignores value type
payload["iat"] = Convert.ToInt64(payload["iat"]);
var jwtToken = new JwtSecurityToken(header, payload);
tokenString = tokenHandler.WriteToken(jwtToken);
}
return tokenString;
}
19
View Source File : TaskSchedulerHandler.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
public static void UpdateAllTasks(DateTime lightThemeTime, DateTime darkThemeTime)
{
string path = replacedembly.GetExecutingreplacedembly().Location;
DateTime lightTime = DateTime.Today.AddHours(lightThemeTime.Hour).AddMinutes(lightThemeTime.Minute);
DateTime darkTime = DateTime.Today.AddHours(darkThemeTime.Hour).AddMinutes(darkThemeTime.Minute);
try
{
TaskFolder folder = CreateRootFolder();
CreateDailyTask("Light theme", folder, lightTime, path, "/change");
CreateDailyTask("Dark theme", folder, darkTime, path, "/change");
CreateStartupTask("Change theme", folder, path, "/change");
CreateDailyTask("Auto update", folder, lightTime, path, "/update", 3);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
throw ex;
}
}
19
View Source File : App.xaml.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
[STAThread]
public static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
if (args.Length > 0)
{
Logger.Info("Starting app with command line arguments: {0}", string.Join(", ", args));
AutoFileSaver<SettingsModel> autoFileSaver = new AutoFileSaver<SettingsModel>("settings.xml", true);
AppearanceHandler handler = new AppearanceHandler(autoFileSaver.Model);
foreach (string arg in args)
{
switch (arg)
{
case "/light":
handler.SwitchToLightTheme();
break;
case "/dark":
handler.SwitchToDarkTheme();
break;
case "/change":
DateTime now = DateTime.Now;
DateTime t1 = DateTime.Today.AddHours(autoFileSaver.Model.LightThemeTime.Hour).AddMinutes(autoFileSaver.Model.LightThemeTime.Minute);
DateTime t2 = DateTime.Today.AddHours(autoFileSaver.Model.DarkThemeTime.Hour).AddMinutes(autoFileSaver.Model.DarkThemeTime.Minute);
if (now > t1 && now < t2)
{
handler.SwitchToLightTheme();
}
else
{
handler.SwitchToDarkTheme();
}
break;
case "/update":
AutoUpdater autoUpdater = new AutoUpdater(true, true);
autoUpdater.CheckForUpdates(true).Wait();
break;
case "/clean":
TaskSchedulerHandler.DeleteAllTasks();
break;
default:
Logger.Error("Command line argument is not accepted: {0}", arg);
break;
}
}
}
else
{
App app = new App();
app.InitializeComponent();
app.Run();
}
}
19
View Source File : TokenCleanerHost.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task RemoveExpiredTokensAsync(CancellationToken cancellationToken)
{
try
{
using var scope = _provider.CreateScope();
var service = scope.ServiceProvider;
var pageRequest = new PageRequest
{
// Community OData transform date from UTC so we substract the UTC diff
Filter = $"{nameof(IGrant.Expiration)} lt {DateTime.UtcNow.AddHours(DateTime.UtcNow.Hour - DateTime.Now.Hour):o}",
OrderBy = nameof(IAuditable.CreatedAt)
};
var oneTimeTokenStore = service.GetRequiredService<IAdminStore<OneTimeToken>>();
var oneTimeTokenResponse = await oneTimeTokenStore.GetAsync(pageRequest, cancellationToken).ConfigureAwait(false);
await RemoveExpiredTokensAsync(oneTimeTokenStore, oneTimeTokenResponse.Items, cancellationToken).ConfigureAwait(false);
var refreshTokenStore = service.GetRequiredService<IAdminStore<RefreshToken>>();
var refreshTokenResponse = await refreshTokenStore.GetAsync(pageRequest, cancellationToken).ConfigureAwait(false);
await RemoveExpiredTokensAsync(refreshTokenStore, refreshTokenResponse.Items, cancellationToken).ConfigureAwait(false);
var referenceTokenStore = service.GetRequiredService<IAdminStore<ReferenceToken>>();
var referenceTokenResponse = await referenceTokenStore.GetAsync(pageRequest, cancellationToken).ConfigureAwait(false);
await RemoveExpiredTokensAsync(referenceTokenStore, referenceTokenResponse.Items, cancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
_logger.LogDebug("TaskCanceledException. Exiting.");
}
catch (Exception e)
{
_logger.LogError(e, $"Exception removing expired grants: {e.Message}");
}
}
19
View Source File : SystemEventsCenter.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject obj = e.NewEvent;
string clsName = obj.ClreplacedPath.ClreplacedName;
switch (clsName)
{
case "Win32_ProcessStartTrace":
case "Win32_ProcessStopTrace":
{
ProcessEventArgs arg = new ProcessEventArgs()
{
SessionId = Convert.ToInt32(obj["SessionID"]),
ProcessId = Convert.ToInt32(obj["ProcessID"]),
ProcessName = obj["ProcessName"] as string,
TimeCreated = DateTime.FromFileTimeUtc(Convert.ToInt64(obj["TIME_CREATED"])).AddHours(UtcOffsetHours),
};
if (clsName == "Win32_ProcessStartTrace" && this.ProcessStart != null)
this.ProcessStart(this, arg);
if (clsName == "Win32_ProcessStopTrace" && this.ProcessExit != null)
this.ProcessExit(this, arg);
}
break;
default:
break;
}
}
19
View Source File : KickassParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
private DateTime ParseDate(string date)
{
var digitEndIndex = 0;
foreach(var c in date)
{
if (char.IsLetter(c))
break;
digitEndIndex++;
}
int.TryParse(date.Substring(0, digitEndIndex), out var numberToSubtract);
var parsedDate = DateTime.UtcNow;
if (date.Contains("min.")) parsedDate = parsedDate.AddMinutes(-numberToSubtract);
if (date.Contains("hour")) parsedDate = parsedDate.AddHours(-numberToSubtract);
if (date.Contains("day")) parsedDate = parsedDate.AddDays(-numberToSubtract);
if (date.Contains("month")) parsedDate = parsedDate.AddMonths(-numberToSubtract);
if (date.Contains("year")) parsedDate = parsedDate.AddYears(-numberToSubtract);
return parsedDate;
}
19
View Source File : AuditGetRecentUpdates.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
{
TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
DateTime oldestUpdate = DateTime.MinValue;
if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
{
OptionSetValue value = this.Units.Get<OptionSetValue>(context);
if (value != null)
{
switch (value.Value)
{
case 222540000:
oldestUpdate = DateTime.Now.AddYears(this.Number.Get<int>(context) * -1);
break;
case 222540001:
oldestUpdate = DateTime.Now.AddMonths(this.Number.Get<int>(context) * -1);
break;
case 222540002:
oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -7);
break;
case 222540003:
oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -1);
break;
case 222540004:
oldestUpdate = DateTime.Now.AddHours(this.Number.Get<int>(context) * -1);
break;
default:
oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get<int>(context) * -1);
break;
}
}
}
int maxUpdates = this.MaxAuditLogs.Get(context) > 100 || this.MaxAuditLogs.Get(context) < 1 ? 100 : this.MaxAuditLogs.Get(context);
RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
{
Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
PagingInfo = new PagingInfo() { Count = maxUpdates, PageNumber = 1 }
};
RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
var detailsToInclude = response.AuditDetailCollection.AuditDetails
.Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
.OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
.ToList();
if (detailsToInclude.Any())
{
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
{
EnreplacedyFilters = EnreplacedyFilters.Attributes,
LogicalName = workflowContext.PrimaryEnreplacedyName
};
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;
foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
{
DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
if (dateToModify.Kind != DateTimeKind.Utc)
{
dateToModify = dateToModify.ToUniversalTime();
}
LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;
var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
.Distinct()
.Select(a =>
new {
AttributeName = a,
DisplayName = GetDisplayLabel(metadata, a)
})
.OrderBy(a => a.DisplayName);
foreach (var item in details)
{
DataRow newRow = table.NewRow();
newRow["User"] = GetDisplayValue(detail.AuditRecord, "userid");
newRow["Date"] = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
newRow["Attribute"] = item.DisplayName;
newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
table.Rows.Add(newRow);
}
}
}
return table;
}
19
View Source File : DateAddOrSubtract.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected override void Execute(CodeActivityContext context)
{
bool dateSet = false;
if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
{
OptionSetValue value = this.Units.Get<OptionSetValue>(context);
if (value != null)
{
switch (value.Value)
{
case 222540000:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddYears(this.Number.Get<int>(context)));
break;
case 222540001:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddMonths(this.Number.Get<int>(context)));
break;
case 222540002:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context) * 7));
break;
case 222540003:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddDays(this.Number.Get<int>(context)));
break;
case 222540004:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddHours(this.Number.Get<int>(context)));
break;
default:
ModifiedDate.Set(context, this.DateToModify.Get(context).AddMinutes(this.Number.Get<int>(context)));
break;
}
dateSet = true;
}
}
if (!dateSet)
{
ModifiedDate.Set(context, this.DateToModify.Get(context));
}
}
19
View Source File : CourtSystem.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static DateTime DetermineCourtHearingDate()
{
if (RealisticCourtDates)
{
DateTime CourtDate = DateTime.Now;
int Minutes = (int)Math.Round(((float)CourtDate.Minute) / 5.0f) * 5;
while (CourtDate.Minute != Minutes)
{
CourtDate = CourtDate.AddMinutes(1);
Minutes = (int)Math.Round(((float)CourtDate.Minute) / 5.0f) * 5;
}
while (CourtDate.Hour > 17 || CourtDate.Hour < 9)
{
CourtDate = CourtDate.AddHours(LSPDFRPlusHandler.rnd.Next(1, 8));
}
CourtDate = CourtDate.AddDays(LSPDFRPlusHandler.rnd.Next(1, 4));
return CourtDate;
}
else
{
return DateTime.Now.AddMinutes(LSPDFRPlusHandler.rnd.Next(2, 10));
}
}
19
View Source File : FormatExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static bool ValidateTimeRegex(string value)
{
var r = TimeRegex.Match(value);
if (r.Success)
{
if (int.TryParse(r.Groups["h"].Value, out var h) && int.TryParse(r.Groups["m"].Value, out var m) && int.TryParse(r.Groups["s"].Value, out var s))
{
// parse milliseconds
var ms = r.Groups["ms"] is Group msg && msg.Success && int.TryParse(msg.Value, out var ms_) ? (int?)ms_ : null;
// extract offset information
var oo = r.Groups["oo"] is Group oog && oog.Success ? oog.Value : null;
var zh = r.Groups["zh"] is Group zhg && zhg.Success && int.TryParse(zhg.Value, out var zh_) ? (int?)zh_ : null;
var zm = r.Groups["zm"] is Group zmg && zmg.Success && int.TryParse(zmg.Value, out var zm_) ? (int?)zm_ : null;
// time values must be in range (leap seconds!)
if (h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 60)
return false;
// millisecond value must be at least 0
if (ms != null && ms < 0)
return false;
// offset indicator exists but isn't proper value
if (oo != null && oo != "-" && oo != "+")
return false;
// check that offset hour is valid
if (zh != null)
if (zh < 0 || zh > 23)
return false;
// check that offset minute is valid
if (zm != null)
if (zm < 0 || zm > 59)
return false;
// leap second, but wrong minute
if (s == 60)
{
var t = new DateTime(2000, 1, 1, h, m, 59);
// offset indicator exists but isn't proper value
if (oo != null)
{
if (zh is int zhi)
t = oo == "+" ? t.AddHours(-zhi) : t.AddHours(zhi);
if (zm is int zmi)
t = oo == "+" ? t.AddMinutes(-zmi) : t.AddMinutes(zmi);
}
// leap second, but wrong minute
if (t.Minute != 59)
return false;
// leap second, but wrong hour
if (t.Hour != 23)
return false;
}
// all the checks succeeded
return true;
}
}
return false;
}
19
View Source File : WorkerController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
[HttpGet]
public IEnumerable<WorkerDto> GetAll()
{
// Prune worker entries that have not responded in 1h
_context.RemoveRange(_context.Workers.Where(w => w.ActiveExperimentInstance == null && w.LastRequestTime < DateTime.UtcNow.AddHours(-1)));
// or did not finish after 48h
var oldWorker = _context.Workers.Where(w => w.ActiveExperimentInstance != null && w.LastRequestTime < DateTime.UtcNow.AddHours(-48)).
Include(w => w.ActiveExperimentInstance);
_context.RemoveRange(oldWorker);
foreach(var worker in oldWorker)
{
worker.ActiveExperimentInstance.Reset();
}
_context.RemoveRange();
_context.SaveChanges();
return _context.Workers
.Include(w => w.ActiveExperimentInstance)
.Select(w => new WorkerDto
{
Token = w.Token,
Capabilities = w.Capabilities,
ActiveExperimentInstanceId = w.ActiveExperimentInstance.Id,
ActiveExperimentId = w.ActiveExperimentInstance.ExperimentId,
ConnectionInfo = w.ConnectionInfo,
LastRequestTime = w.LastRequestTime,
RegistrationTime = w.RegistrationTime
});
}
19
View Source File : ConfiguracoesSeguranca.cs
License : MIT License
Project Creator : alexandrebeato
License : MIT License
Project Creator : alexandrebeato
public static string GerarToken(UsuarioViewModel usuarioViewModel)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_chave);
var allClaims = new List<Claim>();
switch (usuarioViewModel.TipoUsuario)
{
case (TipoUsuario.Agencia):
{
allClaims.Add(new Claim("agencia", "1"));
break;
}
case (TipoUsuario.Cliente):
{
allClaims.Add(new Claim("cliente", "1"));
break;
}
}
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(
new GenericIdenreplacedy(usuarioViewModel.Id.ToString(), "Login"),
allClaims
),
NotBefore = DateTime.UtcNow.AddMinutes(-15),
Expires = DateTime.UtcNow.AddHours(8),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
19
View Source File : InteractiveBrokersServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<Candle> GetCandleHistory(string nameSec, TimeFrame tf)
{
SecurityIb contractIb =
_secIB.Find(
contract =>
contract.Symbol + "_" + contract.SecType + "_" + contract.Exchange == nameSec);
if (contractIb == null)
{
return null; ;
}
DateTime timeEnd = DateTime.Now.ToUniversalTime();
DateTime timeStart = timeEnd.AddMinutes(60);
string barSize = "1 min";
int mergeCount = 0;
if (tf == TimeFrame.Sec1)
{
barSize = "1 sec";
timeStart = timeEnd.AddMinutes(10);
}
else if (tf == TimeFrame.Sec5)
{
barSize = "5 secs";
}
else if (tf == TimeFrame.Sec15)
{
barSize = "15 secs";
}
else if (tf == TimeFrame.Sec30)
{
barSize = "30 secs";
}
else if (tf == TimeFrame.Min1)
{
timeStart = timeEnd.AddHours(5);
barSize = "1 min";
}
else if (tf == TimeFrame.Min5)
{
timeStart = timeEnd.AddHours(25);
barSize = "5 mins";
}
else if (tf == TimeFrame.Min15)
{
timeStart = timeEnd.AddHours(75);
barSize = "15 mins";
}
else if (tf == TimeFrame.Min30)
{
timeStart = timeEnd.AddHours(150);
barSize = "30 mins";
}
else if (tf == TimeFrame.Hour1)
{
timeStart = timeEnd.AddHours(1300);
barSize = "1 hour";
}
else if (tf == TimeFrame.Hour2)
{
timeStart = timeEnd.AddHours(2100);
barSize = "1 hour";
mergeCount = 2;
}
else if (tf == TimeFrame.Hour4)
{
timeStart = timeEnd.AddHours(4200);
barSize = "1 hour";
mergeCount = 4;
}
else if (tf == TimeFrame.Day)
{
barSize = "1 day";
timeStart = timeEnd.AddDays(701);
}
else
{
return null;
}
CandlesRequestResult = null;
_client.GetCandles(contractIb, timeEnd, timeStart, barSize, "TRADES");
DateTime startSleep = DateTime.Now;
while (true)
{
Thread.Sleep(1000);
if (startSleep.AddSeconds(30) < DateTime.Now)
{
break;
}
if (CandlesRequestResult != null)
{
break;
}
}
if (CandlesRequestResult != null &&
CandlesRequestResult.CandlesArray.Count != 0)
{
if (mergeCount != 0)
{
List<Candle> newCandles = Merge(CandlesRequestResult.CandlesArray, mergeCount);
CandlesRequestResult.CandlesArray = newCandles;
return StraichCandles(CandlesRequestResult);
}
return StraichCandles(CandlesRequestResult);
}
_client.GetCandles(contractIb, timeEnd, timeStart, barSize, "MIDPOINT");
startSleep = DateTime.Now;
while (true)
{
Thread.Sleep(1000);
if (startSleep.AddSeconds(30) < DateTime.Now)
{
break;
}
if (CandlesRequestResult != null)
{
break;
}
}
if (CandlesRequestResult != null &&
CandlesRequestResult.CandlesArray.Count != 0)
{
if (mergeCount != 0)
{
List<Candle> newCandles = Merge(CandlesRequestResult.CandlesArray, mergeCount);
CandlesRequestResult.CandlesArray = newCandles;
return StraichCandles(CandlesRequestResult);
}
return StraichCandles(CandlesRequestResult);
}
return null;
}
19
View Source File : AppBase.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private async Task<StandardBusinessDoreplacedent> ConstructStandardBusinessDoreplacedent(string instanceGuid, Instance instance)
{
DateTime completedTime = DateTime.Now;
Sender digdirSender = new Sender
{
Identifier = new Identifier
{
// 0192 prefix for all Norwegian organisations.
Value = $"0192:{_appSettings.EFormidlingSender}",
Authority = "iso6523-actorid-upis"
}
};
List<Receiver> receivers = await GetEFormidlingReceivers(instance);
Scope scope =
new Scope
{
Identifier = _appMetadata.EFormidling.Process,
InstanceIdentifier = Guid.NewGuid().ToString(),
Type = "ConversationId",
ScopeInformation = new List<ScopeInformation>
{
new ScopeInformation
{
ExpectedResponseDateTime = completedTime.AddHours(2)
}
},
};
BusinessScope businessScope = new BusinessScope
{
Scope = new List<Scope> { scope }
};
DoreplacedentIdentification doreplacedentIdentification = new DoreplacedentIdentification
{
InstanceIdentifier = instanceGuid,
Standard = _appMetadata.EFormidling.Standard,
TypeVersion = _appMetadata.EFormidling.TypeVersion,
CreationDateAndTime = completedTime,
Type = _appMetadata.EFormidling.Type
};
StandardBusinessDoreplacedentHeader sbdHeader = new StandardBusinessDoreplacedentHeader
{
HeaderVersion = "1.0",
BusinessScope = businessScope,
DoreplacedentIdentification = doreplacedentIdentification,
Receiver = receivers,
Sender = new List<Sender> { digdirSender }
};
StandardBusinessDoreplacedent sbd = new StandardBusinessDoreplacedent
{
StandardBusinessDoreplacedentHeader = sbdHeader,
Arkivmelding = new Arkivmelding { Sikkerhetsnivaa = _appMetadata.EFormidling.SecurityLevel },
};
return sbd;
}
19
View Source File : EFormidlingClientIntTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[Fact]
public async void Send_Standard_Business_Doreplacedent()
{
var service = _serviceProvider.GetService<IEFormidlingClient>();
var jsonString = File.ReadAllText(@"TestData\sbd.json");
StandardBusinessDoreplacedent sbd = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(jsonString);
string process = "urn:no:difi:profile:arkivmelding:administrasjon:ver1.0";
string type = "arkivmelding";
DateTime currentCreationTime = DateTime.Now;
DateTime currentCreationTime2HoursLater = currentCreationTime.AddHours(2);
Guid obj = Guid.NewGuid();
_guid = obj.ToString();
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().Identifier = process;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().ScopeInformation.First().ExpectedResponseDateTime = currentCreationTime2HoursLater;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.Type = type;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.CreationDateAndTime = currentCreationTime;
StandardBusinessDoreplacedent sbdVerified = await service.CreateMessage(sbd);
replacedert.Equal(JsonSerializer.Serialize(sbdVerified), JsonSerializer.Serialize(sbd));
}
19
View Source File : EFormidlingClientIntTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[Fact]
public async void Send_Attachment_Arkivmelding()
{
var service = _serviceProvider.GetService<IEFormidlingClient>();
var jsonString = File.ReadAllText(@"TestData\sbd.json");
StandardBusinessDoreplacedent sbd = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(jsonString);
string process = "urn:no:difi:profile:arkivmelding:administrasjon:ver1.0";
string type = "arkivmelding";
DateTime currentCreationTime = DateTime.Now;
currentCreationTime = currentCreationTime.AddMinutes(-1);
DateTime currentCreationTime2HoursLater = currentCreationTime.AddHours(2);
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().Identifier = process;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().ScopeInformation.First().ExpectedResponseDateTime = currentCreationTime2HoursLater;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.Type = type;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.CreationDateAndTime = currentCreationTime;
_ = await service.CreateMessage(sbd);
string filename = "arkivmelding.xml";
bool sendArkivmelding = false;
using (FileStream fs = File.OpenRead(@"TestData\arkivmelding.xml"))
{
if (fs.Length > 3)
{
sendArkivmelding = await service.UploadAttachment(fs, _guid, filename);
}
}
replacedert.True(sendArkivmelding);
}
19
View Source File : EFormidlingClientIntTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[Fact]
public async void Send_Invalid_Standard_Business_Doreplacedent()
{
var service = _serviceProvider.GetService<IEFormidlingClient>();
var jsonString = File.ReadAllText(@"TestData\sbd.json");
StandardBusinessDoreplacedent sbd = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(jsonString);
string type = "arkivmelding";
DateTime currentCreationTime = DateTime.Now;
DateTime currentCreationTime2HoursLater = currentCreationTime.AddHours(2);
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.Type = type;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.CreationDateAndTime = currentCreationTime;
WebException ex = await replacedert.ThrowsAsync<WebException>(async () => await service.CreateMessage(sbd));
}
19
View Source File : EFormidlingClientIntTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[Fact]
public async void Send_Attachment_Binary()
{
var service = _serviceProvider.GetService<IEFormidlingClient>();
var jsonString = File.ReadAllText(@"TestData\sbd.json");
StandardBusinessDoreplacedent sbd = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(jsonString);
string process = "urn:no:difi:profile:arkivmelding:administrasjon:ver1.0";
string type = "arkivmelding";
DateTime currentCreationTime = DateTime.Now;
currentCreationTime = currentCreationTime.AddMinutes(-1);
DateTime currentCreationTime2HoursLater = currentCreationTime.AddHours(2);
Guid obj = Guid.NewGuid();
_guid = obj.ToString();
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().Identifier = process;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().ScopeInformation.First().ExpectedResponseDateTime = currentCreationTime2HoursLater;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.Type = type;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.CreationDateAndTime = currentCreationTime;
_ = await service.CreateMessage(sbd);
string filename = "test.pdf";
bool sendBinaryFile = false;
using (FileStream fs = File.OpenRead(@"TestData\test.pdf"))
{
if (fs.Length > 3)
{
sendBinaryFile = await service.UploadAttachment(fs, _guid, filename);
}
}
replacedert.True(sendBinaryFile);
}
19
View Source File : EFormidlingClientIntTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[Fact]
public async void Verify_Sent_Attachments()
{
var service = _serviceProvider.GetService<IEFormidlingClient>();
var jsonString = File.ReadAllText(@"TestData\sbd.json");
StandardBusinessDoreplacedent sbd = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(jsonString);
string process = "urn:no:difi:profile:arkivmelding:administrasjon:ver1.0";
string type = "arkivmelding";
DateTime currentCreationTime = DateTime.Now;
currentCreationTime = currentCreationTime.AddMinutes(-1);
DateTime currentCreationTime2HoursLater = currentCreationTime.AddHours(2);
Guid obj = Guid.NewGuid();
_guid = obj.ToString();
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().Identifier = process;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.BusinessScope.Scope.First().ScopeInformation.First().ExpectedResponseDateTime = currentCreationTime2HoursLater;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.Type = type;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.InstanceIdentifier = _guid;
sbd.StandardBusinessDoreplacedentHeader.DoreplacedentIdentification.CreationDateAndTime = currentCreationTime;
StandardBusinessDoreplacedent sbdVerified = await service.CreateMessage(sbd);
string filename = "arkivmelding.xml";
using (FileStream fs = File.OpenRead(@"TestData\arkivmelding.xml"))
{
if (fs.Length > 3)
{
_ = await service.UploadAttachment(fs, _guid, filename);
}
}
string filenameAttachment = "test.pdf";
using (FileStream fs = File.OpenRead(@"TestData\test.pdf"))
{
if (fs.Length > 3)
{
_ = await service.UploadAttachment(fs, _guid, filenameAttachment);
}
}
await service.SendMessage(_guid);
Thread.Sleep(20000);
var httpClient = new HttpClient();
var messageId = _guid;
var appsetting = _serviceProvider.GetService<IConfiguration>().GetSection("EFormidlingClientSettings:BaseUrl");
var baseUrl = appsetting.Value;
HttpResponseMessage response = await httpClient.GetAsync($"{baseUrl}messages/in/peek?serviceIdentifier=DPO");
string responseBody = await response.Content.ReadreplacedtringAsync();
StandardBusinessDoreplacedent sbdLocked = JsonSerializer.Deserialize<StandardBusinessDoreplacedent>(responseBody);
response = await httpClient.GetAsync($"{baseUrl}messages/in/pop/{messageId}");
FileInfo fileInfo;
using (var stream = response.Content.ReadreplacedtreamAsync().Result)
{
fileInfo = new FileInfo("sent_package.zip");
using (var fileStream = fileInfo.OpenWrite())
{
await stream.CopyToAsync(fileStream);
}
}
response = await httpClient.DeleteAsync($"{baseUrl}messages/in/{messageId}");
_ = await response.Content.ReadreplacedtringAsync();
replacedert.True(fileInfo.Exists);
}
19
View Source File : AuthenticationController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private X509Certificate2 GetLatestCertificateWithRolloverDelay(
List<X509Certificate2> certificates, int rolloverDelayHours)
{
// First limit the search to just those certificates that have existed longer than the rollover delay.
var rolloverCutoff = DateTime.Now.AddHours(-rolloverDelayHours);
var potentialCerts =
certificates.Where(c => c.NotBefore < rolloverCutoff).ToList();
// If no certs could be found, then widen the search to any usable certificate.
if (!potentialCerts.Any())
{
potentialCerts = certificates.Where(c => c.NotBefore < DateTime.Now).ToList();
}
// Of the potential certs, return the newest one.
return potentialCerts
.OrderByDescending(c => c.NotBefore)
.FirstOrDefault();
}
19
View Source File : JwtSigningCertificateProvider.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public async Task<List<X509Certificate2>> GetCertificates()
{
await _semapreplaced.WaitAsync();
try
{
if (_certificateUpdateTime > DateTime.Now && _certificates != null)
{
return _certificates;
}
_certificates = new List<X509Certificate2>();
if (string.IsNullOrEmpty(_keyVaultSettings.ClientId) || string.IsNullOrEmpty(_keyVaultSettings.ClientSecret))
{
_certificates.Add(new X509Certificate2(_certificateSettings.CertificatePath, _certificateSettings.CertificatePwd));
}
else
{
List<X509Certificate2> certificates = await GetAllCertificateVersions(
_keyVaultSettings.SecretUri, _certificateSettings.CertificateName);
_certificates.AddRange(certificates);
}
// Reuse the same list of certificates for 1 hour.
_certificateUpdateTime = DateTime.Now.AddHours(1);
_certificates = _certificates.OrderByDescending(cer => cer.NotBefore).ToList();
return _certificates;
}
finally
{
_semapreplaced.Release();
}
}
19
View Source File : SasTokenProvider.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private bool StillYoung(DateTime created)
{
return created.AddHours(_allowedSasTokenAgeHours) > DateTime.UtcNow;
}
19
View Source File : SasTokenProvider.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private bool StillYoung(DateTime created)
{
return created.AddHours(_storageConfiguration.AllowedSasTokenAgeHours) > DateTime.UtcNow;
}
19
View Source File : IQueryableExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
[Fact]
public void ThenBy_When_Sorted_In_Ascending_Order_Returns_List_Ordered_Ascending()
{
// Arrange
var minDate = DateTime.Now.AddHours(-1);
var midDate = DateTime.Now;
var maxDate = DateTime.Now.AddDays(1);
var queryable = new List<DateTime> { midDate, maxDate, minDate }.AsQueryable();
var orderedQueryable = queryable.OrderBy(date => date.Day);
// Act
var result = orderedQueryable.ThenBy<DateTime>("Hour", OrderByDirection.Ascending);
// replacedert
result.First().ShouldBe(minDate);
result.Last().ShouldBe(maxDate);
}
19
View Source File : IQueryableExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
[Fact]
public void ThenBy_When_OrderedDescending_With_Nested_Property_Returns_List_Ordered_Descending()
{
// Arrange
var minDate = DateTime.Now.AddHours(-1);
var midDate = DateTime.Now;
var maxDate = DateTime.Now.AddDays(1);
var queryable = new List<DateTime> { midDate, minDate, maxDate }.AsQueryable();
var orderedQueryable = queryable.OrderByDescending(date => date.Day);
string nestedProperty = "Date.Hour";
// Act
var result = orderedQueryable.ThenBy<DateTime>(nestedProperty, OrderByDirection.Descending);
// replacedert
result.First().ShouldBe(maxDate);
result.Last().ShouldBe(minDate);
}
See More Examples