Here are the examples of the csharp api long.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2951 Examples
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override string Readreplacedtring(ISqDataRecordReader recordReader)
=> this.ReadNullable(recordReader)?.ToString()
?? throw new SqExpressException($"Null value is not expected in non nullable column '{this.ColumnName.Name}'");
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override string? Readreplacedtring(ISqDataRecordReader recordReader) => this.Read(recordReader)?.ToString();
19
View Source File : TableColumnsTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
[Test]
public void TestInt64()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.Int64, this.Table.ColInt64.SqlType);
replacedert.AreEqual("[AT].[ColInt64]", this.Table.ColInt64.ToSql());
replacedert.IsFalse(this.Table.ColInt64.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColInt64.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColInt64.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColInt64.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColInt64.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColInt64.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetInt64(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
replacedert.Throws<SqExpressException>(() => this.Table.ColInt64.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableInt64(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(Int64.MaxValue);
replacedert.AreEqual(Int64.MaxValue.ToString(), this.Table.ColInt64.Readreplacedtring(reader.Object));
replacedert.AreEqual(Int64.MinValue.ToString(), this.Table.ColInt64.FromString(Int64.MinValue.ToString()).ToSql());
replacedert.Throws<SqExpressException>(() => this.Table.ColInt64.FromString(null));
}
19
View Source File : TableColumnsTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
[Test]
public void TestNullableInt64()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.Int64, this.Table.ColNullableInt64.SqlType);
replacedert.AreEqual("[AT].[ColNullableInt64]", this.Table.ColNullableInt64.ToSql());
replacedert.IsTrue(this.Table.ColNullableInt64.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColNullableInt64.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColNullableInt64.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColNullableInt64.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColNullableInt64.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColNullableInt64.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetNullableInt64(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
replacedert.IsNull(this.Table.ColNullableInt64.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableInt64(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(Int64.MaxValue);
replacedert.AreEqual(Int64.MaxValue.ToString(), this.Table.ColNullableInt64.Readreplacedtring(reader.Object));
replacedert.AreEqual(Int64.MinValue.ToString(), this.Table.ColNullableInt64.FromString(Int64.MinValue.ToString()).ToSql());
replacedert.AreEqual("NULL", this.Table.ColNullableInt64.FromString(null).ToSql());
}
19
View Source File : IrdClient.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<SearchResult> SearchAsync(string query, CancellationToken cancellationToken)
{
try
{
var requestUri = new Uri(BaseUrl + "/data.php").SetQueryParameters(new Dictionary<string, string>
{
["draw"] = query.Length.ToString(),
["columns[0][data]"] = "id",
["columns[0][name]"] = "",
["columns[0][searchable]"] = "true",
["columns[0][orderable]"] = "true",
["columns[0][search][value]"] = "",
["columns[0][search][regex]"] = "false",
["columns[1][data]"] = "replacedle",
["columns[1][name]"] = "",
["columns[1][searchable]"] = "true",
["columns[1][orderable]"] = "true",
["columns[1][search][value]"] = "",
["columns[1][search][regex]"] = "false",
["order[0][column]"] = "0",
["order[0][dir]"] = "asc",
["start"] = "0",
["length"] = "10",
["search[value]"] = query.Trim(100),
["_"] = DateTime.UtcNow.Ticks.ToString(),
});
try
{
var responseBytes = await client.GetByteArrayAsync(requestUri).ConfigureAwait(false);
var result = Deserialize(responseBytes);
result.Data = result.Data ?? new List<SearchResulreplacedem>(0);
foreach (var item in result.Data)
{
item.Filename = GetIrdFilename(item.Filename);
item.replacedle = Getreplacedle(item.replacedle);
}
return result;
}
catch (Exception e)
{
Log.Error(e, "Failed to make API call to IRD Library");
return null;
}
}
catch (Exception e)
{
Log.Error(e);
return null;
}
}
19
View Source File : DateTimeHelper.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public string GetTimestamp(bool milliseconds = false)
{
var ts = DateTime.UtcNow - TimestampStart;
return Convert.ToInt64(milliseconds ? ts.TotalMilliseconds : ts.TotalSeconds).ToString();
}
19
View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
{
var value = ResolveDynamicInvoke(exp);
var isValueType = false;
var list = new List<string>();
if (valueType.IsEnum)
{
isValueType = true;
var valueList = (IEnumerable)value;
if (valueList != null)
{
foreach (var c in valueList)
{
list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
}
}
}
else
{
var typeName = valueType.Name;
switch (typeName)
{
case "Guid":
if (value is IEnumerable<Guid> guidValues)
{
foreach (var c in guidValues)
{
list.Add(c.ToString());
}
}
break;
case "DateTime":
if (value is IEnumerable<DateTime> dateTimeValues)
{
foreach (var c in dateTimeValues)
{
list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
break;
case "Byte":
isValueType = true;
if (value is IEnumerable<byte> byteValues)
{
foreach (var c in byteValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Char":
if (value is IEnumerable<char> charValues)
{
foreach (var c in charValues)
{
list.Add(c.ToString());
}
}
break;
case "Int16":
isValueType = true;
if (value is IEnumerable<short> shortValues)
{
foreach (var c in shortValues)
{
list.Add(c.ToString());
}
}
break;
case "Int32":
isValueType = true;
if (value is IEnumerable<int> intValues)
{
foreach (var c in intValues)
{
list.Add(c.ToString());
}
}
break;
case "Int64":
isValueType = true;
if (value is IEnumerable<long> longValues)
{
foreach (var c in longValues)
{
list.Add(c.ToString());
}
}
break;
case "Double":
isValueType = true;
if (value is IEnumerable<double> doubleValues)
{
foreach (var c in doubleValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Single":
isValueType = true;
if (value is IEnumerable<float> floatValues)
{
foreach (var c in floatValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Decimal":
isValueType = true;
if (value is IEnumerable<decimal> decimalValues)
{
foreach (var c in decimalValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
}
}
if (list!.Count < 1)
return;
sqlBuilder.Append(columnName);
sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");
//值类型不带引号
if (isValueType)
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("{0}", list[i]);
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
else
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
sqlBuilder.Append(")");
}
19
View Source File : MapSchemaStringBuilder.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public void AppendRouteToken(long position, BssMapRouteToken value)
{
sb.Append($"[{position.ToString()}]");
sb.Append(value.ToString());
sb.Append(" ");
}
19
View Source File : MapSchemaStringBuilder.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public void AppendNextOff(long position, ushort value)
{
sb.Append($"[{position.ToString()}]");
sb.Append("NextOff(" + value.ToString() + ")");
sb.Append(" ");
}
19
View Source File : JsonSender.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public override async Task<string> SendAlert((string, Dictionary<string, dynamic>) res, string sourceIp, string path, string guid)
{
try
{
path = path.Split("/")[1];
var _path = paths.ContainsKey(path)? paths[path] : path;
var message = $"Trapdoor triggered in: {_path}";
var temp = await GenerateAlert(res, sourceIp, message);
var content = new StringContent(temp, Encoding.UTF8, "application/json");
await _client.PostAsync(send_link, content);
return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
19
View Source File : JsonData.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
19
View Source File : BclHelpers.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) {
kind = DateTimeKind.Unspecified;
switch (source.WireType)
{
case WireType.String:
case WireType.StartGroup:
SubItemToken token = ProtoReader.StartSubItem(source);
int fieldNumber;
TimeSpanScale scale = TimeSpanScale.Days;
long value = 0;
while ((fieldNumber = source.ReadFieldHeader()) > 0)
{
switch (fieldNumber)
{
case FieldTimeSpanScale:
scale = (TimeSpanScale)source.ReadInt32();
break;
case FieldTimeSpanValue:
source.replacedert(WireType.SignedVariant);
value = source.ReadInt64();
break;
case FieldTimeSpanKind:
kind = (DateTimeKind)source.ReadInt32();
switch(kind)
{
case DateTimeKind.Unspecified:
case DateTimeKind.Utc:
case DateTimeKind.Local:
break; // fine
default:
throw new ProtoException("Invalid date/time kind: " + kind.ToString());
}
break;
default:
source.SkipField();
break;
}
}
ProtoReader.EndSubItem(token, source);
switch (scale)
{
case TimeSpanScale.Days:
return value * TimeSpan.TicksPerDay;
case TimeSpanScale.Hours:
return value * TimeSpan.TicksPerHour;
case TimeSpanScale.Minutes:
return value * TimeSpan.TicksPerMinute;
case TimeSpanScale.Seconds:
return value * TimeSpan.TicksPerSecond;
case TimeSpanScale.Milliseconds:
return value * TimeSpan.TicksPerMillisecond;
case TimeSpanScale.Ticks:
return value;
case TimeSpanScale.MinMax:
switch (value)
{
case 1: return long.MaxValue;
case -1: return long.MinValue;
default: throw new ProtoException("Unknown min/max value: " + value.ToString());
}
default:
throw new ProtoException("Unknown timescale: " + scale.ToString());
}
case WireType.Fixed64:
return source.ReadInt64();
default:
throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString());
}
}
19
View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void ThrowEnumException(ProtoWriter writer, object enumValue)
{
if (writer == null) throw new ArgumentNullException("writer");
string rhs = enumValue == null ? "<null>" : (enumValue.GetType().FullName + "." + enumValue.ToString());
throw new ProtoException("No wire-value is mapped to the enum " + rhs + " at position " + writer.position64.ToString());
}
19
View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
internal static Exception CreateException(ProtoWriter writer)
{
if (writer == null) throw new ArgumentNullException("writer");
return new ProtoException("Invalid serialization operation with wire-type " + writer.wireType.ToString() + " at position " + writer.position64.ToString());
}
19
View Source File : Send_0x0002.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public long ConvertQQGroupId(long code)
{
var group = code.ToString();
var left = Convert.ToInt64(group.Substring(0, group.Length - 6));
string right = "", gid = "";
if (left >= 1 && left <= 10)
{
right = group.Substring(group.Length - 6, 6);
gid = left + 202 + right;
}
else if (left >= 11 && left <= 19)
{
right = group.Substring(group.Length - 6, 6);
gid = left + 469 + right;
}
else if (left >= 20 && left <= 66)
{
left = Convert.ToInt64(left.ToString().Substring(0, 1));
right = group.Substring(group.Length - 7, 7);
gid = left + 208 + right;
}
else if (left >= 67 && left <= 156)
{
right = group.Substring(group.Length - 6, 6);
gid = left + 1943 + right;
}
else if (left >= 157 && left <= 209)
{
left = Convert.ToInt64(left.ToString().Substring(0, 2));
right = group.Substring(group.Length - 7, 7);
gid = left + 199 + right;
}
else if (left >= 210 && left <= 309)
{
left = Convert.ToInt64(left.ToString().Substring(0, 2));
right = group.Substring(group.Length - 7, 7);
gid = left + 389 + right;
}
else if (left >= 310 && left <= 499)
{
left = Convert.ToInt64(left.ToString().Substring(0, 2));
right = group.Substring(group.Length - 7, 7);
gid = left + 349 + right;
}
else
{
return code;
}
return Convert.ToInt64(gid);
}
19
View Source File : Util.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static string GetQQNum(string six)
{
return Convert.ToInt64(six.Replace(" ", ""), 16).ToString();
}
19
View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
protected AuthenticationHeaderValue GetAuthorizationHeader(string uri, HttpMethod method)
{
string nonce = DateTime.Now.Ticks.ToString();
string timestamp = DateTime.Now.ToUnixTimestamp().ToString();
List<string> authParams = new List<string>();
authParams.Add("oauth_consumer_key=" + ConsumerKey);
authParams.Add("oauth_nonce=" + nonce);
authParams.Add("oauth_signature_method=HMAC-SHA1");
authParams.Add("oauth_timestamp=" + timestamp);
authParams.Add("oauth_token=" + AccessToken);
authParams.Add("oauth_version=1.0");
SplitUri(uri, out string url, out string[] queryParams);
List<string> requestParams = new List<string>(authParams);
requestParams.AddRange(queryParams);
requestParams.Sort();
string signatureBaseString = string.Join("&", requestParams);
signatureBaseString = string.Concat(method.Method.ToUpper(), "&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(signatureBaseString));
string signature = GetSignature(signatureBaseString);
string hv = string.Join(", ", authParams.Select(x => x.Replace("=", " = \"") + '"'));
hv += $", oauth_signature=\"{Uri.EscapeDataString(signature)}\"";
return new AuthenticationHeaderValue("OAuth", hv);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
private static void WriteLine(long recipient, string what, string message)
{
Console.WriteLine($"[Recipient:{recipient.ToString().PadRight(20)}] [{what.PadRight(10)}] {message}");
}
19
View Source File : TokenAuthController.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
private static List<Claim> CreateJwtClaims(ClaimsIdenreplacedy idenreplacedy)
{
var claims = idenreplacedy.Claims.ToList();
var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier);
// Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
claims.AddRange(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
});
return claims;
}
19
View Source File : UserCenterController.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
[HttpPost]
[Authorization]
public IActionResult AvatarUpload([FromForm(Name = "file")] IFormFile file)
{
try
{
if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
{
return toResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
}
var fileExtName = Path.GetExtension(file.FileName).ToLower();
var fileName = DateTime.Now.Ticks.ToString() + fileExtName;
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };
int MaxContentLength = 1024 * 1024 * 4;
if (!AllowedFileExtensions.Contains(fileExtName))
{
return toResponse(StatusCodeType.Error, "上传失败,未经允许上传类型");
}
if (file.Length > MaxContentLength)
{
return toResponse(StatusCodeType.Error, "上传图片过大,不能超过 " + (MaxContentLength / 1024).ToString() + " MB");
}
var filePath = $"/{DateTime.Now:yyyyMMdd}/";
var avatarDirectory = $"{AppSettings.Configuration["AvatarUpload:AvatarDirectory"]}{filePath}";
if (!Directory.Exists(avatarDirectory))
{
Directory.CreateDirectory(avatarDirectory);
}
using (var stream = new FileStream($"{avatarDirectory}{fileName}", FileMode.Create))
{
file.CopyTo(stream);
}
var avatarUrl = $"{AppSettings.Configuration["AvatarUpload:AvatarUrl"]}{filePath}{fileName}";
var userSession = _tokenManager.GetSessionInfo();
#region 更新用户信息
var response = _usersService.Update(m => m.UserID == userSession.UserID, m => new Sys_Users
{
AvatarUrl = avatarUrl,
UpdateID = userSession.UserID,
UpdateName = userSession.UserName,
UpdateTime = DateTime.Now
});
#endregion
#region 更新登录会话记录
_tokenManager.RefreshSession(userSession.UserID);
#endregion
return toResponse(avatarUrl);
}
catch (Exception)
{
throw;
}
}
19
View Source File : Bench.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
internal static string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
19
View Source File : ClientHashChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public ApproveLoadWorldReason GenerateRequestAndDoJob(object context)
{
// each request - response Client-Server-Client ~100-200 ms, get all check hash in one request
// каждый запрос-отклик к серверу ~100-200 мс, получаем за один запрос все файлы
// ~40 000 files *512 SHA key ~ size of package ~ 2,5 Mb
ApproveLoadWorldReason result = ApproveLoadWorldReason.LoginOk;
bool downloading = true;
long totalSize = 0;
long downloadSize = 0;
while (downloading)
{
var clientFileChecker = (ClientFileChecker)context;
var model = new ModelModsFiles()
{
Files = clientFileChecker.FilesHash,
FolderType = clientFileChecker.FolderType,
};
UpdateModsWindow.replacedle = "OC_Hash_Downloading".Translate();
UpdateModsWindow.HashStatus = "";
UpdateModsWindow.SummaryList = null;
Loger.Log($"Send hash {clientFileChecker.Folder}");
var res = _sessionClient.TransObject2<ModelModsFiles>(model, RequestTypePackage, ResponseTypePackage);
if (res.Files.Count > 0)
{
if (totalSize == 0) totalSize = res.TotalSize;
downloadSize += res.Files.Sum(f => f.Size);
Loger.Log($"Files that need for a change: {downloadSize}/{totalSize} count={res.Files.Count}");
var pr = downloadSize > totalSize || totalSize == 0 ? 100 : downloadSize * 100 / totalSize;
UpdateModsWindow.HashStatus = "OC_Hash_Downloading_Finish".Translate()
+ pr.ToString() + "%";
result = result | ApproveLoadWorldReason.ModsFilesFail;
//Loger.Log("TTTTT 0");
FileChecker.FileSynchronization(clientFileChecker.Folder, res);
//Loger.Log("TTTTT 1");
clientFileChecker.RecalculateHash(res.Files.Select(f => f.FileName).ToList());
//Loger.Log("TTTTT 2");
var addList = res.Files
.Select(f => f.FileName)
.Where(f => f.Contains("\\"))
.Select(f => f.Substring(0, f.IndexOf("\\")))
//.Distinct() //вместо дистинкта группируем без разницы заглавных букв, но сохраняем оригинальное название
.Select(f => new { orig = f, comp = f.ToLower() })
.GroupBy(p => p.comp)
.Select(g => g.Max(p => p.orig))
.Where(f => UpdateModsWindow.SummaryList == null || !UpdateModsWindow.SummaryList.Any(sl => sl == f))
.ToList();
if (UpdateModsWindow.SummaryList == null)
UpdateModsWindow.SummaryList = addList;
else
UpdateModsWindow.SummaryList.AddRange(addList);
}
downloading = res.TotalSize != 0;
}
return result;
}
19
View Source File : AttackUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string CheckPossibilityAttack(IPlayerEx attacker, IPlayerEx host, long attackerWOServerId, long hostWOServerId
, bool protectingNovice)
{
try
{
var res =
!attacker.Online ? "Attacker not online"
: !host.Online ? "Host not online"
: !attacker.Public.EnablePVP ? "Attacker not EnablePVP"
: !host.Public.EnablePVP ? "Host not EnablePVP"
: null
;
if (res != null) return res;
if (!protectingNovice) return null;
var hostCosts = host.CostWorldObjects(hostWOServerId);
var hostCost = MaxCostAttackerCaravan(hostCosts.MarketValue + hostCosts.MarketValuePawn, true);
var attCosts = attacker.CostWorldObjects(attackerWOServerId);
var attCost = attCosts.MarketValue + attCosts.MarketValuePawn;
res =
//стоимость колонии больше стоимости каравана
attCost > hostCost
? //"The cost of the attackers is higher than the cost of the colony, this is not fair"
"The cost of the attacker must be less than " + ((long)hostCost).ToString()
//колонии больше 1 года
//todo : host.Public.LastTick < 3600000 ? "You must not attack the game for less than a year"
//колонию атаковали недавно
: (DateTime.UtcNow - host.Public.LastPVPTime).TotalMinutes < host.MinutesIntervalBetweenPVP
? "It was recently attacked. Wait to " + host.Public.LastPVPTime.ToGoodUtcString()
: null;
/*
if (res != null) Loger.Log("CheckPossibilityAttack: " + res
+ " LastOnlineTime=" + attacker.Public.LastOnlineTime.ToString("o")
+ " UtcNow=" + DateTime.UtcNow.ToString("o")
);
*/
return res;
}
catch (Exception exp)
{
Loger.Log("CheckPossibilityAttack Exception" + exp.ToString());
return "Error calc";
}
}
19
View Source File : Loger.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private static void LogWrite(string msg, bool withCatch, int threadId = 0)
{
var thn = threadId != 0 ? threadId : Thread.CurrentThread.ManagedThreadId;
var dn = DateTime.Now;
var dd = !LastMsg.ContainsKey(thn) ? 0 : (long)(dn - LastMsg[thn]).TotalMilliseconds;
LastMsg[thn] = dn;
if (dd >= 1000000) dd = 0;
var logMsg = dn.ToString(Culture) + " |" + dd.ToString().PadLeft(6) + " |" + thn.ToString().PadLeft(4) + " | " + msg;
var fileName = $"Log_{DateTime.Now.ToString("yyyy-MM-dd")}_{MainHelper.RandomSeed}.txt";
if (withCatch) Console.WriteLine(logMsg);
lock (ObjLock)
{
try
{
//if (LogMessage != null) LogMessage(logMsg);
File.AppendAllText(PathLog + fileName, logMsg + Environment.NewLine, Encoding.UTF8);
}
catch (Exception exp)
{
if (withCatch)
{
LogErr = "Log exception: " + exp.Message + Environment.NewLine + logMsg;
LogErrThr = thn;
}
}
}
}
19
View Source File : PlayerServer.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public bool GetKeyReconnect()
{
if ((DateTime.UtcNow - KeyReconnectTime).TotalMinutes < 30
&& !string.IsNullOrEmpty(KeyReconnect1))
return false;
KeyReconnectTime = DateTime.UtcNow;
var rnd = new Random((int)(DateTime.UtcNow.Ticks & int.MaxValue));
var key = "o6*#fn`~ыggTgj0&9 gT54Qa[g}t,23rfr4*vcx%%4/\"d!2" + rnd.Next(int.MaxValue).ToString()
+ DateTime.UtcNow.Date.AddHours(DateTime.UtcNow.Hour).ToBinary().ToString()
+ Public.Login;
var hash = new CryptoProvider().GetHash(key);
KeyReconnect2 = KeyReconnect1;
KeyReconnect1 = hash;
return true;
}
19
View Source File : OVRSceneLoader.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void LoadScene(SceneInfo sceneInfo)
{
replacedetBundle mainSceneBundle = null;
Debug.Log("[OVRSceneLoader] Loading main scene: " + sceneInfo.scenes[0] + " with version " + sceneInfo.version.ToString());
logTextBox.text += "Target Scene: " + sceneInfo.scenes[0] + "\n";
logTextBox.text += "Version: " + sceneInfo.version.ToString() + "\n";
// Load main scene and dependent additive scenes (if any)
Debug.Log("[OVRSceneLoader] Loading scene bundle files.");
// Fetch all files under scene cache path, excluding unnecessary files such as scene metadata file
string[] bundles = Directory.GetFiles(scenePath, "*_*");
logTextBox.text += "Loading " + bundles.Length + " bundle(s) . . . ";
string mainSceneBundleFileName = "scene_" + sceneInfo.scenes[0].ToLower();
try
{
foreach (string b in bundles)
{
var replacedetBundle = replacedetBundle.LoadFromFile(b);
if (replacedetBundle != null)
{
Debug.Log("[OVRSceneLoader] Loading file bundle: " + replacedetBundle.name == null ? "null" : replacedetBundle.name);
loadedreplacedetBundles.Add(replacedetBundle);
}
else
{
Debug.LogError("[OVRSceneLoader] Loading file bundle failed");
}
if (replacedetBundle.name == mainSceneBundleFileName)
{
mainSceneBundle = replacedetBundle;
}
if (replacedetBundle.name == resourceBundleName)
{
OVRResources.SetResourceBundle(replacedetBundle);
}
}
}
catch(Exception e)
{
logTextBox.text += "<color=red>" + e.Message + "</color>";
return;
}
logTextBox.text += "<color=green>DONE\n</color>";
if (mainSceneBundle != null)
{
logTextBox.text += "Loading Scene: {0:P0}\n";
formattedLogText = logTextBox.text;
string[] scenePaths = mainSceneBundle.GetAllScenePaths();
string sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]);
loadSceneOperation = SceneManager.LoadSceneAsync(sceneName);
loadSceneOperation.completed += LoadSceneOperation_completed;
}
else
{
logTextBox.text += "<color=red>Failed to get main scene bundle.\n</color>";
}
}
19
View Source File : PublishArtifact.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task RunAsync(
RunnerActionPluginExecutionContext context,
CancellationToken token)
{
string artifactName = context.GetInput(PublishArtifactInputNames.ArtifactName, required: false); // Back compat since we rename input `artifactName` to `name`
if (string.IsNullOrEmpty(artifactName))
{
artifactName = context.GetInput(PublishArtifactInputNames.Name, required: true);
}
string targetPath = context.GetInput(PublishArtifactInputNames.Path, required: true);
string defaultWorkingDirectory = context.GetGitHubContext("workspace");
targetPath = Path.IsPathFullyQualified(targetPath) ? targetPath : Path.GetFullPath(Path.Combine(defaultWorkingDirectory, targetPath));
if (String.IsNullOrWhiteSpace(artifactName))
{
throw new ArgumentException($"Artifact name can not be empty string");
}
if (Path.GetInvalidFileNameChars().Any(x => artifactName.Contains(x)))
{
throw new ArgumentException($"Artifact name is not valid: {artifactName}. It cannot contain '\\', '/', \"', ':', '<', '>', '|', '*', and '?'");
}
// Build ID
string buildIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.BuildId)?.Value ?? string.Empty;
if (!int.TryParse(buildIdStr, out int buildId))
{
throw new ArgumentException($"Run Id is not an Int32: {buildIdStr}");
}
string fullPath = Path.GetFullPath(targetPath);
bool isFile = File.Exists(fullPath);
bool isDir = Directory.Exists(fullPath);
if (!isFile && !isDir)
{
// if local path is neither file nor folder
throw new FileNotFoundException($"Path does not exist {targetPath}");
}
// Container ID
string containerIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.ContainerId)?.Value ?? string.Empty;
if (!long.TryParse(containerIdStr, out long containerId))
{
throw new ArgumentException($"Container Id is not an Int64: {containerIdStr}");
}
context.Output($"Uploading artifact '{artifactName}' from '{fullPath}' for run #{buildId}");
FileContainerServer fileContainerHelper = new FileContainerServer(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
var propertiesDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
long size = 0;
try
{
size = await fileContainerHelper.CopyToContainerAsync(context, fullPath, token);
propertiesDictionary.Add("artifactsize", size.ToString());
context.Output($"Uploaded '{size}' bytes from '{fullPath}' to server");
}
// if any of the results were successful, make sure to attach them to the build
finally
{
// Definition ID is a dummy value only used by HTTP client routing purposes
int definitionId = 1;
PipelinesServer pipelinesHelper = new PipelinesServer(context.VssConnection);
var artifact = await pipelinesHelper.replacedociateActionsStorageArtifactAsync(
definitionId,
buildId,
containerId,
artifactName,
size,
token);
context.Output($"replacedociated artifact {artifactName} ({artifact.ContainerId}) with run #{buildId}");
}
}
19
View Source File : ExecutionContext.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void AddIssue(Issue issue, string logMessage = null)
{
ArgUtil.NotNull(issue, nameof(issue));
if (string.IsNullOrEmpty(logMessage))
{
logMessage = issue.Message;
}
issue.Message = HostContext.SecretMasker.MaskSecrets(issue.Message);
if (issue.Type == IssueType.Error)
{
// tracking line number for each issue in log file
// log UI use this to navigate from issue to log
if (!string.IsNullOrEmpty(logMessage))
{
long logLineNumber = Write(WellKnownTags.Error, logMessage);
issue.Data["logFileLineNumber"] = logLineNumber.ToString();
}
if (_record.ErrorCount < _maxIssueCount)
{
_record.Issues.Add(issue);
}
_record.ErrorCount++;
}
else if (issue.Type == IssueType.Warning)
{
// tracking line number for each issue in log file
// log UI use this to navigate from issue to log
if (!string.IsNullOrEmpty(logMessage))
{
long logLineNumber = Write(WellKnownTags.Warning, logMessage);
issue.Data["logFileLineNumber"] = logLineNumber.ToString();
}
if (_record.WarningCount < _maxIssueCount)
{
_record.Issues.Add(issue);
}
_record.WarningCount++;
}
else if (issue.Type == IssueType.Notice)
{
// tracking line number for each issue in log file
// log UI use this to navigate from issue to log
if (!string.IsNullOrEmpty(logMessage))
{
long logLineNumber = Write(WellKnownTags.Notice, logMessage);
issue.Data["logFileLineNumber"] = logLineNumber.ToString();
}
if (_record.NoticeCount < _maxIssueCount)
{
_record.Issues.Add(issue);
}
_record.NoticeCount++;
}
_jobServerQueue.QueueTimelineRecordUpdate(_mainTimelineId, _record);
}
19
View Source File : ObjectCacheExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static JObject GetJson<TKey>(
this ObjectCache cache,
Func<string, object, bool> filter,
Func<CacheItemDetail, TKey> orderBy,
string replacedle = null,
string description = null,
Uri feedAlternateLink = null,
Uri itemAlternateLink = null,
string regionName = null,
bool expanded = false)
{
var objectCacheElement = new JObject
{
{ "type", cache.ToString() },
{ "count", cache.GetCount(regionName).ToString() },
{ "defaultCacheCapabilities", cache.DefaultCacheCapabilities.ToString() }
};
var compositeCache = cache as CompositeObjectCache;
while (compositeCache != null && compositeCache.Cache is CompositeObjectCache)
{
compositeCache = compositeCache.Cache as CompositeObjectCache;
}
var memoryCache = compositeCache != null ? compositeCache.Cache as MemoryCache : cache as MemoryCache;
var memoryCacheElement = memoryCache != null
? new JObject
{
{ "cacheMemoryLimit", memoryCache.CacheMemoryLimit.ToString() },
{ "physicalMemoryLimit", memoryCache.PhysicalMemoryLimit.ToString() },
{ "pollingInterval", memoryCache.PollingInterval.ToString() }
}
: null;
var items = GetJsonItems(cache, filter, orderBy, itemAlternateLink, regionName, expanded);
var retval = CreateSerializableFeed(replacedle ?? cache.Name, description, feedAlternateLink, objectCacheElement, memoryCacheElement, items);
return retval;
}
19
View Source File : ObjectCacheExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static XmlDoreplacedent GetCacheFootprintXml(this ObjectCache cache, bool expanded, Uri requestUrl)
{
var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));
var doc = new XmlDoreplacedent();
var rootElement = doc.CreateElement("CacheFootprint");
var enreplacedyElements = new List<XmlElement>();
var footprint = GetCacheFootprint(cache, alternateLink);
foreach (var enreplacedyType in footprint)
{
var enreplacedyElement = doc.CreateElement("Enreplacedy");
enreplacedyElement.SetAttribute("Name", enreplacedyType.Name);
enreplacedyElement.SetAttribute("Count", enreplacedyType.GetCount().ToString());
enreplacedyElement.SetAttribute("Size", enreplacedyType.GetSize().ToString());
if (expanded)
{
foreach (var item in enreplacedyType.Items)
{
var itemElement = doc.CreateElement("Item");
itemElement.SetAttribute("LogicalName", item.Enreplacedy.LogicalName);
itemElement.SetAttribute("Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty));
itemElement.SetAttribute("Id", item.Enreplacedy.Id.ToString());
var cacheElement = doc.CreateElement("Cache");
cacheElement.SetAttribute("Id", item.CacheItemKey);
cacheElement.SetAttribute("Type", item.CacheItemType.ToString());
cacheElement.SetAttribute("Link", item.Link.ToString());
cacheElement.SetAttribute("Size", GetEnreplacedySizeInMemory(item.Enreplacedy).ToString());
itemElement.AppendChild(cacheElement);
enreplacedyElement.AppendChild(itemElement);
}
}
enreplacedyElements.Add(enreplacedyElement);
}
// Sort the enreplacedies by descending size
enreplacedyElements = enreplacedyElements.OrderByDescending(el => int.Parse(el.GetAttribute("Size"))).ToList();
var enreplacediesElement = doc.CreateElement("Enreplacedies");
foreach (var enreplacedyElement in enreplacedyElements)
{
enreplacediesElement.AppendChild(enreplacedyElement);
}
if (!expanded)
{
// Add link to the Expanded view with enreplacedy record details
var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
var expandedView = doc.CreateElement("expandedView");
expandedView.InnerText = uriBuilder.ToString();
rootElement.AppendChild(expandedView);
}
rootElement.AppendChild(enreplacediesElement);
doc.AppendChild(rootElement);
return doc;
}
19
View Source File : ChatAuthController.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetTokenString(IList<Claim> claims)
{
string tokenString = null;
using (var cryptoServiceProvider = GetCryptoProvider(true))
{
string issuer = PortalSettings.Instance.DomainName;
string audience = string.Empty;
DateTime notBefore = DateTime.Now;
DateTime expires = notBefore.AddHours(1);
var tokenHandler = new JwtSecurityTokenHandler();
var signingCredentials = new SigningCredentials(new RsaSecurityKey(cryptoServiceProvider),
SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
// need to explicitly add "iat" claim
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var iat = Convert.ToInt64((TimeZoneInfo.ConvertTimeToUtc(notBefore) - unixEpoch).TotalSeconds - 1);
claims.Add(new Claim("iat", iat.ToString(), ClaimValueTypes.Integer));
var header = new JwtHeader(signingCredentials);
var payload = new JwtPayload(issuer, audience, claims, notBefore, expires);
// Need to adjust this because Claim clreplaced ignores value type
payload["iat"] = Convert.ToInt64(payload["iat"]);
var jwtToken = new JwtSecurityToken(header, payload);
tokenString = tokenHandler.WriteToken(jwtToken);
}
return tokenString;
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AdriaandeJongh
License : GNU General Public License v3.0
Project Creator : AdriaandeJongh
static string GetFileSize(string filepath)
{
return new FileInfo(filepath).Length.ToString();
}
19
View Source File : ObjectPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static void Farmer_doDivorce_Prefix(ref Farmer __instance, ref string __state)
{
try
{
if (__instance.spouse != null)
{
__state = __instance.getSpouse().name;
}
else if (__instance.team.GetSpouse(__instance.UniqueMultiplayerID) != null)
{
long spouseID = __instance.team.GetSpouse(__instance.UniqueMultiplayerID).Value;
__state = spouseID.ToString();
}
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(Farmer_doDivorce_Prefix)}:\n{ex}", LogLevel.Error);
}
}
19
View Source File : DebugPanel.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
[GUIPage(Traffic)]
private void TrafficPage()
{
TrafficStatsGameLevel trafficStatsGameLevel = PhotonNetwork.networkingPeer.TrafficStatsGameLevel;
long num = PhotonNetwork.networkingPeer.TrafficStatsElapsedMs / 1000L;
if (num == 0L)
{
num = 1L;
}
left.Reset();
right.Reset();
bool cache = NetworkStats.Value;
ToggleButton(left, NetworkStats, locale["statsOn"], true);
if (NetworkStats.Value != cache)
{
PhotonNetwork.networkingPeer.TrafficStatsEnabled = NetworkStats.Value;
return;
}
if (!NetworkStats.Value)
{
return;
}
Label(left, locale.Format("statString", trafficStatsGameLevel.TotalOutgoingMessageCount.ToString(), trafficStatsGameLevel.TotalIncomingMessageCount.ToString(), trafficStatsGameLevel.TotalMessageCount.ToString()), true);
Label(left, locale.Format("avgSec", num.ToString()), true);
Label(left, locale.Format("statString", (trafficStatsGameLevel.TotalOutgoingMessageCount / num).ToString(), (trafficStatsGameLevel.TotalIncomingMessageCount / num).ToString(), (trafficStatsGameLevel.TotalMessageCount / num).ToString()), true);
Label(left, locale.Format("ping", PhotonNetwork.networkingPeer.RoundTripTime.ToString(), PhotonNetwork.networkingPeer.RoundTripTimeVariance.ToString()), true);
Label(left, locale.Format("deltaSend", trafficStatsGameLevel.LongestDeltaBetweenSending.ToString()), true);
Label(left, locale.Format("deltaDispatch", trafficStatsGameLevel.LongestDeltaBetweenDispatching.ToString()), true);
Label(left, locale.Format("deltaEvent", trafficStatsGameLevel.LongestEventCallbackCode.ToString(), trafficStatsGameLevel.LongestEventCallback.ToString()), true);
Label(left, locale.Format("deltaOperation", trafficStatsGameLevel.LongestOpResponseCallbackOpCode.ToString(), trafficStatsGameLevel.LongestOpResponseCallback.ToString()), true);
left.MoveToEndY(WindowPosition, Style.Height);
if (Button(left, locale["btnReset"]))
{
PhotonNetwork.networkingPeer.TrafficStatsReset();
PhotonNetwork.networkingPeer.TrafficStatsEnabled = true;
}
LabelCenter(right, locale["in"], true);
var stats = PhotonNetwork.networkingPeer.TrafficStatsIncoming;
Label(right, locale.Format("bytesCountPackets", stats.TotalPacketBytes.ToString()), true);
Label(right, locale.Format("bytesCountCmd", stats.TotalCommandBytes.ToString()), true);
Label(right, locale.Format("packetsCount", stats.TotalPacketCount.ToString()), true);
Label(right, locale.Format("cmdCount", stats.TotalCommandsInPackets.ToString()), true);
LabelCenter(right, locale["out"], true);
stats = PhotonNetwork.networkingPeer.TrafficStatsOutgoing;
Label(right, locale.Format("bytesCountPackets", stats.TotalPacketBytes.ToString()), true);
Label(right, locale.Format("bytesCountCmd", stats.TotalCommandBytes.ToString()), true);
Label(right, locale.Format("packetsCount", stats.TotalPacketCount.ToString()), true);
Label(right, locale.Format("cmdCount", stats.TotalCommandsInPackets.ToString()), true);
}
19
View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static byte[] ToUtf8Bytes(this long longVal)
{
return FastToUtf8Bytes(longVal.ToString());
}
19
View Source File : StorageKeyExtensions.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static string ToStorageKey(this long n)
{
return n.ToString();
}
19
View Source File : ElectionTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
[Fact]
public async Task ElectionContract_AnnounceElection_Twice_Test()
{
var s = Stopwatch.StartNew();
s.Start();
var candidateKeyPair = (await ElectionContract_AnnounceElection_Test())[0];
var transactionResult = await AnnounceElectionAsync(candidateKeyPair);
transactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
transactionResult.Error.ShouldContain("This public key already announced election.");
s.Stop();
_testOutputHelper.WriteLine(s.ElapsedMilliseconds.ToString());
}
19
View Source File : CrossChainDataConsumerTest.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private SideChainBlockData CreateSideChainBlockData(int chainId, long height)
{
return new SideChainBlockData
{
ChainId = chainId,
Height = height,
TransactionStatusMerkleTreeRoot = HashHelper.ComputeFrom(height.ToString())
};
}
19
View Source File : Contract.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public override Empty CpuConsumingMethod(Empty input)
{
var sum = 0L;
for (var i = 0; i < 99; i++)
{
sum = sum.Add(i);
}
State.Map[sum.ToString()] = sum.ToString();
return new Empty();
}
19
View Source File : InValueCacheTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
[Fact]
public void InValueCacheBasicFunctionTest()
{
const long startRoundId = 1000000L;
Hash GenerateInValue(long i) => HashHelper.ComputeFrom($"InValue{i.ToString()}");
for (var i = 0; i < 13; i++)
{
var roundId = startRoundId + i * 100;
var inValue = GenerateInValue(roundId);
_inValueCache.AddInValue(roundId, inValue);
}
_inValueCache.GetInValue(startRoundId + 500).ShouldBe(GenerateInValue(startRoundId + 500));
// Already cleared.
_inValueCache.GetInValue(startRoundId).ShouldBe(Hash.Empty);
}
19
View Source File : DataMap.cs
License : MIT License
Project Creator : aerosoul94
License : MIT License
Project Creator : aerosoul94
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var G = e.Graphics;
var cellPad = 5;
_visibleRows = (_rowInfo.Height / CellSize + cellPad) + 1;
_visibleColumns = _totalColumns;
_startCell = vScrollPos * _totalColumns;
_endCell = _startCell + Math.Min(
_visibleRows * _totalColumns,
CellCount - _startCell);
_visibleCells = _endCell - _startCell;
#if DEBUG
G.DrawRectangle(_frameBorderPen, _columnInfo);
G.DrawRectangle(_frameBorderPen, _rowInfo);
G.DrawRectangle(_frameBorderPen, _grid);
#endif
// Draw column info
for (int c = 0; c < _visibleColumns; c++)
{
G.DrawString((c + 1).ToString().PadLeft(2),
_font,
_fontBrush,
_columnInfo.X + (c * (CellSize + cellPad)),
_columnInfo.Y);
}
// Draw row info
for (int r = 0; r < _visibleRows; r++)
{
var offset = (vScrollPos + r) * (Increment * _visibleColumns);
var row = (vScrollPos + r) + 1;
// Draw row number
G.DrawString(row.ToString().PadLeft(6),
_font,
_fontBrush,
_rowInfo.X,
_rowInfo.Y + (r * (CellSize + cellPad)) + 5);
// Draw offset
G.DrawString(offset.ToString("X16"),
_font,
_fontBrush,
_rowInfo.X + 60,
_rowInfo.Y + (r * (CellSize + cellPad)) + 5);
}
// Draw cells
for (int i = 0; i < _visibleCells; i++)
{
// Get column and row for current cell
int x = (i % (int)_totalColumns); // column
int y = (i / (int)_totalColumns); // row
// Calculate coordinates for this cell
var xPos = (x * (CellSize + cellPad));
var yPos = (y * (CellSize + cellPad));
var cellIndex = (int)(_startCell + (y * _visibleColumns) + x);
var rect = new Rectangle(_grid.X + xPos,
_grid.Y + yPos,
CellSize,
CellSize);
Cells[cellIndex].Rect = rect;
if (Cells[cellIndex].Selected)
{
G.FillRectangle(_highlightBrush,
new Rectangle(
_grid.X + xPos - 4,
_grid.Y + yPos - 4,
CellSize + 9,
CellSize + 9));
}
// Draw filled rectangle
G.FillRectangle(
new SolidBrush(Cells[cellIndex].Color),
rect);
G.DrawRectangle(
_cellBorderPen,
rect);
}
}
19
View Source File : ConversionTablePlugin.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
void Update64bit(DataView dv)
{
long offset = dv.CursorOffset;
// make sure offset is valid
if (offset < dv.Buffer.Size - 7 && offset >= 0) {
long val = 0;
// create buffer for raw bytes
byte[] ba = new byte[8];
// fill byte[] according to endianess
if (littleEndian)
for (int i = 0; i < 8; i++)
ba[i] = dv.Buffer[offset+i];
else
for (int i = 0; i < 8; i++)
ba[7-i] = dv.Buffer[offset+i];
// set signed
val = BitConverter.ToInt64(ba);
Signed64bitEntry.Text = val.ToString();
// set unsigned
ulong uval = (ulong)val;
if (unsignedAsHex)
Unsigned64bitEntry.Text = string.Format("0x{0:x}", uval);
else
Unsigned64bitEntry.Text = uval.ToString();
}
else {
Clear64bit();
}
}
19
View Source File : Session.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
public void Save(string path)
{
using (XmlTextWriter xml = new XmlTextWriter(path, null)) {
xml.Formatting = Formatting.Indented;
xml.Indentation = 1;
xml.IndentChar = '\t';
xml.WriteStartDoreplacedent();
xml.WriteStartElement(null, "session", null);
xml.WriteStartElement(null, "windowheight", null);
xml.WriteString(windowHeight.ToString());
xml.WriteEndElement();
xml.WriteStartElement(null, "windowwidth", null);
xml.WriteString(windowWidth.ToString());
xml.WriteEndElement();
xml.WriteStartElement(null, "activefile", null);
xml.WriteString(activeFile);
xml.WriteEndElement();
foreach(SessionFileInfo sfi in files) {
xml.WriteStartElement(null, "file", null);
xml.WriteStartElement(null, "path", null);
xml.WriteString(sfi.Path);
xml.WriteEndElement();
xml.WriteStartElement(null, "offset", null);
xml.WriteString(sfi.Offset.ToString());
xml.WriteEndElement();
xml.WriteStartElement(null, "cursoroffset", null);
xml.WriteString(sfi.CursorOffset.ToString());
xml.WriteEndElement();
xml.WriteStartElement(null, "cursordigit", null);
xml.WriteString(sfi.CursorDigit.ToString());
xml.WriteEndElement();
xml.WriteStartElement(null, "layout", null);
xml.WriteString(sfi.Layout);
xml.WriteEndElement();
xml.WriteStartElement(null, "focusedarea", null);
xml.WriteString(sfi.FocusedArea.ToString());
xml.WriteEndElement();
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndDoreplacedent();
}
}
19
View Source File : FileSizeConverter.cs
License : MIT License
Project Creator : afxw
License : MIT License
Project Creator : afxw
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
long size = (long)values[0];
var fileType = (FileType)values[1];
if (fileType == FileType.Directory)
return "-";
string unit = "bytes";
long minifiedSize = size;
if (size >= 1000)
{
unit = "KB";
minifiedSize = size / 1024;
}
if (size >= 1000000)
{
unit = "MB";
minifiedSize = size / 1048576;
}
if (size >= 1000000000)
{
unit = "GB";
minifiedSize = size / 1073741824;
}
return $"{minifiedSize.ToString()} {unit}";
}
19
View Source File : HttpExtensions.cs
License : MIT License
Project Creator : agc93
License : MIT License
Project Creator : agc93
public static StringContent ToContent(this long l) {
return new StringContent(l.ToString());
}
19
View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static RedisArray.Strings Sort(string key, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get)
{
List<string> args = new List<string>();
args.Add(key);
if (by != null)
args.AddRange(new[] { "BY", by });
if (offset.HasValue && count.HasValue)
args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
foreach (var pattern in get)
args.AddRange(new[] { "GET", pattern });
if (dir.HasValue)
args.Add(dir.ToString().ToUpperInvariant());
if (isAlpha.HasValue && isAlpha.Value)
args.Add("ALPHA");
return new RedisArray.Strings("SORT", args.ToArray());
}
19
View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static RedisInt SortAndStore(string key, string destination, long? offset = null, long? count = null, string by = null, RedisSortDir? dir = null, bool? isAlpha = null, params string[] get)
{
List<string> args = new List<string>();
args.Add(key);
if (by != null)
args.AddRange(new[] { "BY", by });
if (offset.HasValue && count.HasValue)
args.AddRange(new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
foreach (var pattern in get)
args.AddRange(new[] { "GET", pattern });
if (dir.HasValue)
args.Add(dir.ToString().ToUpperInvariant());
if (isAlpha.HasValue && isAlpha.Value)
args.Add("ALPHA");
args.AddRange(new[] { "STORE", destination });
return new RedisInt("SORT", args.ToArray());
}
19
View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static RedisArray.Strings ZRange(string key, long start, long stop, bool withScores = false)
{
string[] args = withScores
? new[] { key, start.ToString(), stop.ToString(), "WITHSCORES" }
: new[] { key, start.ToString(), stop.ToString() };
return new RedisArray.Strings("ZRANGE", args);
}
19
View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static RedisArray.Strings ZRangeByScore(string key, string min, string max, bool withScores = false, long? offset = null, long? count = null)
{
object[] args = new[] { key, min, max};
if (withScores)
args = RedisArgs.Concat(args, new[] { "WITHSCORES" });
if (offset.HasValue && count.HasValue)
args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
return new RedisArray.Strings("ZRANGEBYSCORE", args);
}
19
View Source File : RedisCommand.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static RedisArray.WeakPairs<string, double> ZRangeByScoreWithScores(string key, string min, string max, long? offset = null, long? count = null)
{
object[] args = new[] { key, min, max, "WITHSCORES" };
if (offset.HasValue && count.HasValue)
args = RedisArgs.Concat(args, new[] { "LIMIT", offset.Value.ToString(), count.Value.ToString() });
return new RedisArray.WeakPairs<string, double>("ZRANGEBYSCORE", args);
}
See More Examples