Here are the examples of the csharp api System.DateTime.AddSeconds(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2186 Examples
19
Source : JwtTokenMock.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static string GenerateToken(ClaimsPrincipal principal, TimeSpan tokenExipry, string issuer = "UnitTest")
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(principal.Idenreplacedy),
Expires = DateTime.UtcNow.AddSeconds(tokenExipry.TotalSeconds),
SigningCredentials = GetSigningCredentials(issuer),
Audience = "altinn.no",
Issuer = issuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string tokenstring = tokenHandler.WriteToken(token);
return tokenstring;
}
19
Source : JwtTokenMock.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static string GenerateToken(ClaimsPrincipal principal, TimeSpan tokenExpiry, string issuer = "UnitTest")
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(principal.Idenreplacedy),
Expires = DateTime.UtcNow.AddSeconds(tokenExpiry.TotalSeconds),
SigningCredentials = GetSigningCredentials(),
Audience = "altinn.no",
Issuer = issuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string serializedToken = tokenHandler.WriteToken(token);
return serializedToken;
}
19
Source : JwtGenerator.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static string GenerateToken(ClaimsPrincipal principal, TimeSpan tokenExpiry, string issuer = "UnitTest")
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(principal.Idenreplacedy),
Expires = DateTime.UtcNow.AddSeconds(tokenExpiry.TotalSeconds),
SigningCredentials = GetSigningCredentials(issuer),
Audience = "altinn.no",
Issuer = issuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string serializedToken = tokenHandler.WriteToken(token);
return serializedToken;
}
19
Source : AuthenticationService.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public string GenerateToken(ClaimsPrincipal principal, int cookieValidityTime)
{
List<X509Certificate2> certificates = new List<X509Certificate2>
{
new X509Certificate2("jwtselfsignedcert.pfx", "qwer1234") // lgtm [cs/hardcoded-credentials]
};
TimeSpan tokenExpiry = new TimeSpan(0, cookieValidityTime, 0);
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdenreplacedy(principal.Idenreplacedy),
Expires = DateTime.UtcNow.AddSeconds(tokenExpiry.TotalSeconds),
SigningCredentials = new X509SigningCredentials(certificates[0])
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string serializedToken = tokenHandler.WriteToken(token);
return serializedToken;
}
19
Source : CollabHistoryItemFactory.cs
with MIT License
from Alword
with MIT License
from Alword
private static DateTime TimeStampToDateTime(double timeStamp)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(timeStamp).ToLocalTime();
return dateTime;
}
19
Source : MainForm.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
private void NetPlay(int time,string name)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
DateTime dt = startTime.AddSeconds(time);
dtpSyncTime.Value = dt;
SyncButton_Click(new object(), new EventArgs());
//var msTime = (dt - DateTime.Now).TotalMilliseconds;
//StartKeyPlayback((int)msTime + (int)numericUpDown2.Value);
Log.overlayLog($"网络控制:{name.Trim().Replace("\0", string.Empty)}发起倒计时,目标时间:{dt.ToString("HH:mm:ss")}");
//tlblTime.Text = $"{name.Trim().Replace("\0",string.Empty)}发起倒计时:{msTime}毫秒";
}
19
Source : EnforceEditorSettings.cs
with MIT License
from anderm
with MIT License
from anderm
private static bool IsNewEditorSession ()
{
// Determine the last known launch date of the editor by loading it from the PlayerPrefs cache.
System.DateTime lastLaunchDate = System.DateTime.UtcNow;
System.DateTime.TryParse(EditorPrefs.GetString(_replacedemblyReloadTimestampKey), out lastLaunchDate);
// Determine the launch date for this editor session using the current time, and the time since startup.
System.DateTime thisLaunchDate = System.DateTime.UtcNow.AddSeconds(-EditorApplication.timeSinceStartup);
EditorPrefs.SetString(_replacedemblyReloadTimestampKey, thisLaunchDate.ToString());
// If the current session was launched later than the last known session start date, then this must be
// a new session, and we can display the first-time prompt.
return (thisLaunchDate - lastLaunchDate).Seconds > 0;
}
19
Source : TrainingService.cs
with MIT License
from andreluizsecco
with MIT License
from andreluizsecco
public async Task<TrainingDetails> TrainAndGetFinalStatusAsync(string appId, string appVersionId, int timeout = 60)
{
var response = await Post($"apps/{appId}/versions/{appVersionId}/train");
IEnumerable<Models.Training> trainingStatusList = null;
var maximumWaitTime = DateTime.Now.AddSeconds(timeout);
bool wait = true;
IEnumerable<TrainingStatus> statusList;
do
{
if (DateTime.Now > maximumWaitTime)
throw new Exception("Request timeout: LUIS application training is taking too long.");
response = await Get($"apps/{appId}/versions/{appVersionId}/train");
if (response != null)
trainingStatusList = JsonConvert.DeserializeObject<IReadOnlyCollection<Models.Training>>(response);
statusList = trainingStatusList.Select(x => (TrainingStatus)x.Details.StatusId);
wait = statusList.Any(x => (x == TrainingStatus.InProgress || x == TrainingStatus.Queued) && x != TrainingStatus.Fail);
if (wait)
Thread.Sleep(2000);
}
while (wait);
return trainingStatusList.First().Details;
}
19
Source : CookieCollection.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
private static CookieCollection parseResponse (string value)
{
var cookies = new CookieCollection ();
Cookie cookie = null;
var pairs = splitCookieHeaderValue (value);
for (var i = 0; i < pairs.Length; i++) {
var pair = pairs[i].Trim ();
if (pair.Length == 0)
continue;
if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Version = Int32.Parse (pair.GetValue ('=', true));
}
else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
var buff = new StringBuilder (pair.GetValue ('='), 32);
if (i < pairs.Length - 1)
buff.AppendFormat (", {0}", pairs[++i].Trim ());
DateTime expires;
if (!DateTime.TryParseExact (
buff.ToString (),
new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
CultureInfo.CreateSpecificCulture ("en-US"),
DateTimeStyles.AdjustToUniversal | DateTimeStyles.replacedumeUniversal,
out expires))
expires = DateTime.Now;
if (cookie != null && cookie.Expires == DateTime.MinValue)
cookie.Expires = expires.ToLocalTime ();
}
else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
var max = Int32.Parse (pair.GetValue ('=', true));
var expires = DateTime.Now.AddSeconds ((double) max);
if (cookie != null)
cookie.Expires = expires;
}
else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Path = pair.GetValue ('=');
}
else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Domain = pair.GetValue ('=');
}
else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
? "\"\""
: pair.GetValue ('=');
if (cookie != null)
cookie.Port = port;
}
else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Comment = urlDecode (pair.GetValue ('='), Encoding.UTF8);
}
else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.CommentUri = pair.GetValue ('=', true).ToUri ();
}
else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Discard = true;
}
else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.Secure = true;
}
else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
if (cookie != null)
cookie.HttpOnly = true;
}
else {
if (cookie != null)
cookies.Add (cookie);
string name;
string val = String.Empty;
var pos = pair.IndexOf ('=');
if (pos == -1) {
name = pair;
}
else if (pos == pair.Length - 1) {
name = pair.Substring (0, pos).TrimEnd (' ');
}
else {
name = pair.Substring (0, pos).TrimEnd (' ');
val = pair.Substring (pos + 1).TrimStart (' ');
}
cookie = new Cookie (name, val);
}
}
if (cookie != null)
cookies.Add (cookie);
return cookies;
}
19
Source : UnixEpoch.cs
with MIT License
from angusmillar
with MIT License
from angusmillar
public static DateTime UnixTimeStampToLocalDateTime(double unixTimeStamp)
{
// Unix time stamp is seconds past epoch
return Value.AddSeconds(unixTimeStamp).ToLocalTime();
}
19
Source : AnimeScraperService.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
public override async Task Work()
{
await base.Work();
try
{
foreach (string formatFilter in this._formatsFilter)
{
this._anilistQuery.Variables["format"] = formatFilter;
for (int currentPage = 1; currentPage <= this._totalPages; currentPage++)
{
this._anilistQuery.Variables["page"] = currentPage;
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(this._anilistQuery), Encoding.UTF8, "application/json")
};
try
{
using (var response = await this._anilistClient.SendAsync(request))
{
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
this._rateLimitReset = Convert.ToInt64(((string[])response.Headers.GetValues("X-RateLimit-Reset"))[0]);
}
throw new HttpRequestException("RateLimit superato", ex);
}
AnilistResponse anilistResponse = JsonConvert.DeserializeObject<AnilistResponse>(await response.Content.ReadreplacedtringAsync());
if (currentPage == 1)
{
this._totalPages = anilistResponse.Data.Page.PageInfo.LastPage;
}
foreach (AnilistResponse.ResponseMedia m in anilistResponse.Data.Page.Media)
{
Anime anime = new Anime(m);
if (this._animeCollection.Exists(ref anime))
{
this._animeCollection.Edit(ref anime);
}
else
{
this._animeCollection.Add(ref anime);
}
}
this._rateLimitRemaining = Convert.ToInt32(((string[])response.Headers.GetValues("X-RateLimit-Remaining"))[0]);
this.Log($"Format {formatFilter} done {GetProgress(currentPage, this._totalPages)}%", true);
}
}
catch (HttpRequestException ex)
{
currentPage--;
DateTime timeOfReset = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
timeOfReset = timeOfReset.AddSeconds(this._rateLimitReset).ToLocalTime();
TimeSpan timeToWait = timeOfReset - DateTime.Now;
this.Log($"Waiting {timeToWait.TotalMilliseconds.ToString("F0")} ms!", true);
Thread.Sleep((int)timeToWait.TotalMilliseconds + 1000);
}
if (_cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException("Process cancellation requested!");
}
}
}
}
catch(Exception ex)
{
throw;
}
}
19
Source : LoginController.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
[HttpGet]
[Route("RefreshToken")]
public async Task<MessageModel<TokenInfoViewModel>> RefreshToken(string token = "")
{
string jwtStr = string.Empty;
if (string.IsNullOrEmpty(token))
return Failed<TokenInfoViewModel>("token无效,请重新登录!");
var tokenModel = JwtHelper.SerializeJwt(token);
if (tokenModel != null && JwtHelper.customSafeVerify(token) && tokenModel.Uid > 0)
{
var user = await _sysUserInfoServices.QueryById(tokenModel.Uid);
if (user != null)
{
var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(user.uLoginName, user.uLoginPWD);
//如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, user.uLoginName),
new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//用户标识
var idenreplacedy = new ClaimsIdenreplacedy(JwtBearerDefaults.AuthenticationScheme);
idenreplacedy.AddClaims(claims);
var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
return Success(refreshToken, "获取成功");
}
}
return Failed<TokenInfoViewModel>("认证失败!");
}
19
Source : LoginController.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
[HttpGet]
[Route("JWTToken3.0")]
public async Task<MessageModel<TokenInfoViewModel>> GetJwtToken3(string name = "", string preplaced = "")
{
string jwtStr = string.Empty;
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(preplaced))
return Failed<TokenInfoViewModel>("用户名或密码不能为空");
preplaced = MD5Helper.MD5Encrypt32(preplaced);
var user = await _sysUserInfoServices.Query(d => d.uLoginName == name && d.uLoginPWD == preplaced && d.tdIsDelete == false);
if (user.Count > 0)
{
var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, preplaced);
//如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, name),
new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
// ids4和jwt切换
// jwt
if (!Permissions.IsUseIds4)
{
var data = await _roleModulePermissionServices.RoleModuleMaps();
var list = (from item in data
where item.IsDeleted == false
orderby item.Id
select new PermissionItem
{
Url = item.Module?.LinkUrl,
Role = item.Role?.Name.ObjToString(),
}).ToList();
_requirement.Permissions = list;
}
var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
return Success(token, "获取成功");
}
else
{
return Failed<TokenInfoViewModel>("认证失败");
}
}
19
Source : DateHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static DateTime StampToDateTime(string time)
{
time = time.Substring(0, 10);
double timestamp = Convert.ToInt64(time);
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(timestamp).ToLocalTime();
return dateTime;
}
19
Source : JwtHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static string IssueJwt(TokenModelJwt tokenModel)
{
string iss = Appsettings.app(new string[] { "Audience", "Issuer" });
string aud = Appsettings.app(new string[] { "Audience", "Audience" });
string secret = AppSecretConfig.Audience_Secret_String;
//var claims = new Claim[] //old
var claims = new List<Claim>
{
/*
* 特别重要:
1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法,或者在整个解决方案,搜索这个方法,看哪里使用了!
2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
*/
new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
//这个就是过期时间,目前是过期1000秒,可自定义,注意JWT有自己的缓冲过期时间
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()),
new Claim(JwtRegisteredClaimNames.Iss,iss),
new Claim(JwtRegisteredClaimNames.Aud,aud),
//new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
};
// 可以将一个用户的多个角色全部赋予;
// 作者:DX 提供技术支持;
claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwt = new JwtSecurityToken(
issuer: iss,
claims: claims,
signingCredentials: creds);
var jwtHandler = new JwtSecurityTokenHandler();
var encodedJwt = jwtHandler.WriteToken(jwt);
return encodedJwt;
}
19
Source : WeChatConfigServices.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public async Task<MessageModel<WeChatApiDto>> GetToken(string publicAccount)
{
var config = await this.QueryById(publicAccount);
if (config == null) MessageModel<string>.Success($"公众号{publicAccount}未维护至系统");//还没过期,直接返回
if (config.tokenExpiration > DateTime.Now)
{
//再次判断token在微信服务器是否正确
var wechatIP = await WeChatHelper.GetWechatIP(config.token);
if (wechatIP.errcode == 0)
MessageModel<WeChatApiDto>.Success("", new WeChatApiDto { access_token = config.token });//还没过期,直接返回
}
//过期了,重新获取
var data = await WeChatHelper.GetToken(config.appid, config.appsecret);
if (data.errcode.Equals(0))
{
config.token = data.access_token;
config.tokenExpiration = DateTime.Now.AddSeconds(data.expires_in);
await this.Update(config);
return MessageModel<WeChatApiDto>.Success("",data);
}
else
{
return MessageModel<WeChatApiDto>.Fail($"\r\n获取Token失败\r\n错误代码:{data.errcode}\r\n错误信息:{data.errmsg}");
}
}
19
Source : WeChatConfigServices.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public async Task<MessageModel<WeChatApiDto>> RefreshToken(string publicAccount)
{
var config = await this.QueryById(publicAccount);
if (config == null) MessageModel<string>.Success($"公众号{publicAccount}未维护至系统");//还没过期,直接返回
//过期了,重新获取
var data = await WeChatHelper.GetToken(config.appid, config.appsecret);
if (data.errcode.Equals(0))
{
config.token = data.access_token;
config.tokenExpiration = DateTime.Now.AddSeconds(data.expires_in);
await this.Update(config);
return MessageModel<WeChatApiDto>.Success("", data);
}
else
{
return MessageModel<WeChatApiDto>.Fail($"\r\n获取Token失败\r\n错误代码:{data.errcode}\r\n错误信息:{data.errmsg}");
}
}
19
Source : LoginController.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
[HttpGet]
[Route("JWTToken3.0")]
public async Task<object> GetJwtToken3(string name = "", string preplaced = "")
{
string jwtStr = string.Empty;
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(preplaced))
{
return new JsonResult(new
{
Status = false,
message = "用户名或密码不能为空"
});
}
preplaced = MD5Helper.MD5Encrypt32(preplaced);
var user = await _SysAdminRepository.Query(d => d.uLoginName == name && d.uLoginPWD == preplaced);
var teacher = await _iTeacherRepository.Query(d => d.Account == name && d.Preplacedword == preplaced);
var data = await _roleModulePermissionRepository.RoleModuleMaps();
var list = new List<PermissionItem>();
{
list = (from item in data
where item.IsDeleted == false
orderby item.Id
select new PermissionItem
{
Url = item.Module?.LinkUrl,
Role = item.Role?.Name.ObjToString(),
}).ToList();
}
_requirement.Permissions = list;
if (user.Count > 0)
{
var userRoles = await _SysAdminRepository.GetUserRoleNameStr(name, preplaced);
//如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, name),
new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()),
new Claim("GID", "-9999"),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//用户标识
var idenreplacedy = new ClaimsIdenreplacedy(JwtBearerDefaults.AuthenticationScheme);
idenreplacedy.AddClaims(claims);
var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
return new JsonResult(token);
} else if (teacher.Count>0) {
var userRoles = "Teacher_Role";//单独手写教师权限
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, name),
new Claim(JwtRegisteredClaimNames.Jti, teacher.FirstOrDefault().Id.ToString()),
new Claim("GID", teacher.FirstOrDefault().gradeId.ToString()),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//用户标识
var idenreplacedy = new ClaimsIdenreplacedy(JwtBearerDefaults.AuthenticationScheme);
idenreplacedy.AddClaims(claims);
var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
return new JsonResult(token);
}
else
{
return new JsonResult(new
{
success = false,
message = "认证失败"
});
}
}
19
Source : LoginController.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
[HttpGet]
[Route("RefreshToken")]
public async Task<object> RefreshToken(string token = "")
{
string jwtStr = string.Empty;
if (string.IsNullOrEmpty(token))
{
return new JsonResult(new
{
Status = false,
message = "token无效,请重新登录!"
});
}
var tokenModel = JwtToken.SerializeJwt(token);
if (tokenModel != null && tokenModel.Uid > 0)
{
var user = await _SysAdminRepository.QueryById(tokenModel.Uid);
if (user != null)
{
var userRoles = await _SysAdminRepository.GetUserRoleNameStr(user.uLoginName, user.uLoginPWD);
//如果是基于用户的授权策略,这里要添加用户;如果是基于角色的授权策略,这里要添加角色
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, user.uLoginName),
new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ObjToString()),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
//用户标识
var idenreplacedy = new ClaimsIdenreplacedy(JwtBearerDefaults.AuthenticationScheme);
idenreplacedy.AddClaims(claims);
var refreshToken = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
return new JsonResult(refreshToken);
}
}
return new JsonResult(new
{
success = false,
message = "认证失败"
});
}
19
Source : TimelineImageNoticeModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void StartNotice()
{
TimelineVisualNoticeModel.EnqueueToHide(
this,
(sender, model) =>
{
var result = false;
var notice = model as TimelineImageNoticeModel;
lock (notice)
{
var delay = notice.Delay.HasValue ?
notice.Delay.Value :
0;
if (DateTime.Now >= notice.TimeToHide.AddSeconds(delay + 0.1d) ||
notice.toHide)
{
if (notice.overlay != null)
{
if (notice.overlay.OverlayVisible)
{
notice.RemoveSyncToHide();
TimelineVisualNoticeModel.DequeueToHide(sender);
}
notice.overlay.OverlayVisible = false;
}
notice.toHide = false;
}
}
return result;
});
this.overlay?.ShowNotice();
}
19
Source : TimelineExpressionsModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void Set(
Match matched)
{
var sets = this.SetStatements
.Where(x =>
x.Enabled.GetValueOrDefault() &&
!string.IsNullOrEmpty(x.Name));
var tables = this.TableStatements
.Where(x =>
x.Enabled.GetValueOrDefault());
if (!sets.Any() &&
!tables.Any())
{
return;
}
var isVaribleChanged = false;
foreach (var set in sets)
{
var expretion = DateTime.MaxValue;
if (set.TTL > 0)
{
expretion = DateTime.Now.AddSeconds(set.TTL.GetValueOrDefault());
}
var variable = default(TimelineVariable);
if (Variables.ContainsKey(set.Name))
{
variable = Variables[set.Name];
}
else
{
variable = new TimelineVariable(set.Name);
Variables[set.Name] = variable;
}
variable.Zone = set.Scope switch
{
TimelineExpressionsSetModel.Scopes.CurrentZone => TimelineController.CurrentController?.CurrentZoneName ?? string.Empty,
TimelineExpressionsSetModel.Scopes.Global => TimelineModel.GlobalZone,
_ => string.Empty
};
// トグル?
if (set.IsToggle.GetValueOrDefault())
{
var current = false;
if (DateTime.Now <= variable.Expiration &&
variable.Value is bool b)
{
current = b;
}
variable.Value = !current;
}
else
{
var newValue = ObjectComparer.ConvertToValue(set.Value, matched);
if (!ObjectComparer.Equals(variable.Value, newValue))
{
variable.Value = newValue;
isVaribleChanged = true;
}
}
// カウンタを更新する
if (!string.IsNullOrEmpty(set.Count))
{
variable.Counter = set.ExecuteCount(variable.Counter);
isVaribleChanged = true;
}
// 有効期限を設定する
variable.Expiration = expretion;
if (isVaribleChanged)
{
// フラグの状況を把握するためにログを出力する
TimelineController.RaiseLog(
string.IsNullOrEmpty(set.Count) ?
$"{TimelineConstants.LogSymbol} set VAR['{set.Name}'] = {variable.Value}" :
$"{TimelineConstants.LogSymbol} set VAR['{set.Name}'] = {variable.Counter}");
if (ReferedTriggerRecompileDelegates.ContainsKey(set.Name))
{
lock (variable)
{
ReferedTriggerRecompileDelegates[set.Name]?.Invoke();
}
}
}
}
19
Source : SpellsController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void MatchCore(
Models.Spell spell,
string logLine)
{
var regex = spell.Regex;
var notifyNeeded = false;
if (!spell.IsInstance)
{
// マッチング計測開始
spell.StartMatching();
// 開始条件を確認する
if (ConditionUtility.CheckConditionsForSpell(spell))
{
// 正規表現が無効?
if (!spell.RegexEnabled ||
regex == null)
{
var keyword = spell.KeywordReplaced;
if (string.IsNullOrWhiteSpace(keyword))
{
return;
}
// キーワードが含まれるか?
if (logLine.Contains(keyword, StringComparison.OrdinalIgnoreCase))
{
var targetSpell = spell;
// ヒットしたログを格納する
targetSpell.MatchedLog = logLine;
// スペル名(表示テキスト)を置換する
var replacedreplacedle = ConditionUtility.GetReplacedreplacedle(targetSpell);
// PC名を置換する
replacedreplacedle = XIVPluginHelper.Instance.ReplacePartyMemberName(
replacedreplacedle,
Settings.Default.PCNameInitialOnDisplayStyle);
targetSpell.SpellreplacedleReplaced = replacedreplacedle;
targetSpell.UpdateDone = false;
targetSpell.OverDone = false;
targetSpell.BeforeDone = false;
targetSpell.TimeupDone = false;
var now = DateTime.Now;
// ホットバーからリキャスト時間の読込みを試みる
if (!this.TryGetHotbarRecast(targetSpell, out double d))
{
d = targetSpell.RecastTime;
}
targetSpell.CompleteScheduledTime = now.AddSeconds(d);
targetSpell.MatchDateTime = now;
// マッチング計測終了
spell.EndMatching();
// マッチ時点のサウンドを再生する
targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);
targetSpell.Play(targetSpell.MatchTextToSpeak, targetSpell.MatchAdvancedConfig);
notifyNeeded = true;
// 遅延サウンドタイマを開始する
targetSpell.StartOverSoundTimer();
targetSpell.StartBeforeSoundTimer();
targetSpell.StartTimeupSoundTimer();
}
}
else
{
// 正規表現でマッチングする
var match = regex.Match(logLine);
if (match.Success)
{
#if DEBUG
if (logLine.Contains("MARK"))
{
Debug.WriteLine("MARK");
}
#endif
var targetSpell = default(Spell);
void setreplacedle()
{
targetSpell = spell;
// ヒットしたログを格納する
targetSpell.MatchedLog = logLine;
// スペル名(表示テキスト)を置換する
var replacedreplacedle = match.Result(ConditionUtility.GetReplacedreplacedle(targetSpell));
// PC名を置換する
replacedreplacedle = XIVPluginHelper.Instance.ReplacePartyMemberName(
replacedreplacedle,
Settings.Default.PCNameInitialOnDisplayStyle);
// インスタンス化する?
if (targetSpell.ToInstance)
{
// 同じタイトルのインスタンススペルを探す
// 存在すればそれを使用して、なければ新しいインスタンスを生成する
targetSpell = SpellTable.Instance.GetOrAddInstance(
replacedreplacedle,
targetSpell);
}
else
{
targetSpell.SpellreplacedleReplaced = replacedreplacedle;
}
}
// スペルタイトルを編集する
setreplacedle();
targetSpell.UpdateDone = false;
targetSpell.OverDone = false;
targetSpell.BeforeDone = false;
targetSpell.TimeupDone = false;
var now = DateTime.Now;
// 効果時間を決定する
// グループ "duration" をキャプチャーしていた場合は効果時間を置換する
// 最大値9999を超えていた場合は無視する
var duration = targetSpell.RecastTime;
if (RegexExtensions.TryGetDuration(match, out double d))
{
duration = d;
}
else
{
// ホットバーからリキャスト時間の読込みを試みる
if (this.TryGetHotbarRecast(targetSpell, out double durationFromHotbar))
{
duration = durationFromHotbar;
}
}
targetSpell.CompleteScheduledTime = now.AddSeconds(duration);
// スペル対象を保存する
// グループ "target" をキャプチャーしていた場合はその文字列を保存する
var targetName = match.Groups["target"].Value;
if (!string.IsNullOrWhiteSpace(targetName))
{
targetSpell.TargetName = targetName;
}
// マッチ日時を格納する
targetSpell.MatchDateTime = now;
// マッチング計測終了
spell.EndMatching();
// マッチ時点のサウンドを再生する
targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);
if (!string.IsNullOrWhiteSpace(targetSpell.MatchTextToSpeak))
{
var tts = match.Result(targetSpell.MatchTextToSpeak);
targetSpell.Play(tts, targetSpell.MatchAdvancedConfig);
}
notifyNeeded = true;
// 遅延サウンドタイマを開始する
targetSpell.StartOverSoundTimer();
targetSpell.StartBeforeSoundTimer();
targetSpell.StartTimeupSoundTimer();
}
}
}
}
// 延長をマッチングする
if (spell.MatchDateTime > DateTime.MinValue)
{
var keywords = new string[] { spell.KeywordForExtendReplaced1, spell.KeywordForExtendReplaced2, spell.KeywordForExtendReplaced3 };
var regexes = new Regex[] { spell.RegexForExtend1, spell.RegexForExtend2, spell.RegexForExtend3 };
var timeToExtends = new double[] { spell.RecastTimeExtending1, spell.RecastTimeExtending2, spell.RecastTimeExtending3 };
for (int i = 0; i < keywords.Length; i++)
{
var keywordToExtend = keywords[i];
var regexToExtend = regexes[i];
var timeToExtend = timeToExtends[i];
// マッチングする
var exntended = false;
if (!spell.RegexEnabled ||
regexToExtend == null)
{
if (!string.IsNullOrWhiteSpace(keywordToExtend))
{
exntended = logLine.Contains(keywordToExtend, StringComparison.OrdinalIgnoreCase);
}
}
else
{
var match = regexToExtend.Match(logLine);
exntended = match.Success;
if (exntended)
{
// targetをキャプチャーしている?
if (!string.IsNullOrWhiteSpace(spell.TargetName))
{
var targetName = match.Groups["target"].Value;
if (!string.IsNullOrWhiteSpace(targetName))
{
// targetが当初のマッチングと一致するか確認する
if (spell.TargetName != targetName)
{
exntended = false;
}
}
}
}
}
if (!exntended)
{
continue;
}
var now = DateTime.Now;
// リキャストタイムを延長する
var newSchedule = spell.CompleteScheduledTime.AddSeconds(timeToExtend);
spell.BeforeDone = false;
spell.UpdateDone = false;
if (spell.ExtendBeyondOriginalRecastTime)
{
if (spell.UpperLimitOfExtension > 0)
{
var newDuration = (newSchedule - now).TotalSeconds;
if (newDuration > (double)spell.UpperLimitOfExtension)
{
newSchedule = newSchedule.AddSeconds(
(newDuration - (double)spell.UpperLimitOfExtension) * -1);
}
}
}
else
{
var newDuration = (newSchedule - now).TotalSeconds;
if (newDuration > (double)spell.RecastTime)
{
newSchedule = newSchedule.AddSeconds(
(newDuration - (double)spell.RecastTime) * -1);
}
}
spell.CompleteScheduledTime = newSchedule;
if (!spell.IsNotResetBarOnExtended)
{
spell.MatchDateTime = now;
}
notifyNeeded = true;
// 遅延サウンドタイマを開始(更新)する
spell.StartOverSoundTimer();
spell.StartBeforeSoundTimer();
spell.StartTimeupSoundTimer();
}
}
// end if 延長マッチング
// ACT標準のSpellTimerに変更を通知する
if (notifyNeeded)
{
this.UpdateNormalSpellTimer(spell, false);
this.NotifyNormalSpellTimer(spell);
}
}
19
Source : TimelineTesterView.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private async void TimelineTesterView_Loaded(
object sender,
RoutedEventArgs e)
{
if (!File.Exists(this.LogFile))
{
return;
}
var list = new List<TestLog>();
await Task.Run(() =>
{
var seq = 1L;
using (var sr = new StreamReader(this.LogFile, new UTF8Encoding(false)))
{
while (!sr.EndOfStream)
{
var logline = sr.ReadLine();
if (string.IsNullOrEmpty(logline) ||
logline.StartsWith("#") ||
logline.StartsWith("//"))
{
continue;
}
var log = new TestLog(logline)
{
Seq = seq++
};
list.Add(log);
}
}
if (!list.Any())
{
return;
}
// 頭出しをする
var combatStart = list.FirstOrDefault(x => x.Log.Contains("戦闘開始"));
if (combatStart != null)
{
list.RemoveRange(0, list.IndexOf(combatStart));
}
else
{
// ダミー戦闘開始5秒前を挿入する
var head = list.First();
list.Insert(0, new TestLog(
$"[{head.Timestamp.AddSeconds(-5):HH:mm:ss.fff}] 00:0039:戦闘開始まで5秒! [DUMMY]"));
// xivlog flush を挿入する
var last = list.Last();
list.Add(new TestLog(
$"[{last.Timestamp.AddSeconds(1):HH:mm:ss.fff}] /xivlog flush"));
}
var first = list.First();
foreach (var log in list)
{
if (log.Timestamp >= first.Timestamp)
{
log.Time = log.Timestamp - first.Timestamp;
}
else
{
log.Time = log.Timestamp.AddDays(1) - first.Timestamp;
}
}
});
this.Logs.Clear();
this.Logs.AddRange(list);
}
19
Source : TimelineVisualNoticeModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void StartNotice(
Action<TimelineVisualNoticeModel> removeCallback,
bool isDummyMode = false)
{
this.IsVisible = true;
this.RefreshDuration();
EnqueueToHide(
this,
(sender, model) =>
{
var result = false;
var notice = model as TimelineVisualNoticeModel;
notice.RefreshDuration();
var delay = notice.Delay.HasValue ?
notice.Delay.Value :
0;
if (DateTime.Now >= notice.TimeToHide.AddSeconds(delay + 1.0d) ||
notice.toHide)
{
if (!sender.IsDummyMode)
{
if (notice.IsVisible)
{
notice.RemoveSyncToHide();
DequeueToHide(sender);
}
notice.toHide = false;
notice.IsVisible = false;
removeCallback?.Invoke(notice);
}
result = true;
}
return result;
},
isDummyMode);
}
19
Source : SpellsController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void MatchCore(
Models.Spell spell,
string logLine)
{
var regex = spell.Regex;
var notifyNeeded = false;
if (!spell.IsInstance)
{
// マッチング計測開始
spell.StartMatching();
// 開始条件を確認する
if (ConditionUtility.CheckConditionsForSpell(spell))
{
// 正規表現が無効?
if (!spell.RegexEnabled ||
regex == null)
{
var keyword = spell.KeywordReplaced;
if (string.IsNullOrWhiteSpace(keyword))
{
return;
}
// キーワードが含まれるか?
if (logLine.Contains(keyword, StringComparison.OrdinalIgnoreCase))
{
var targetSpell = spell;
// ヒットしたログを格納する
targetSpell.MatchedLog = logLine;
// スペル名(表示テキスト)を置換する
var replacedreplacedle = ConditionUtility.GetReplacedreplacedle(targetSpell);
// PC名を置換する
replacedreplacedle = XIVPluginHelper.Instance.ReplacePartyMemberName(
replacedreplacedle,
Settings.Default.PCNameInitialOnDisplayStyle);
targetSpell.SpellreplacedleReplaced = replacedreplacedle;
targetSpell.UpdateDone = false;
targetSpell.OverDone = false;
targetSpell.BeforeDone = false;
targetSpell.TimeupDone = false;
var now = DateTime.Now;
// ホットバーからリキャスト時間の読込みを試みる
if (!this.TryGetHotbarRecast(targetSpell, out double d))
{
d = targetSpell.RecastTime;
}
targetSpell.CompleteScheduledTime = now.AddSeconds(d);
targetSpell.MatchDateTime = now;
// マッチング計測終了
spell.EndMatching();
// マッチ時点のサウンドを再生する
targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);
targetSpell.Play(targetSpell.MatchTextToSpeak, targetSpell.MatchAdvancedConfig);
notifyNeeded = true;
// 遅延サウンドタイマを開始する
targetSpell.StartOverSoundTimer();
targetSpell.StartBeforeSoundTimer();
targetSpell.StartTimeupSoundTimer();
}
}
else
{
// 正規表現でマッチングする
var match = regex.Match(logLine);
if (match.Success)
{
#if DEBUG
if (logLine.Contains("MARK"))
{
Debug.WriteLine("MARK");
}
#endif
var targetSpell = default(Spell);
void setreplacedle()
{
targetSpell = spell;
// ヒットしたログを格納する
targetSpell.MatchedLog = logLine;
// スペル名(表示テキスト)を置換する
var replacedreplacedle = match.Result(ConditionUtility.GetReplacedreplacedle(targetSpell));
// PC名を置換する
replacedreplacedle = XIVPluginHelper.Instance.ReplacePartyMemberName(
replacedreplacedle,
Settings.Default.PCNameInitialOnDisplayStyle);
// インスタンス化する?
if (targetSpell.ToInstance)
{
// 同じタイトルのインスタンススペルを探す
// 存在すればそれを使用して、なければ新しいインスタンスを生成する
targetSpell = SpellTable.Instance.GetOrAddInstance(
replacedreplacedle,
targetSpell);
}
else
{
targetSpell.SpellreplacedleReplaced = replacedreplacedle;
}
}
// スペルタイトルを編集する
setreplacedle();
targetSpell.UpdateDone = false;
targetSpell.OverDone = false;
targetSpell.BeforeDone = false;
targetSpell.TimeupDone = false;
var now = DateTime.Now;
// 効果時間を決定する
// グループ "duration" をキャプチャーしていた場合は効果時間を置換する
// 最大値9999を超えていた場合は無視する
var duration = targetSpell.RecastTime;
if (RegexExtensions.TryGetDuration(match, out double d))
{
duration = d;
}
else
{
// ホットバーからリキャスト時間の読込みを試みる
if (this.TryGetHotbarRecast(targetSpell, out double durationFromHotbar))
{
duration = durationFromHotbar;
}
}
targetSpell.CompleteScheduledTime = now.AddSeconds(duration);
// スペル対象を保存する
// グループ "target" をキャプチャーしていた場合はその文字列を保存する
var targetName = match.Groups["target"].Value;
if (!string.IsNullOrWhiteSpace(targetName))
{
targetSpell.TargetName = targetName;
}
// マッチ日時を格納する
targetSpell.MatchDateTime = now;
// マッチング計測終了
spell.EndMatching();
// マッチ時点のサウンドを再生する
targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);
if (!string.IsNullOrWhiteSpace(targetSpell.MatchTextToSpeak))
{
var tts = match.Result(targetSpell.MatchTextToSpeak);
targetSpell.Play(tts, targetSpell.MatchAdvancedConfig);
}
notifyNeeded = true;
// 遅延サウンドタイマを開始する
targetSpell.StartOverSoundTimer();
targetSpell.StartBeforeSoundTimer();
targetSpell.StartTimeupSoundTimer();
}
}
}
}
// 延長をマッチングする
if (spell.MatchDateTime > DateTime.MinValue)
{
var keywords = new string[] { spell.KeywordForExtendReplaced1, spell.KeywordForExtendReplaced2, spell.KeywordForExtendReplaced3 };
var regexes = new Regex[] { spell.RegexForExtend1, spell.RegexForExtend2, spell.RegexForExtend3 };
var timeToExtends = new double[] { spell.RecastTimeExtending1, spell.RecastTimeExtending2, spell.RecastTimeExtending3 };
for (int i = 0; i < keywords.Length; i++)
{
var keywordToExtend = keywords[i];
var regexToExtend = regexes[i];
var timeToExtend = timeToExtends[i];
// マッチングする
var exntended = false;
if (!spell.RegexEnabled ||
regexToExtend == null)
{
if (!string.IsNullOrWhiteSpace(keywordToExtend))
{
exntended = logLine.Contains(keywordToExtend, StringComparison.OrdinalIgnoreCase);
}
}
else
{
var match = regexToExtend.Match(logLine);
exntended = match.Success;
if (exntended)
{
// targetをキャプチャーしている?
if (!string.IsNullOrWhiteSpace(spell.TargetName))
{
var targetName = match.Groups["target"].Value;
if (!string.IsNullOrWhiteSpace(targetName))
{
// targetが当初のマッチングと一致するか確認する
if (spell.TargetName != targetName)
{
exntended = false;
}
}
}
}
}
if (!exntended)
{
continue;
}
var now = DateTime.Now;
// リキャストタイムを延長する
var newSchedule = spell.CompleteScheduledTime.AddSeconds(timeToExtend);
spell.BeforeDone = false;
spell.UpdateDone = false;
if (spell.ExtendBeyondOriginalRecastTime)
{
if (spell.UpperLimitOfExtension > 0)
{
var newDuration = (newSchedule - now).TotalSeconds;
if (newDuration > (double)spell.UpperLimitOfExtension)
{
newSchedule = newSchedule.AddSeconds(
(newDuration - (double)spell.UpperLimitOfExtension) * -1);
}
}
}
else
{
var newDuration = (newSchedule - now).TotalSeconds;
if (newDuration > (double)spell.RecastTime)
{
newSchedule = newSchedule.AddSeconds(
(newDuration - (double)spell.RecastTime) * -1);
}
}
spell.CompleteScheduledTime = newSchedule;
if (!spell.IsNotResetBarOnExtended)
{
spell.MatchDateTime = now;
}
notifyNeeded = true;
// 遅延サウンドタイマを開始(更新)する
spell.StartOverSoundTimer();
spell.StartBeforeSoundTimer();
spell.StartTimeupSoundTimer();
}
}
// end if 延長マッチング
// ACT標準のSpellTimerに変更を通知する
if (notifyNeeded)
{
this.UpdateNormalSpellTimer(spell, false);
this.NotifyNormalSpellTimer(spell);
}
}
19
Source : SpellsController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public bool UpdateHotbarRecast(
Spell spell)
{
var result = false;
if (!spell.UseHotbarRecastTime ||
string.IsNullOrEmpty(spell.HotbarName))
{
return result;
}
var now = DateTime.Now;
if ((now - spell.MatchDateTime).TotalSeconds <= 0.1)
{
return result;
}
if (spell.CompleteScheduledTime.AddMilliseconds(HotbarAdjustThreshold * 2) >= now)
{
if (!this.TryGetHotbarRecast(spell, out double d))
{
return result;
}
var newSchedule = now.AddSeconds(d);
// ホットバー情報とnミリ秒以上乖離したら補正する
var gap = Math.Abs((newSchedule - spell.CompleteScheduledTime).TotalMilliseconds);
if (d > 1.0 &&
gap >= HotbarAdjustThreshold)
{
result = true;
if (spell.CompleteScheduledTime.AddSeconds(-1) <= now)
{
spell.MatchDateTime = now;
spell.OverDone = false;
spell.TimeupDone = false;
}
spell.CompleteScheduledTime = newSchedule;
spell.BeforeDone = false;
spell.UpdateDone = false;
spell.StartOverSoundTimer();
spell.StartBeforeSoundTimer();
spell.StartTimeupSoundTimer();
}
}
return result;
}
19
Source : Ticker.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void StartDelayedSoundTimer()
{
if (this.delayedSoundTask != null)
{
this.delayedSoundTask.IsCancel = true;
}
if (this.Delay <= 0 ||
this.MatchDateTime <= DateTime.MinValue)
{
return;
}
if (string.IsNullOrWhiteSpace(this.DelaySound) &&
string.IsNullOrWhiteSpace(this.DelayTextToSpeak))
{
return;
}
var timeToPlay = this.MatchDateTime.AddSeconds(this.Delay);
var duration = (timeToPlay - DateTime.Now).TotalMilliseconds;
if (duration > 0d)
{
this.delayedSoundTask = DelayableTask.Run(
this.PlayDelayedSound,
TimeSpan.FromMilliseconds(duration));
}
}
19
Source : TickerModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void Sync(
string logline,
string syncTarget)
{
if (logline.Length < 14)
{
return;
}
var text = logline.Substring(0, 14)
.Replace("[", string.Empty)
.Replace("]", string.Empty);
if (!DateTime.TryParse(text, out DateTime timestamp))
{
return;
}
var nextTick = timestamp.AddSeconds(TickerGlobalInterval);
if (nextTick <= DateTime.Now)
{
return;
}
this.lastSyncTimestamp = DateTime.Now;
Task.Run(() =>
{
Thread.Sleep(nextTick - DateTime.Now);
this.RestartTickerCallback?.Invoke();
this.AppLogger.Trace($"3s ticker synced to {syncTarget}.");
});
}
19
Source : VideoCapture.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void FinishRecording()
{
this.StopRecordingSubscriber?.Stop();
lock (this)
{
if (!Config.Instance.IsRecording)
{
return;
}
}
if (!Config.Instance.IsEnabledRecording)
{
return;
}
if (!Config.Instance.UseObsRpc)
{
this.Input.Keyboard.ModifiedKeyStroke(
Config.Instance.StopRecordingShortcut.GetModifiers(),
Config.Instance.StopRecordingShortcut.GetKeys());
}
else
{
this.SendToggleRecording();
}
var contentName = !string.IsNullOrEmpty(this.contentName) ?
this.contentName :
ActGlobals.oFormActMain.CurrentZone;
if (!string.IsNullOrEmpty(Config.Instance.VideoSaveDictory) &&
Directory.Exists(Config.Instance.VideoSaveDictory))
{
Task.Run(async () =>
{
var now = DateTime.Now;
var prefix = Config.Instance.VideFilePrefix.Trim();
prefix = string.IsNullOrEmpty(prefix) ?
string.Empty :
$"{prefix} ";
var deathCountText = this.deathCount > 1 ?
$" death{this.deathCount - 1}" :
string.Empty;
var f = $"{prefix}{this.startTime:yyyy-MM-dd HH-mm} {contentName} try{this.TryCount:00} {VideoDurationPlaceholder}{deathCountText}.ext";
await Task.Delay(TimeSpan.FromSeconds(8));
var files = Directory.GetFiles(
Config.Instance.VideoSaveDictory,
"*.*");
var original = files
.OrderByDescending(x => File.GetLastWriteTime(x))
.FirstOrDefault();
if (!string.IsNullOrEmpty(original))
{
var timestamp = File.GetLastWriteTime(original);
if (timestamp >= now.AddSeconds(-10))
{
var ext = Path.GetExtension(original);
f = f.Replace(".ext", ext);
var dest = Path.Combine(
Path.GetDirectoryName(original),
f);
using (var tf = TagLib.File.Create(original))
{
dest = dest.Replace(
VideoDurationPlaceholder,
$"{tf.Properties.Duration.TotalSeconds:N0}s");
tf.Tag.replacedle = Path.GetFileNameWithoutExtension(dest);
tf.Tag.Subreplacedle = $"{prefix} - {contentName}";
tf.Tag.Album = $"FFXIV - {contentName}";
tf.Tag.AlbumArtists = new[] { "FFXIV", this.playerName }.Where(x => !string.IsNullOrEmpty(x)).ToArray();
tf.Tag.Genres = new[] { "Game" };
tf.Tag.Comment =
$"{prefix} - {contentName}\n" +
$"{this.startTime:yyyy-MM-dd HH:mm} try{this.TryCount}{deathCountText}";
tf.Save();
}
File.Move(
original,
dest);
XIVLogPlugin.Instance.EnqueueLogLine(
"00",
$"[XIVLog] The video was saved. {Path.GetFileName(dest)}");
}
}
});
}
WPFHelper.InvokeAsync(() =>
{
lock (this)
{
Config.Instance.IsRecording = false;
}
});
}
19
Source : EnmityInfoWorker.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private bool RefreshEPS()
{
if (this.DiffSampleTimer.Elapsed.TotalSeconds < 3.0)
{
return false;
}
this.DiffSampleTimer.Restart();
var me = this.CurrentEnmityModelList.FirstOrDefault(x => x.IsMe);
var sample = (
from x in this.CurrentEnmityModelList
where
x.JobID == JobIDs.PLD ||
x.JobID == JobIDs.WAR ||
x.JobID == JobIDs.DRK
orderby
Math.Abs(x.Enmity - (me?.Enmity ?? 0)) ascending
select
x).FirstOrDefault();
if (sample == null)
{
this.currentTankEPS = 0;
this.currentNearThreshold = 0;
return true;
}
var last = this.DiffEnmityList.LastOrDefault();
var diff = Math.Abs(sample.Enmity - (last?.Value ?? 0));
var now = DateTime.Now;
this.DiffEnmityList.Add(new DiffEnmity()
{
Timestamp = now,
SampleName = sample.Name,
Value = sample.Enmity,
Diff = diff,
});
var olds = this.DiffEnmityList
.Where(x => x.Timestamp < now.AddSeconds(-30))
.ToArray();
foreach (var item in olds)
{
this.DiffEnmityList.Remove(item);
}
var parameters = this.DiffEnmityList
.Where(x =>
this.currentTankEPS <= 0 ||
x.Diff <= (this.currentTankEPS * 10.0));
// EPSと危険域閾値を算出する
this.currentTankEPS = parameters.Any() ?
parameters.Average(x => x.Diff) :
0;
this.currentNearThreshold = this.currentTankEPS * Settings.Instance.Enmity.NearThresholdRate;
return true;
}
19
Source : ActionEchoesModel.cs
with MIT License
from anoyetta-academy
with MIT License
from anoyetta-academy
private static ActionEchoesModel CreateDesignModeDataModel()
{
var model = new ActionEchoesModel();
var now = DateTime.Now;
model.PlayerName = "Anoyetta Anon";
model.PlayerJob = "SCH";
model.EncDPS = 3567;
model.Duration = TimeSpan.FromMinutes(10);
model.Time = now;
model.IsActive = true;
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 5),
Actor = model.PlayerName,
ID = 168,
Name = "ミアズマ",
Category = ActionCategory.Spell,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 4.01),
Actor = model.PlayerName,
ID = 178,
Name = "バイオラ",
Category = ActionCategory.Spell,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 4),
Actor = model.PlayerName,
ID = 9618,
Name = "エナジードレイン",
Category = ActionCategory.Ability,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 3.01),
Actor = model.PlayerName,
ID = 179,
Name = "シャドウフレア",
Category = ActionCategory.Ability,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 3),
Actor = model.PlayerName,
ID = 7436,
Name = "連環計",
Category = ActionCategory.Ability,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 2.01),
Actor = model.PlayerName,
ID = 177,
Name = "ミアズラ",
Category = ActionCategory.Spell,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 2),
Actor = model.PlayerName,
ID = 9618,
Name = "エナジードレイン",
Category = ActionCategory.Ability,
RecastTime = 2.5f,
});
model.Add(new ActionEcreplaceddel()
{
Timestamp = now.AddSeconds(-2.5 * 1),
Actor = model.PlayerName,
ID = 7435,
Name = "魔炎法",
Category = ActionCategory.Spell,
RecastTime = 2.5f,
});
return model;
}
19
Source : DockerSqlDatabaseUtilities.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static async Task WaitUntilDatabaseAvailableAsync(string databasePort)
{
var end = DateTime.UtcNow.AddSeconds(60);
var connectionEstablised = false;
while (!connectionEstablised && end > DateTime.UtcNow)
{
try
{
var sqlConnectionString = $"Data Source=localhost,{databasePort};Integrated Security=False;User ID=SA;Preplacedword={SQLSERVER_SA_PreplacedWORD}";
using var sqlConnection = new SqlConnection(sqlConnectionString);
await sqlConnection.OpenAsync();
connectionEstablised = true;
}
catch
{
// If opening the SQL connection fails, SQL Server is not ready yet
await Task.Delay(500);
}
}
if (!connectionEstablised)
{
throw new Exception("Connection to the SQL docker database could not be established within 60 seconds.");
}
return;
}
19
Source : SqlServerContainer.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private async Task WaitUntilDatabaseAvailableAsync(int databasePort)
{
var end = DateTime.UtcNow.AddSeconds(60);
var connectionEstablised = false;
while (!connectionEstablised && end > DateTime.UtcNow)
{
try
{
var sqlConnectionString = $"Data Source=localhost,{databasePort};Integrated Security=False;User ID=SA;Preplacedword={_preplacedword}";
using var sqlConnection = new SqlConnection(sqlConnectionString);
await sqlConnection.OpenAsync();
connectionEstablised = true;
}
catch
{
// If opening the SQL connection fails, SQL Server is not ready yet
await Task.Delay(500);
}
}
if (!connectionEstablised)
{
throw new Exception("Connection to the SQL docker database could not be established within 60 seconds.");
}
return;
}
19
Source : ChatOverlayViewModel.cs
with MIT License
from anoyetta
with MIT License
from anoyetta
public void ExtendTimeToHide()
{
lock (this)
{
this.lastLogAddedTimestamp = DateTime.Now.AddSeconds(
this.ChatOverlaySettings.TimeToHide / 2d);
}
}
19
Source : TimeGatedMessageCache.cs
with Apache License 2.0
from anthturner
with Apache License 2.0
from anthturner
internal bool IsExpired(int expirySeconds)
{
return Cached.AddSeconds(expirySeconds) < DateTime.Now;
}
19
Source : CountdownControl.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Start(int secsElapsed)
{
_start = GetNowUtc().AddSeconds(-secsElapsed);
_timer!.Start();
}
19
Source : DBAReadLog.cs
with MIT License
from ap0405140
with MIT License
from ap0405140
[Microsoft.SqlServer.Server.SqlFunction
(DataAccess = DataAccessKind.Read,
FillRowMethodName = "DBAReadLog_FillRow",
TableDefinition = "LSN nvarchar(max),Type nvarchar(max),TransactionID nvarchar(max),BeginTime nvarchar(max),EndTime nvarchar(max),ObjectName nvarchar(max),Operation nvarchar(max),RedoSQL nvarchar(max),UndoSQL nvarchar(max),Message nvarchar(max)")]
public static IEnumerable DBAReadLog(string pconnectionstring,
string pbegintime,
string pendtime,
string pobjectname)
{
DatabaseLog[] r;
DatabaseLogreplacedyzer xc;
if (string.IsNullOrEmpty(pbegintime))
{
pbegintime = DateTime.Now.AddSeconds(-5).ToString("yyyy-MM-dd HH:mm:ss");
}
if (string.IsNullOrEmpty(pendtime))
{
pendtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
xc = new DatabaseLogreplacedyzer(pconnectionstring);
r = xc.ReadLog(pbegintime, pendtime, pobjectname);
return r;
}
19
Source : Form1.cs
with MIT License
from ap0405140
with MIT License
from ap0405140
private void Form1_Load(object sender, EventArgs e)
{
config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
//Connection String: Please change below connection string for your environment.
txtConnectionstring.Text = config.AppSettings.Settings["DefaultConnectionString"].Value;
//Time Range: Default to read at last 10 seconds 's logs, you can change the time range for need.
dtStarttime.Value = Convert.ToDateTime(DateTime.Now.AddSeconds(-10).ToString("yyyy/MM/dd HH:mm:ss"));
dtEndtime.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
//Table Name: Need include schema name(like dbo.Table1), When blank means query all tables 's logs, you can change it for need.
txtTablename.Text = "";
timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
timer.Enabled = false;
Init();
}
19
Source : DatetimeImplementation.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public Datetime addSeconds(int seconds) => new DatetimeInstance(dateTime.AddSeconds(seconds));
19
Source : IPhoneSystemExtensions.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public static DateTime NSDateToDateTime(this NSDate date)
{
double secs = date.SecondsSinceReferenceDate;
if (secs < -63113904000)
return DateTime.MinValue;
if (secs > 252423993599)
return DateTime.MaxValue;
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0));
return reference.AddSeconds(date.SecondsSinceReferenceDate);
}
19
Source : IPhoneSystemExtensions.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public static DateTimeOffset NSDateToDateTimeOffset(this NSDate date)
{
double secs = date.SecondsSinceReferenceDate;
if (secs < -63113904000)
return DateTimeOffset.MinValue;
if (secs > 252423993599)
return DateTimeOffset.MaxValue;
var reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0));
return new DateTimeOffset(reference.AddSeconds(date.SecondsSinceReferenceDate));
}
19
Source : Program.cs
with GNU General Public License v3.0
from approved
with GNU General Public License v3.0
from approved
private static void OrbWalkTimer_Elapsed(object sender, ElapsedEventArgs e)
{
#if DEBUG
owStopWatch.Start();
TimerCallbackCounter++;
#endif
if (!HasProcess || IsExiting || GetForegroundWindow() != LeagueProcess.MainWindowHandle)
{
#if DEBUG
TimerCallbackCounter--;
#endif
return;
}
// Store time at timer tick start into a variable for readability
var time = e.SignalTime;
// Make sure we can send input without being dropped
// This is used for gating movement orders when waiting for an attack to be prepared
// This is not needed if this function is not ran frequently enough for it to matter
// If it isn't, you might end up with this timer and this function's timer being out of sync
// resulting in a (worst-case) OrderTickRate + MinInputDelay delay
// It is currently disabled due to this, enable it if you want/need to
if (true || nextInput < time)
{
// If we can attack, do so
if (nextAttack < time)
{
// Store current time + input delay so we're aware when we can move next
nextInput = time.AddSeconds(MinInputDelay);
// Send attack input
InputSimulator.Keyboard.KeyDown((ushort)DirectInputKeys.DIK_A);
InputSimulator.Mouse.MouseClick(InputSimulator.Mouse.Buttons.Left);
InputSimulator.Keyboard.KeyUp((ushort)DirectInputKeys.DIK_A);
// We've sent input now, so we're re-fetching time as I have no idea how long input takes
// I'm replaceduming it's negligable, but why not
// Please check what the actual difference is if you consider keeping this lol
var attackTime = DateTime.Now;
// Store timings for when to next attack / move
nextMove = attackTime.AddSeconds(GetBufferedWindupDuration());
nextAttack = attackTime.AddSeconds(GetSecondsPerAttack());
}
// If we can't attack but we can move, do so
else if (nextMove < time)
{
// Store current time + input delay so we're aware when we can attack / move next
nextInput = time.AddSeconds(MinInputDelay);
// Send move input
InputSimulator.Mouse.MouseClick(InputSimulator.Mouse.Buttons.Right);
}
}
#if DEBUG
TimerCallbackCounter--;
owStopWatch.Reset();
#endif
}
19
Source : TimeHelper.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public static DateTime GetRandomTime(DateTime time1, DateTime time2)
{
Random random = new Random();
DateTime minTime = new DateTime();
DateTime maxTime = new DateTime();
System.TimeSpan ts = new System.TimeSpan(time1.Ticks - time2.Ticks);
// 获取两个时间相隔的秒数
double dTotalSecontds = ts.TotalSeconds;
int iTotalSecontds = 0;
if (dTotalSecontds > System.Int32.MaxValue)
{
iTotalSecontds = System.Int32.MaxValue;
}
else if (dTotalSecontds < System.Int32.MinValue)
{
iTotalSecontds = System.Int32.MinValue;
}
else
{
iTotalSecontds = (int)dTotalSecontds;
}
if (iTotalSecontds > 0)
{
minTime = time2;
maxTime = time1;
}
else if (iTotalSecontds < 0)
{
minTime = time1;
maxTime = time2;
}
else
{
return time1;
}
int maxValue = iTotalSecontds;
if (iTotalSecontds <= System.Int32.MinValue)
maxValue = System.Int32.MinValue + 1;
int i = random.Next(System.Math.Abs(maxValue));
return minTime.AddSeconds(i);
}
19
Source : AtlassRequest.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public void SetOpenId(string openId, int expireSecond)
{
// SetCookie("openId", openId, expireSecond);
_context.Response.Cookies.Append("openId", openId, new CookieOptions()
{
Expires = DateTime.UtcNow.AddSeconds(expireSecond),
Path = "/",
HttpOnly = false,
IsEssential=true,
Secure=false
//Secure = true,
//SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None
});
}
19
Source : AtlassRequest.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public void SetCookie(string key, string value, int expireSecond)
{
string cliamsString = Encrypt.AesEncrypt(value);
_context.Response.Cookies.Append(key, cliamsString, new CookieOptions()
{
Expires = DateTime.UtcNow.AddSeconds(expireSecond),
Path = "/",
HttpOnly = false,
IsEssential = true,
Secure = false,
//Secure = true,
//SameSite= Microsoft.AspNetCore.Http.SameSiteMode.None
});
}
19
Source : AccessTokenResult.cs
with Apache License 2.0
from arbing
with Apache License 2.0
from arbing
public static DateTime GetExpireTime(int expireInSeconds)
{
if (expireInSeconds > 3600)
{
expireInSeconds -= 600;//提前10分钟过期
}
else if (expireInSeconds > 1800)
{
expireInSeconds -= 300;//提前5分钟过期
}
else if (expireInSeconds > 300)
{
expireInSeconds -= 30;//提前1分钟过期
}
return DateTime.Now.AddSeconds(expireInSeconds);//提前2分钟重新获取
}
19
Source : TimestampConverter.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
int timestamp = serializer.Deserialize<int>(reader);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp).ToLocalTime();
}
19
Source : GuardAgainstOutOfSQLDateRange.cs
with MIT License
from ardalis
with MIT License
from ardalis
[Theory]
[InlineData(1)]
[InlineData(60)]
[InlineData(60 * 60)]
[InlineData(60 * 60 * 24)]
[InlineData(60 * 60 * 24 * 30)]
[InlineData(60 * 60 * 24 * 30 * 365)]
public void ThrowsGivenValueBelowMinDate(int offsetInSeconds)
{
DateTime date = SqlDateTime.MinValue.Value.AddSeconds(-offsetInSeconds);
replacedert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfSQLDateRange(date, nameof(date)));
}
19
Source : GuardAgainstOutOfSQLDateRange.cs
with MIT License
from ardalis
with MIT License
from ardalis
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(60)]
[InlineData(60 * 60)]
[InlineData(60 * 60 * 24)]
[InlineData(60 * 60 * 24 * 30)]
[InlineData(60 * 60 * 24 * 30 * 365)]
public void DoNothingGivenSqlMinValue(int offsetInSeconds)
{
DateTime date = SqlDateTime.MinValue.Value.AddSeconds(offsetInSeconds);
Guard.Against.OutOfSQLDateRange(date, nameof(date));
}
19
Source : GuardAgainstOutOfSQLDateRange.cs
with MIT License
from ardalis
with MIT License
from ardalis
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(60)]
[InlineData(60 * 60)]
[InlineData(60 * 60 * 24)]
[InlineData(60 * 60 * 24 * 30)]
[InlineData(60 * 60 * 24 * 30 * 365)]
public void DoNothingGivenSqlMaxValue(int offsetInSeconds)
{
DateTime date = SqlDateTime.MaxValue.Value.AddSeconds(-offsetInSeconds);
Guard.Against.OutOfSQLDateRange(date, nameof(date));
}
See More Examples