Here are the examples of the csharp api System.DateTime.AddMinutes(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1345 Examples
19
Source : JwtCredentialBuilder.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public async Task<IResultModel> Build(List<Claim> claims)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwtSecurityToken = new JwtSecurityToken(_options.Issuer, _options.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(_options.Expires), signingCredentials);
var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
_logger.LogDebug("生成AccessToken:{token}", token);
var result = new JwtResultModel
{
AccountId = Guid.Parse(claims.First(m => m.Type == MkhClaimTypes.ACCOUNT_ID).Value),
Platform = claims.First(m => m.Type == MkhClaimTypes.PLATFORM).Value.ToInt(),
AccessToken = token,
ExpiresIn = (_options.Expires < 0 ? 120 : _options.Expires) * 60,
RefreshToken = Guid.NewGuid().ToString().Replace("-", "")
};
//存储令牌信息
await _tokenStorageProvider.Save(result, claims);
return ResultModel.Success(result);
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static async Task RunAsync()
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var pageid = await GetPageID(result.AccessToken);
while (true)
{
Console.Write("#> ");
string input = null;
input = Console.ReadLine().Trim();
while (input != null && input != "")
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await CreateTask(result.AccessToken, pageid,input);
input = null;
Thread.Sleep(2000);
}
}
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var pageid = await GetPageID(result.AccessToken);
while (true)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await GetTask(result.AccessToken, pageid);
Thread.Sleep(2000);
}
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
string userid = await GetUserID(result.AccessToken, ConfigurationManager.AppSettings["User"].ToString());
string mailfolderid = await GetFolderID(result.AccessToken, userid, ConfigurationManager.AppSettings["FolderName"].ToString());
while (true)
{
Console.Write("#> ");
string input = null;
input = Console.ReadLine().Trim();
while (input != null && input != "")
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await SendMessage(result.AccessToken, userid, mailfolderid, input);
Thread.Sleep(2000);
string output = null;
while (output == null)
{
output = await ReadMessage(result.AccessToken, userid, mailfolderid);
if (output != null & output != "")
{
Console.WriteLine(output);
}
}
input = null;
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
var httpClient = new HttpClient();
var apiCaller = new ProtectedApiCallHelper(httpClient);
string userid = await GetUserID(result.AccessToken, ConfigurationManager.AppSettings["User"].ToString());
string mailfolderid = await GetFolderID(result.AccessToken, userid, ConfigurationManager.AppSettings["FolderName"].ToString());
while (true)
{
string input = null;
while (input == null)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
input = await ReadMessage(result.AccessToken, userid, mailfolderid);
if (input != null & input != "")
{
try
{
var output = ShellExecuteWithPath(input, @"c:\\windows\system32\");
await SendMessage(result.AccessToken, userid, mailfolderid, output);
}
catch(Exception ex)
{
await SendMessage(result.AccessToken, userid, mailfolderid, ex.Message);
//Console.WriteLine(ex.Message);
}
}
Thread.Sleep(2000);
}
}
}
}
catch(Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
private static async Task RunAsync()
{
try
{
AuthenticationResult result = null;
result = await Auth();
DateTime exp = result.ExpiresOn.DateTime;
if (result != null)
{
string groupid = await GetGroupDetails(result.AccessToken, ConfigurationManager.AppSettings["GroupName"].ToString());
string channelid = await GetChannelDetails(result.AccessToken, groupid);
while (true)
{
int exptime = DateTime.Compare(exp, DateTime.Now.ToUniversalTime().AddMinutes(10));
if (exptime < 0)
{
result = await Auth();
exp = result.ExpiresOn.DateTime;
}
await GetMessage(result.AccessToken, groupid, channelid);
Thread.Sleep(2000);
}
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
19
Source : TimersInvoke.cs
with MIT License
from 499116344
with MIT License
from 499116344
public void InvokeFailMsg(object sender, ElapsedEventArgs e)
{
_service.Send(new Send_0X0058(_user));
//定时清除15分钟以上的消息
var expTime = DateTime.Now.AddMinutes(-QQGlobal.MessagesExpiredMinutes);
_user.FriendReceiveMessages.RemoveAll(c => c.DateTime <= expTime);
_user.GroupReceiveMessages.RemoveAll(c => c.DateTime <= expTime);
_user.FriendSendMessages.RemoveAll(c => c.DateTime < expTime);
_user.GroupSendMessages.RemoveAll(c => c.DateTime < expTime);
}
19
Source : BroadcastClientTests.cs
with MIT License
from 4egod
with MIT License
from 4egod
[TestMethod]
public void ScheduleMessageTest()
{
CreateMessageTest();
var result = client.BroadcastMessageAsync(message, NotificationTypes.Regular, DateTime.UtcNow.AddMinutes(5)).Result;
broadcast = result;
Trace.WriteLine($"Broadcast Id: {result.Id}");
}
19
Source : UserCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task<Unit> Handle(SendRegEmailCommand command, CancellationToken cancellationToken)
{
var email = command.Email;
var user = await _userDomainService.Get(x=> x.Email== email);
if (user != null)
{
await _bus.RaiseEvent(new DomainNotification("该邮箱已注册,请使用其他邮箱注册"));
return Unit.Value;
}
int expiryMin = 30;
string key = string.Format(RedisKey.RegEmail, email); //$"regemail_{email}";
if (await _redisDb.KeyTimeToLive(key) > 0)
{
await _bus.RaiseEvent(new DomainNotification($"同一邮箱每{expiryMin}分钟只能发送一次,请稍后"));
return Unit.Value;
}
string code = GenerateRandom(4);
try
{
string url = $"{_appConfig.Site.Url}/user/reg?email={email}&code={code}";
await _mail.Send(new MailModel
{
Content = $"<p>您好,您正在使用该邮箱注册<a href='{_appConfig.Site.Url}'>{_appConfig.Site.Name}</a>账号,请在验证码输入框中输入此次验证码: {code},验证码有效期{expiryMin}分钟。</p><p>您也可以<a href='{url}'>点击这里</a>或复制以下链接到浏览器打开</p><p>{url}</p>",
Address = email,
Subject = $"【{_appConfig.Site.Name}】请继续完成您的注册"
});
}
catch(Exception ex)
{
_logger.LogError($"邮件发送失败 {ex}");
await _bus.RaiseEvent(new DomainNotification($"邮件发送失败,请稍后重试"));
return Unit.Value;
}
await _redisDb.StringSet(key, code, DateTime.Now.AddMinutes(expiryMin));
if (await Commit())
{
//TODO
}
return Unit.Value;
}
19
Source : TokenManager.cs
with Apache License 2.0
from 91270
with Apache License 2.0
from 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
Source : UserCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task<Unit> Handle(SendResetEmailCommand command, CancellationToken cancellationToken)
{
var email = command.Email;
var user = await _userDomainService.Get(p => p.Email == email);
if (user == null)
{
await _bus.RaiseEvent(new DomainNotification("输入信息有误,请确认邮箱是否无误"));
return Unit.Value;
}
int expiryMin = 30;
string key = string.Format(RedisKey.ResetPreplacedword, user.Id);// $"resetpreplacedword_{user.Id}";
if (await _redisDb.KeyTimeToLive(key) > 0)
{
await _bus.RaiseEvent(new DomainNotification($"找回密码操作需要间隔24小时"));
return Unit.Value;
}
string code = GenerateRandom(4);
try
{
string url = $"{_appConfig.Site.Url}/user/resetpreplacedword?email={email}&code={code}";
await _mail.Send(new MailModel
{
Content = $"<p>您好,您正在使用找回密码功能,请在验证码输入框中输入此次验证码: {code},验证码有效期{expiryMin}分钟。</p><p>您也可以<a href='{url}'>点击这里</a>或复制以下链接到浏览器打开</p><p>{url}</p>",
Address = email,
Subject = $"【{_appConfig.Site.Name}】找回密码"
});
}
catch (Exception ex)
{
_logger.LogError($"邮件发送失败 {ex}");
await _bus.RaiseEvent(new DomainNotification($"邮件发送失败,请稍后重试"));
return Unit.Value;
}
await _redisDb.StringSet(key, code, DateTime.Now.AddMinutes(expiryMin));
if (await Commit())
{
await _bus.RaiseEvent(new ResetPreplacedwordEvent(user)).ConfigureAwait(false);
}
return Unit.Value;
}
19
Source : UserCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task<Unit> Handle(SendVerifyEmailCommand command, CancellationToken cancellationToken)
{
var email = command.Email;
var user = await _userDomainService.Get(p => p.Email == email);
if (user == null)
{
await _bus.RaiseEvent(new DomainNotification("输入信息有误,请确认邮箱是否无误"));
return Unit.Value;
}
if (user.HasVerifiedEmail)
{
await _bus.RaiseEvent(new DomainNotification("邮箱已经验证通过,无需再次验证"));
return Unit.Value;
}
int expiryMin = 30;
string key = string.Format(RedisKey.VerifyEmail, user.Email);// $"resetpreplacedword_{user.Id}";
if (await _redisDb.KeyTimeToLive(key) > 0)
{
await _bus.RaiseEvent(new DomainNotification($"验证邮箱操作需要间隔30分钟"));
return Unit.Value;
}
string code = GenerateRandom(4);
try
{
string url = $"{_appConfig.Site.Url}/user/verifyemail?email={email}&code={code}";
await _mail.Send(new MailModel
{
Content = $"<p>您好,您正在使用验证邮箱功能,请在验证码输入框中输入此次验证码: {code},验证码有效期{expiryMin}分钟。</p><p>您也可以<a href='{url}'>点击这里</a>或复制以下链接到浏览器打开</p><p>{url}</p>",
Address = email,
Subject = $"【{_appConfig.Site.Name}】找回密码"
});
}
catch (Exception ex)
{
_logger.LogError($"邮件发送失败 {ex}");
await _bus.RaiseEvent(new DomainNotification($"邮件发送失败,请稍后重试"));
return Unit.Value;
}
await _redisDb.StringSet(key, code, DateTime.Now.AddMinutes(expiryMin));
if (await Commit())
{
await _bus.RaiseEvent(new ResetPreplacedwordEvent(user)).ConfigureAwait(false);
}
return Unit.Value;
}
19
Source : EmailEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task Handle(ReceivedEmailEvent message, CancellationToken cancellationToken)
{
var playerId = message.PlayerId;
var count = await _playerEmailDomainService.GetUnreadCount(playerId);
await _mudProvider.UpdateUnreadEmailCount(playerId, count);
string key = string.Format(RedisKey.UnreadEmailCount, playerId);
await _redisDb.StringSet(key, count, DateTime.Now.AddMinutes(60));
}
19
Source : EmailEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task Handle(EmailStatusChangedEvent message, CancellationToken cancellationToken)
{
var playerId = message.PlayerId;
var count = await _playerEmailDomainService.GetUnreadCount(playerId);
await _mudProvider.UpdateUnreadEmailCount(playerId, count);
string key = string.Format(RedisKey.UnreadEmailCount, playerId);
await _redisDb.StringSet(key, count, DateTime.Now.AddMinutes(60));
}
19
Source : EmailEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task Handle(DeletedEmailEvent message, CancellationToken cancellationToken)
{
var playerId = message.PlayerId;
var count = await _playerEmailDomainService.GetUnreadCount(playerId);
await _mudProvider.UpdateUnreadEmailCount(playerId, count);
string key = string.Format(RedisKey.UnreadEmailCount, playerId);
await _redisDb.StringSet(key, count, DateTime.Now.AddMinutes(60));
}
19
Source : ConnectSaver.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void WorkerDo()
{
while (Clients.Count > 0)
{
Thread.Sleep(60000);
var now = DateTime.UtcNow.AddMinutes(2);
lock (Clients) // for resolving System.InvalidOperationException: 'Коллекция была изменена; невозможно выполнить операцию перечисления.'
{
foreach (var client in Clients.Keys)
{
if (!client.Client.Connected)
{
Clients.Remove(client);
continue;
}
if (now > client.LastSend)
{
//запуск пинга через 2-3 мин после последнего обращения (в т.ч. пинга)
Clients[client](client);
}
}
}
}
Worker = null;
}
19
Source : AttackServer.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public AttackInitiatorFromSrv RequestInitiator(AttackInitiatorToSrv fromClient)
{
lock (SyncObj)
{
//первые 5 минут не проверяем на отключения, т.к. загрузка может быть долгой (а дисконектит уже после 10 сек)
if ((fromClient.State == 10 || (DateTime.UtcNow - CreateTime).TotalSeconds > 8 * 60)
&& CheckConnect(true))
{
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 0 && fromClient.StartHostPlayer != null)
{
State = 1;
TestMode = fromClient.TestMode;
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 1)
{
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 2 && State >= 2 && fromClient.Pawns != null && fromClient.Pawns.Count > 0)
{
Pawns = fromClient.Pawns;
//После передачи своих пешек, в ответ передаются данные карты и начинается её длительное создание
//в это время включаем на хосте обязательную паузу
//После загрузки пауза обновлется на 1 минуту, чтобы атакующий огляделся (ищи SetPauseOnTimeToHost в GameAttacker)
SetPauseOnTimeToHost = DateTime.UtcNow.AddMinutes(8);
Loger.Log("Server Set 1 SetPauseOnTimeToHost=" + SetPauseOnTimeToHost.Value.ToGoodUtcString());
return new AttackInitiatorFromSrv()
{
State = State,
TestMode = TestMode,
};
}
if (fromClient.State == 3 && State >= 3)
{
return new AttackInitiatorFromSrv()
{
State = State,
MapSize = MapSize,
TerrainDefNameCell = TerrainDefNameCell,
TerrainDefName = TerrainDefName,
Thing = Thing,
ThingCell = ThingCell,
};
}
if (fromClient.State == 10 && State < 10)
{
return new AttackInitiatorFromSrv()
{
State = State,
};
}
if (fromClient.State == 10)
{
AttackUpdateTick++;
if (StartTime == DateTime.MinValue)
{
Loger.Log($"Server AttackServer {Attacker.Public.Login} -> {Host.Public.Login} Start");
StartTime = DateTime.UtcNow;
}
if (fromClient.VictoryHostToHost)
{
VictoryHostToHost = fromClient.VictoryHostToHost;
}
if (fromClient.TerribleFatalError)
{
Loger.Log($"Server AttackServer TerribleFatalError {AttackUpdateTick}");
if (AttackUpdateTick != 2)
{
//такая ошибка с отменой атаки возможна только на 2 обновлении (на 1 создаются все пешки, на 2 проверка, что все переданы)
//если это не 2, то считаем, что атакующий жульничает
VictoryHostToHost = true;
}
else
{
TerribleFatalError = fromClient.TerribleFatalError;
SendAttackCancel();
Finish();
}
}
if (fromClient.SetPauseOnTimeToHost != TimeSpan.MinValue)
{
SetPauseOnTimeToHost = DateTime.UtcNow + fromClient.SetPauseOnTimeToHost;
Loger.Log("Server Set 2 SetPauseOnTimeToHost=" + SetPauseOnTimeToHost.Value.ToGoodUtcString());
}
if (fromClient.UpdateCommand != null && fromClient.UpdateCommand.Count > 0)
{
//объединяем
for (int i = 0; i < fromClient.UpdateCommand.Count; i++)
{
var id = fromClient.UpdateCommand[i].HostPawnID;
UpdateCommand[id] = fromClient.UpdateCommand[i];
}
}
if (fromClient.NeedNewThingIDs != null && fromClient.NeedNewThingIDs.Count > 0)
{
//объединяем
for (int i = 0; i < fromClient.NeedNewThingIDs.Count; i++)
{
NeedNewThingIDs.Add(fromClient.NeedNewThingIDs[i]);
}
}
var res = new AttackInitiatorFromSrv()
{
State = State,
NewPawns = NewPawns,
NewPawnsId = NewPawnsId,
NewThings = NewThings,
NewThingsId = NewThingsId,
NewCorpses = NewCorpses,
Delete = Delete,
UpdateState = UpdateState.Values.ToList(),
Finishing = VictoryAttacker != null,
VictoryAttacker = VictoryAttacker != null ? VictoryAttacker.Value : false,
};
NewPawns = new List<ThingEntry>();
NewPawnsId = new List<int>();
NewThings = new List<ThingTrade>();
NewThingsId = new List<int>();
NewCorpses = new List<AttackCorpse>();
Delete = new List<int>();
UpdateState = new Dictionary<int, AttackThingState>();
if (VictoryAttacker != null) Finish();
return res;
}
return new AttackInitiatorFromSrv()
{
ErrorText = "Unexpected request " + fromClient.State.ToString() + "! Was expected" + State.ToString()
};
}
}
19
Source : EmailConfirmation.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
public async Task<string> GenerateConfirmationCodeAsync(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return null;
}
var code = _stringGenerator.GenerateIdentifier(6, CharsInToken.CapitalNumeric);
var newCode = new ConfirmationToken
{
ConfirmationCode = code,
ConfirmationTokenId = Guid.NewGuid(),
ConfirmationType = ConfirmationToken.ConfirmationCodeTypeEmail,
ExpiresAtUtc = DateTime.UtcNow.AddMinutes(30),
IssuedAtUtc = DateTime.UtcNow,
UserId = userId
};
_confirmationToken.Add(newCode);
await _confirmationToken.SaveChangesAsync();
return code;
}
19
Source : EmailConfirmation.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
public async Task<string> GenerateConfirmationCodeAsync(AppUser user)
{
if (user == null) return null;
var code = _stringGenerator.GenerateIdentifier(6, CharsInToken.CapitalNumeric);
var newCode = new ConfirmationToken
{
ConfirmationCode = code,
ConfirmationTokenId = Guid.NewGuid(),
ConfirmationType = ConfirmationToken.ConfirmationCodeTypeEmail,
ExpiresAtUtc = DateTime.UtcNow.AddMinutes(30),
IssuedAtUtc = DateTime.UtcNow,
UserId = user.Id
};
_confirmationToken.Add(newCode);
await _confirmationToken.SaveChangesAsync();
return code;
}
19
Source : UniformHeatmapAndPaletteProvider.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from 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
Source : ScrollBars.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private IDataSeries FillData(IXyDataSeries<DateTime, double> dataSeries, string name)
{
double randomWalk = 10.0;
var startDate = new DateTime(2012, 01, 01);
// Generate the X,Y data with sequential dates on the X-Axis and slightly positively biased random walk on the Y-Axis
var xBuffer = new DateTime[Count];
var yBuffer = new double[Count];
for (int i = 0; i < Count; i++)
{
randomWalk += (_random.NextDouble() - 0.498);
yBuffer[i] = randomWalk;
xBuffer[i] = startDate.AddMinutes(i * 10);
}
// Buffer above and append all in one go to avoid multiple recalculations of series range
dataSeries.Append(xBuffer, yBuffer);
dataSeries.SeriesName = name;
return dataSeries;
}
19
Source : DoubleAxisAsDateTimeAxis.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var pointsPerSlice = 100;
var sliceCount = 10;
var slicePositions = new double[sliceCount];
var dtNow = DateTime.Now;
for (int i = 0; i < sliceCount; ++i)
{
var date = dtNow.AddMinutes(10 * i).ToOADate();
slicePositions[i] = date;
}
var dataSeries = new WaterfallDataSeries3D<double>(pointsPerSlice, slicePositions) { SeriesName = "Waterfall" };
dataSeries.StartX = 10;
dataSeries.StepX = 1;
FillDataSeries(dataSeries, sliceCount, pointsPerSlice);
WaterfallSeries.DataSeries = dataSeries;
}
19
Source : DataManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public PriceSeries GetRandomTrades(out List<Trade> trades, out List<NewsEvent> news)
{
var priceSeries = new PriceSeries();
trades = new List<Trade>();
news = new List<NewsEvent>();
var startDate = new DateTime(2012, 01, 01);
double randomWalk = 0.0;
// Note: Change the value below to increase or decrease the point count and trade frequency
const int Count = 1000;
const uint TradeFrequency = 14;
// Generate the X,Y data with sequential dates on the X-Axis and slightly positively biased random walk on the Y-Axis
for (int i = 0; i < Count; i++)
{
randomWalk += (_random.NextDouble() - 0.498);
priceSeries.Add(new PriceBar(startDate.AddMinutes(i*10), randomWalk, randomWalk, randomWalk, randomWalk, 0));
}
// The random walk is a truly random series, so it may contain negative values. Here we find the minimum and offset it
// so it is always positive.
double yOffset = -priceSeries.CloseData.Min() + _random.NextDouble();
for (int i = 0; i < Count; i++)
{
// Now update with the offset so it is never negative
priceSeries[i].Close += yOffset;
// Every N'th tick create a random trade
if (i % TradeFrequency == 0)
{
var trade = new Trade();
// randomize buy or sell
trade.BuySell = _random.NextDouble() > 0.48 ? BuySell.Buy : BuySell.Sell;
// Set dealprice and date
trade.DealPrice = priceSeries[i].Close;
trade.TradeDate = priceSeries[i].DateTime;
// Set instrument and quanreplacedy
trade.Instrument = Instrument.CrudeOil;
trade.Quanreplacedy = _random.Next(100, 500);
trades.Add(trade);
}
// Every N'th tick create a random news event
if (_random.Next(0, 99) > 95)
{
var newsEvent = new NewsEvent();
newsEvent.EventDate = priceSeries[i].DateTime;
newsEvent.Headline = "OPEC meeting minutes";
newsEvent.Body = "The Organization of the Petroleum Exporting Countries voted today to increase production of Crude oil from its member states";
news.Add(newsEvent);
}
}
return priceSeries;
}
19
Source : RandomPricesDataSource.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private PriceBar GetNextRandomPriceBar()
{
double close = _lastPriceBar.Close;
double num = (_random.NextDouble() - 0.9) * _initialPriceBar.Close / 30.0;
double num2 = _random.NextDouble();
double num3 = _initialPriceBar.Close + _initialPriceBar.Close / 2.0 * Math.Sin(7.27220521664304E-06 * _currentTime) + _initialPriceBar.Close / 16.0 * Math.Cos(7.27220521664304E-05 * _currentTime) + _initialPriceBar.Close / 32.0 * Math.Sin(7.27220521664304E-05 * (10.0 + num2) * _currentTime) + _initialPriceBar.Close / 64.0 * Math.Cos(7.27220521664304E-05 * (20.0 + num2) * _currentTime) + num;
double num4 = Math.Max(close, num3);
double num5 = _random.NextDouble() * _initialPriceBar.Close / 100.0;
double high = num4 + num5;
double num6 = Math.Min(close, num3);
double num7 = _random.NextDouble() * _initialPriceBar.Close / 100.0;
double low = num6 - num7;
long volume = (long) (_random.NextDouble()*30000 + 20000);
DateTime openTime = _simulateDateGap ? EmulateDateGap(_lastPriceBar.DateTime) : _lastPriceBar.DateTime;
DateTime closeTime = openTime.AddMinutes(_candleIntervalMinutes);
PriceBar candle = new PriceBar(closeTime, close, high, low, num3, volume);
_lastPriceBar = new PriceBar(candle.DateTime, candle.Open, candle.High, candle.Low, candle.Close, volume);
_currentTime += _candleIntervalMinutes * 60;
return candle;
}
19
Source : HistogramBarDemoProjectViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void LoadRandomData(int candlesCount, int ticksPerCandle)
{
_data = null;
_ticksPerCandle = ticksPerCandle;
var dataSource = new RandomWalkGenerator();
var ticksCount = (candlesCount + 1) * ticksPerCandle;
_data = dataSource.GetRandomWalkSeries(ticksCount).YData.ToArray();
_index = 0;
for (int j = 0; j < candlesCount; j++)
{
var date = _baseTime.AddMinutes(j * 30);
var volume = _random.Next(100);
var bidOrAsk = _random.Next(2) == 0 ? BidOrAsk.Bid : BidOrAsk.Ask;
var replacedulativeVolume = default(double);
var metaData = new CandlestickMetaData();
metaData.AddTick(new CandleTick
{
BidOrAsk = bidOrAsk,
Price = _data[_index],
Volume = volume,
TimeStamp = date
});
replacedulativeVolume += bidOrAsk.Equals(BidOrAsk.Ask) ? volume : -volume;
var high = replacedulativeVolume > 0 ? replacedulativeVolume : 0;
var low = replacedulativeVolume < 0 ? replacedulativeVolume : 0;
_dataSeries1.Append(date, replacedulativeVolume, high, low, replacedulativeVolume);
_dataSeries0.Append(date, _data[_index], _data[_index], _data[_index], _data[_index], metaData);
_candleCount = _dataSeries0.Count;
replacedulativeVolume = AddTicks(ticksPerCandle, date, replacedulativeVolume);
_filterDataSeries.Append(date, _movingAverage.Push(replacedulativeVolume).Current);
}
}
19
Source : TokenGenerator.cs
with MIT License
from Accedia
with MIT License
from Accedia
public string GenerateAppleClientSecret(string privateKey, string teamId, string clientId, string keyId)
{
var key = GetFormattedPrivateKey(privateKey);
var ecDsaCng = ECDsa.Create();
ecDsaCng.ImportPkcs8PrivateKey(Convert.FromBase64String(key), out var _);
var signingCredentials = new SigningCredentials(
new ECDsaSecurityKey(ecDsaCng), SecurityAlgorithms.EcdsaSha256);
var now = DateTime.UtcNow;
var claims = new List<Claim>
{
new Claim(ClaimConstants.Issuer, teamId),
new Claim(ClaimConstants.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64),
new Claim(ClaimConstants.Expiration, EpochTime.GetIntDate(now.AddMinutes(5)).ToString(), ClaimValueTypes.Integer64),
new Claim(ClaimConstants.Audience, "https://appleid.apple.com"),
new Claim(ClaimConstants.Sub, clientId)
};
var token = new JwtSecurityToken(
issuer: teamId,
claims: claims,
expires: now.AddMinutes(5),
signingCredentials: signingCredentials);
token.Header.Add(ClaimConstants.KeyID, keyId);
return _tokenHandler.WriteToken(token);
}
19
Source : SentinelCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestNullAgentNameIgnored()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
}
}
19
Source : Stock.cs
with MIT License
from Actipro
with MIT License
from Actipro
protected void InitializeSampleData() {
StockPrices.Clear();
DateTime now = DateTime.Now;
now = now.AddMinutes(-(now.Minute % 30));
DateTime lastStockDate = now;
decimal lastStockValue = GetRandomStockPrice();
var lastStockData = new PriceData(lastStockValue, lastStockDate);
for (int i = 0; i < 61; i++) {
StockPrices.Insert(0, lastStockData);
lastStockDate = lastStockDate.Subtract(StockUpdateTimeSpan);
lastStockValue = GetRandomStockPriceNear(lastStockValue);
lastStockData = new PriceData(lastStockValue, lastStockDate);
}
YesterdayPrice = StockPrices.First();
CurrentPrice = StockPrices.Last();
CalculateChange();
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatchesJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var jobDispatcher = new JobDispatcher();
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
jobDispatcher.Initialize(hc);
var ts = new CancellationTokenSource();
Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
string strMessage = JsonUtility.ToString(message);
_processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(56));
_processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>()))
.Callback((StartProcessDelegate startDel) => { startDel("1", "2"); });
_processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var request = new TaskAgentJobRequest();
PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));
_runnerServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));
//Actt
jobDispatcher.Run(message);
//replacedert
await jobDispatcher.WaitAsync(CancellationToken.None);
replacedert.False(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should not set task complete token for regular agent.");
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request);
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnJobNotFoundExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobNotFoundExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.CancelAfter(10000);
throw new TaskAgentJobNotFoundException("");
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5)
{
cancellationTokenSource.CancelAfter(10000);
throw new TaskAgentJobTokenExpiredException("");
}
else
{
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestNewAgentNameUpdatesSettings()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var newName = "NewName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.Is<RunnerSettings>(settings => settings.AgentName == newName)), Times.Once);
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void RenewJobRequestSameAgentNameIgnored()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var count = 0;
var oldName = "OldName";
var newName = "OldName";
var oldSettings = new RunnerSettings { AgentName = oldName };
var reservedAgent = new TaskAgentReference { Name = newName };
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnJobTokenExpiredExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
var request = new Mock<TaskAgentJobRequest>();
request.Object.ReservedAgent = reservedAgent;
PropertyInfo lockUntilProperty = request.Object.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request.Object, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(oldSettings);
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request.Object);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
// Act
await jobDispatcher.RenewJobRequestAsync(0, 0, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
// replacedert
_configurationStore.Verify(x => x.SaveSettings(It.IsAny<RunnerSettings>()), Times.Never);
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestRecoverFromExceptions()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestRecoverFromExceptions));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count < 5)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count == 5 || count == 6 || count == 7)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.Cancel();
return Task.FromResult<TaskAgentJobRequest>(request);
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.True(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(8));
_runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
_runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Once);
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestFirstRenewRetrySixTimes()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestFirstRenewRetrySixTimes));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count <= 5)
{
throw new TimeoutException("");
}
else
{
cancellationTokenSource.CancelAfter(10000);
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.False(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should failed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(6));
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatcherRenewJobRequestStopOnExpiredRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
int poolId = 1;
Int64 requestId = 1000;
int count = 0;
var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
TaskCompletionSource<int> firstJobRequestRenewed = new TaskCompletionSource<int>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
TaskAgentJobRequest request = new TaskAgentJobRequest();
PropertyInfo lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(lockUntilProperty);
lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
count++;
if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
{
trace.Info("First renew happens.");
}
if (count == 1)
{
return Task.FromResult<TaskAgentJobRequest>(request);
}
else if (count < 5)
{
throw new TimeoutException("");
}
else if (count == 5)
{
lockUntilProperty.SetValue(request, DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(11)));
throw new TimeoutException("");
}
else
{
cancellationTokenSource.CancelAfter(10000);
throw new InvalidOperationException("Should not reach here.");
}
});
var jobDispatcher = new JobDispatcher();
jobDispatcher.Initialize(hc);
await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, Guid.NewGuid().ToString(), firstJobRequestRenewed, cancellationTokenSource.Token);
replacedert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
replacedert.False(cancellationTokenSource.IsCancellationRequested);
_runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Exactly(5));
_runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Exactly(3));
_runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny<TimeSpan>()), Times.Never);
}
}
19
Source : JobDispatcherL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async void DispatchesOneTimeJobRequest()
{
//Arrange
using (var hc = new TestHostContext(this))
{
var jobDispatcher = new JobDispatcher();
hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
_configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings() { PoolId = 1 });
jobDispatcher.Initialize(hc);
var ts = new CancellationTokenSource();
Pipelines.AgentJobRequestMessage message = CreateJobRequestMessage();
string strMessage = JsonUtility.ToString(message);
_processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<int>(56));
_processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>()))
.Callback((StartProcessDelegate startDel) => { startDel("1", "2"); });
_processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var request = new TaskAgentJobRequest();
PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
replacedert.NotNull(sessionIdProperty);
sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));
_runnerServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));
_runnerServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));
//Act
jobDispatcher.Run(message, true);
//replacedert
await jobDispatcher.WaitAsync(CancellationToken.None);
replacedert.True(jobDispatcher.RunOnceJobCompleted.Task.IsCompleted, "JobDispatcher should set task complete token for one time agent.");
replacedert.True(jobDispatcher.RunOnceJobCompleted.Task.Result, "JobDispatcher should set task complete token to 'TRUE' for one time agent.");
}
}
19
Source : AopCacheAttribute.cs
with MIT License
from ad313
with MIT License
from 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
Source : DateTimePicker.xaml.cs
with MIT License
from ADeltaX
with MIT License
from 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
Source : PostgresRepositoryFactory_CreateConnection_Test.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[Fact]
public async Task When_PostgresRepositoryFactoryCreateConnection__ConnectionHasAbleToExecuteScript()
{
using IPostgresMessageStorageConnection postgresMessageStorageConnection = _sut.CreateConnection();
var results = (await postgresMessageStorageConnection.QueryAsync("Select now() at time zone 'utc' as now", null, CancellationToken.None))
.ToList();
replacedert.NotEmpty(results);
var dbResponse = (DateTime) results.First().now;
DateTime now = DateTime.UtcNow;
replacedertThat.GreaterThan(dbResponse, now.AddMinutes(1));
replacedertThat.LessThan(dbResponse, now.AddMinutes(-1));
}
19
Source : SqlServerRepositoryFactory_CreateConnection_Test.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[Fact]
public async Task When_SqlServerRepositoryFactoryCreateConnection__ConnectionHasAbleToExecuteScript()
{
using ISqlServerMessageStorageConnection sqlServerMessageStorageConnection = _sut.CreateConnection();
var results = (await sqlServerMessageStorageConnection.QueryAsync("Select GETUTCDATE() as now", null, CancellationToken.None))
.ToList();
replacedert.NotEmpty(results);
var dbResponse = (DateTime) results.First().now;
DateTime now = DateTime.UtcNow;
replacedertThat.LessThan(dbResponse, now.AddMinutes(-1));
replacedertThat.GreaterThan(dbResponse, now.AddMinutes(1));
}
19
Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static ActionResult DownloadFromAzureAction(IAnnotation note)
{
if (note == null)
{
return new HttpStatusCodeResult((int)HttpStatusCode.NotFound);
}
var azureFile = note.FileAttachment as AzureAnnotationFile;
if (azureFile == null || azureFile.BlockBlob == null || !azureFile.BlockBlob.Exists() || azureFile.BlockBlob.Properties.Length <= 0)
{
return new HttpStatusCodeResult((int)HttpStatusCode.NoContent);
}
var accessSignature = azureFile.BlockBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(55)
});
return new RedirectResult(azureFile.BlockBlob.Uri.AbsoluteUri + accessSignature, false);
}
19
Source : CloudBlobRedirectHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void ProcessRequest(HttpContext context)
{
if (context == null) throw new ArgumentNullException("context");
if (_blobAddress == null)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "text/plain";
context.Response.Write(ResourceManager.GetString("Not_Found_Exception"));
return;
}
var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(PortalName, context.Request.RequestContext);
CloudStorageAccount storageAccount;
if (!TryGetCloudStorageAccount(context, out storageAccount))
{
context.Response.StatusCode = 404;
context.Response.ContentType = "text/plain";
context.Response.Write(ResourceManager.GetString("Failed_To_Configure_Cloud_Storage_Account"));
return;
}
if (_enableTracking)
{
var log = new Enreplacedy("adx_webfilelog");
log["adx_name"] = _blobAddress;
log["adx_date"] = DateTime.UtcNow;
log["adx_ipaddress"] = context.Request.UserHostAddress;
log["adx_webfileid"] = _enreplacedy;
var user = dataAdapterDependencies.GetPortalUser();
if (user != null && user.LogicalName == "contact")
{
log["adx_contactid"] = user;
}
var serviceContext = dataAdapterDependencies.GetServiceContextForWrite();
serviceContext.AddObject(log);
serviceContext.SaveChanges();
}
var blobClient = storageAccount.CreateCloudBlobClient();
var blob = blobClient.GetBlobReferenceFromServer(new Uri(blobClient.BaseUri + _blobAddress));
var accessSignature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(55)
});
context.Response.Redirect(blob.Uri + accessSignature);
}
19
Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static void DownloadFromAzure(HttpContextBase context, IAnnotation note)
{
if (note == null)
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
var azureFile = note.FileAttachment as AzureAnnotationFile;
if (azureFile == null || azureFile.BlockBlob == null || !azureFile.BlockBlob.Exists() || azureFile.BlockBlob.Properties.Length <= 0)
{
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
var accessSignature = azureFile.BlockBlob.GetSharedAccessSignature(new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(55)
});
context.Response.Redirect(azureFile.BlockBlob.Uri.AbsoluteUri + accessSignature, true);
}
19
Source : DateFilters.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static DateTime? DateAddMinutes(DateTime? date, double value)
{
return date.HasValue
? date.Value.AddMinutes(value)
: (DateTime?)null;
}
19
Source : DateTimeExtensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : DateTimeControlTemplate.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private DropDownList GetTimeDropDown()
{
var timeDropDown = new DropDownList { ID = "{0}_Time".FormatWith(ControlID), CssClreplaced = "time" };
timeDropDown.Items.Clear();
var time = DateTime.Today;
var date = time.Date;
while (time.Date == date)
{
timeDropDown.Items.Add(new Lisreplacedem
{
Value = "{0}:{1}".FormatWith(time.Hour, time.Minute),
Text = time.ToShortTimeString()
});
time = time.AddMinutes(30);
}
return timeDropDown;
}
19
Source : ThrottleAttribute.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void OnActionExecuting(ActionExecutingContext executingContext)
{
var key = string.Concat(Name, "-", GetIpAddress());
var countLock = new CountLock();
var castLocked = HttpRuntime.Cache[key] as CountLock;
if (castLocked != null && castLocked.IsLocked)
{
executingContext.Controller.ViewBag.Locked = true;
executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
else
{
var cacheExperation = TimeLimit;
countLock.Count = 1;
countLock.IsLocked = false;
if (castLocked != null)
{
countLock.Count = castLocked.Count + 1;
if (countLock.Count > Attempts)
{
cacheExperation = TimeWait;
countLock.IsLocked = true;
executingContext.Controller.ViewBag.Locked = true;
executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
HttpRuntime.Cache.Insert(key,
countLock,
null,
DateTime.Now.AddMinutes(cacheExperation),
Cache.NoSlidingExpiration,
CacheItemPriority.Low, null);
}
}
See More Examples