Here are the examples of the csharp api string.TrimEnd(params char[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3619 Examples
19
View Source File : HealthMonitor.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private string RebuildArgList(string argList, string extras)
{
if (string.IsNullOrEmpty(extras))
return argList;
StringBuilder sb = new StringBuilder();
string s;
Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
Dictionary<string, string> extraDict = Helper.ParseOptions(extras);
foreach (var key in extraDict.Keys)
{
if (eArgs.ContainsKey(key))
{
eArgs[key] = extraDict[key];
}
else
{
eArgs.Add(key, extraDict[key]);
}
}
extraDict.Clear();
extraDict = null;
foreach (var key in eArgs.Keys)
{
sb.AppendFormat("{0} {1} ", key, eArgs[key]);
}
s = sb.ToString().TrimEnd();
eArgs.Clear();
eArgs = null;
sb.Clear();
sb = null;
return s;
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private string GetValueStringFromOffset()
{
string valueString;
TagDataType type = this.entry.Type;
uint count = this.entry.Count;
uint offset = this.entry.Offset;
if (count == 0)
{
return string.Empty;
}
int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);
if (typeSizeInBytes == 1)
{
byte[] bytes = new byte[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
if (type == TagDataType.Ascii)
{
valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
}
else if (count == 1)
{
valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
}
else
{
StringBuilder builder = new StringBuilder();
uint lasreplacedemIndex = count - 1;
for (int i = 0; i < count; i++)
{
builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));
if (i < lasreplacedemIndex)
{
builder.Append(",");
}
}
valueString = builder.ToString();
}
}
else if (typeSizeInBytes == 2)
{
ushort[] values = new ushort[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
values[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
values[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
values[0] = (ushort)(offset & 0x0000ffff);
values[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
if (count == 1)
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture);
break;
}
}
else
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
((short)values[1]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
values[1].ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
valueString = offset.ToString(CultureInfo.InvariantCulture);
}
return valueString;
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private string GetValueStringFromOffset()
{
string valueString;
TagDataType type = entry.Type;
uint count = entry.Count;
uint offset = entry.Offset;
if (count == 0)
{
return string.Empty;
}
int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);
if (typeSizeInBytes == 1)
{
byte[] bytes = new byte[count];
if (offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
if (type == TagDataType.Ascii)
{
valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
}
else if (count == 1)
{
valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
}
else
{
StringBuilder builder = new StringBuilder();
uint lasreplacedemIndex = count - 1;
for (int i = 0; i < count; i++)
{
builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));
if (i < lasreplacedemIndex)
{
builder.Append(",");
}
}
valueString = builder.ToString();
}
}
else if (typeSizeInBytes == 2)
{
ushort[] values = new ushort[count];
if (offsetIsBigEndian)
{
switch (count)
{
case 1:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
values[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
values[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
values[0] = (ushort)(offset & 0x0000ffff);
values[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
if (count == 1)
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture);
break;
}
}
else
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
((short)values[1]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
values[1].ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
valueString = offset.ToString(CultureInfo.InvariantCulture);
}
return valueString;
}
19
View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
{
if (!string.IsNullOrWhiteSpace(customKey))
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";
if (string.IsNullOrWhiteSpace(sql))
throw new ArgumentNullException(nameof(sql));
var builder = new StringBuilder();
builder.AppendFormat("{0}:", sql);
if (param == null)
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";
var prop = GetProperties(param);
foreach (var item in prop)
{
builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
}
if (pageIndex.HasValue)
{
builder.AppendFormat("pageindex={0}&", pageIndex.Value);
}
if (pageSize.HasValue)
{
builder.AppendFormat("pagesize={0}&", pageSize.Value);
}
return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
}
19
View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
View Source File : SfbReader.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static Ps3DiscDumper.Sfb.Sfb Parse(byte[] content)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
if (content.Length < 200)
throw new ArgumentException("Data is too small to be a valid SFB structure", nameof(content));
if (EndianBitConverter.BigEndian.ToInt32(content, 0) != Ps3DiscDumper.Sfb.Sfb.Magic)
throw new ArgumentException("Specified file is not a valid SFB file", nameof(content));
var result = new Ps3DiscDumper.Sfb.Sfb();
using var stream = new MemoryStream(content, false);
using var reader = new BinaryReader(stream, Encoding.ASCII);
reader.ReadInt32(); // magic
result.VersionMajor = EndianBitConverter.BigEndian.ToInt16(reader.ReadBytes(2), 0);
result.VersionMinor = EndianBitConverter.BigEndian.ToInt16(reader.ReadBytes(2), 0);
result.Unknown1 = reader.ReadBytes(0x18);
do
{
var keyEntry = new SfbKeyEntry();
keyEntry.Key = Encoding.ASCII.GetString(reader.ReadBytes(0x10)).TrimEnd('\0');
if (string.IsNullOrEmpty(keyEntry.Key))
break;
keyEntry.ValueOffset = EndianBitConverter.BigEndian.ToInt32(reader.ReadBytes(4), 0);
keyEntry.ValueLength = EndianBitConverter.BigEndian.ToInt32(reader.ReadBytes(4), 0);
keyEntry.Unknown = reader.ReadInt64();
result.KeyEntries.Add(keyEntry);
} while (true);
foreach (var entry in result.KeyEntries)
{
reader.BaseStream.Seek(entry.ValueOffset, SeekOrigin.Begin);
entry.Value = Encoding.ASCII.GetString(reader.ReadBytes(entry.ValueLength)).TrimEnd('\0');
}
return result;
}
19
View Source File : EnvironmentVariableReader.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static T Get<T>(string variable, T defaultValue = default)
{
var value = Environment.GetEnvironmentVariable(variable);
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
value = value.ReplaceIpPlaceholder();
var matches = Regex.Matches(value, "[{](.*?)[}]");
if (matches.Count > 0)
{
foreach (var match in matches)
{
value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
}
}
return (T)Convert.ChangeType(value, typeof(T));
}
19
View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
{
var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
var nextLevel = new List<string>();
var filePaths = new List<string>();
var dirPaths = new List<string>();
while (fsObjects.Any())
{
foreach (var path in fsObjects)
{
if (reader.FileExists(path))
filePaths.Add(path);
else if (reader.DirectoryExists(path))
{
dirPaths.Add(path);
nextLevel.AddRange(reader.GetFileSystemEntries(path));
}
else
Log.Warn($"Unknown filesystem object: {path}");
}
(fsObjects, nextLevel) = (nextLevel, fsObjects);
nextLevel.Clear();
}
var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
var deepestDirnames = new List<string>();
foreach (var dirname in dirnames)
{
var tmp = dirname + "\\";
if (deepestDirnames.Any(n => n.StartsWith(tmp)))
continue;
deepestDirnames.Add(dirname);
}
dirnames = deepestDirnames.OrderBy(n => n).ToList();
var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();
var fileList = new List<FileRecord>();
foreach (var filename in filenames)
{
var clusterRange = reader.PathToClusters(filename);
if (clusterRange.Length != 1)
Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
if (filename.EndsWith("."))
Log.Warn($"Fixing potential mastering error in {filename}");
fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
}
fileList = fileList.OrderBy(r => r.StartSector).ToList();
return (files: fileList, dirs: emptydirs);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
static async Task<int> Main(string[] args)
{
Log.Info("PS3 Disc Dumper v" + Dumper.Version);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
try
{
Log.Error("Looks like there's no console present, restarting...");
var launchArgs = Environment.GetCommandLineArgs()[0];
if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
{
Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
using var currentProcess = Process.GetCurrentProcess();
var pid = currentProcess.Id;
var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
}
Log.Debug($"Using cmdline '{launchArgs}'");
launchArgs = $"-e bash -c {launchArgs}";
var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
using var proc = Process.Start(startInfo);
if (proc.WaitForExit(1_000))
{
if (proc.ExitCode != 0)
{
startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
using var proc2 = Process.Start(startInfo);
if (proc2.WaitForExit(1_000))
{
if (proc2.ExitCode != 0)
{
startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
using var proc3 = Process.Start(startInfo);
if (proc3.WaitForExit(1_000))
{
if (proc3.ExitCode != 0)
{
startInfo = new ProcessStartInfo("konsole", launchArgs);
using var _ = Process.Start(startInfo);
}
}
}
}
}
}
return -2;
}
catch (Exception e)
{
Log.Error(e);
return -3;
}
var lastDiscId = "";
start:
const string replacedleBase = "PS3 Disc Dumper";
var replacedle = replacedleBase;
Console.replacedle = replacedle;
var output = ".";
var inDir = "";
var showHelp = false;
var options = new OptionSet
{
{
"i|input=", "Path to the root of blu-ray disc mount", v =>
{
if (v is string ind)
inDir = ind;
}
},
{
"o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
{
if (v is string outd)
output = outd;
}
},
{
"?|h|help", "Show help", v =>
{
if (v != null)
showHelp = true;
},
true
},
};
try
{
var unknownParams = options.Parse(args);
if (unknownParams.Count > 0)
{
Log.Warn("Unknown parameters: ");
foreach (var p in unknownParams)
Log.Warn("\t" + p);
showHelp = true;
}
if (showHelp)
{
ShowHelp(options);
return 0;
}
var dumper = new Dumper(ApiConfig.Cts);
dumper.DetectDisc(inDir);
await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
if (string.IsNullOrEmpty(dumper.OutputDir))
{
Log.Info("No compatible disc was found, exiting");
return 2;
}
if (lastDiscId == dumper.ProductCode)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
Console.ResetColor();
var confirmKey = Console.ReadKey(true);
switch (confirmKey.Key)
{
case ConsoleKey.Y:
break;
default:
throw new OperationCanceledException("Aborting re-dump of the same disc");
}
}
lastDiscId = dumper.ProductCode;
replacedle += " - " + dumper.replacedle;
var monitor = new Thread(() =>
{
try
{
do
{
if (dumper.CurrentSector > 0)
Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
} while (!ApiConfig.Cts.Token.IsCancellationRequested);
}
catch (TaskCanceledException)
{
}
Console.replacedle = replacedle;
});
monitor.Start();
await dumper.DumpAsync(output).ConfigureAwait(false);
ApiConfig.Cts.Cancel(false);
monitor.Join(100);
if (dumper.BrokenFiles.Count > 0)
{
Log.Fatal("Dump is not valid");
foreach (var file in dumper.BrokenFiles)
Log.Error($"{file.error}: {file.filename}");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Dump is valid");
Console.ResetColor();
}
}
catch (OptionException)
{
ShowHelp(options);
return 1;
}
catch (Exception e)
{
Log.Error(e, e.Message);
}
Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.X:
return 0;
default:
goto start;
}
}
19
View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
19
View Source File : StaticFiles.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static IApplicationBuilder UseFreeAdminLteStaticFiles(this IApplicationBuilder app, string requestPathBase) {
if (_isStaticFiles == false) {
lock (_isStaticFilesLock) {
if (_isStaticFiles == false) {
var curPath = AppDomain.CurrentDomain.BaseDirectory;
var zipPath = $"{curPath}/{Guid.NewGuid()}.zip";
using (var zip = WwwrootStream()) {
using (var fs = File.Open(zipPath, FileMode.OpenOrCreate)) {
zip.CopyTo(fs);
fs.Close();
}
zip.Close();
}
var wwwrootPath = Path.Combine(curPath, "FreeSql.AdminLTE.wwwroot");
if (Directory.Exists(wwwrootPath)) Directory.Delete(wwwrootPath, true);
try {
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, wwwrootPath, Encoding.UTF8);
} catch (Exception ex) {
throw new Exception($"UseFreeAdminLtePreview 错误,资源文件解压失败:{ex.Message}", ex);
} finally {
File.Delete(zipPath);
}
app.UseStaticFiles(new StaticFileOptions {
RequestPath = requestPathBase.TrimEnd('/'),
FileProvider = new PhysicalFileProvider(wwwrootPath)
});
_isStaticFiles = true;
}
}
}
return app;
}
19
View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private static VmessItem ResolveSSLegacy(string result)
{
var match = UrlFinder.Match(result);
if (!match.Success)
return null;
VmessItem server = new VmessItem();
var base64 = match.Groups["base64"].Value.TrimEnd('/');
var tag = match.Groups["tag"].Value;
if (!Utils.IsNullOrEmpty(tag))
{
server.remarks = Utils.UrlDecode(tag);
}
Match details;
try
{
details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));
}
catch (FormatException)
{
return null;
}
if (!details.Success)
return null;
server.security = details.Groups["method"].Value;
server.id = details.Groups["preplacedword"].Value;
server.address = details.Groups["hostname"].Value;
server.port = int.Parse(details.Groups["port"].Value);
return server;
}
19
View Source File : Board.cs
License : MIT License
Project Creator : 3583Bytes
License : MIT License
Project Creator : 3583Bytes
internal static string Fen(bool boardOnly, Board board)
{
string output = String.Empty;
byte blankSquares = 0;
for (byte x = 0; x < 64; x++)
{
byte index = x;
if (board.Squares[index].Piece != null)
{
if (blankSquares > 0)
{
output += blankSquares.ToString();
blankSquares = 0;
}
if (board.Squares[index].Piece.PieceColor == ChessPieceColor.Black)
{
output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType).ToLower();
}
else
{
output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType);
}
}
else
{
blankSquares++;
}
if (x % 8 == 7)
{
if (blankSquares > 0)
{
output += blankSquares.ToString();
output += "/";
blankSquares = 0;
}
else
{
if (x > 0 && x != 63)
{
output += "/";
}
}
}
}
if (output.EndsWith("/"))
{
output = output.TrimEnd('/');
}
if (board.WhoseMove == ChessPieceColor.White)
{
output += " w ";
}
else
{
output += " b ";
}
string castle = "-";
if (board.WhiteCastled == false)
{
if (board.Squares[60].Piece != null)
{
if (board.Squares[60].Piece.Moved == false)
{
if (board.Squares[63].Piece != null)
{
if (board.Squares[63].Piece.Moved == false)
{
castle += "K";
}
}
if (board.Squares[56].Piece != null)
{
if (board.Squares[56].Piece.Moved == false)
{
castle += "Q";
}
}
}
}
}
if (board.BlackCastled == false)
{
if (board.Squares[4].Piece != null)
{
if (board.Squares[4].Piece.Moved == false)
{
if (board.Squares[7].Piece != null)
{
if (board.Squares[7].Piece.Moved == false)
{
castle += "k";
}
}
if (board.Squares[0].Piece != null)
{
if (board.Squares[0].Piece.Moved == false)
{
castle += "q";
}
}
}
}
}
if (castle != "-")
{
castle = castle.TrimStart('-');
}
output += castle;
if (board.EnPreplacedantPosition != 0)
{
output += " " + GetColumnFromByte((byte)(board.EnPreplacedantPosition % 8)) + "" + (byte)(8 - (byte)(board.EnPreplacedantPosition / 8)) + " ";
}
else
{
output += " - ";
}
if (!boardOnly)
{
output += board.HalfMoveClock + " ";
output += board.MoveCount;
}
return output.Trim();
}
19
View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public static bool IsDirectoryPath(this string path)
{
return IsEndSlash(path?.TrimEnd());
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
{
if (ShellCommand == null || ShellCommand == "") return "";
string ShellCommandName = ShellCommand.Split(' ')[0];
string ShellCommandArguments = "";
if (ShellCommand.Contains(" "))
{
ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
}
System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
if (Username != "")
{
shellProcess.StartInfo.UserName = Username;
shellProcess.StartInfo.Domain = Domain;
System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
foreach (char c in Preplacedword)
{
SecurePreplacedword.AppendChar(c);
}
shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
}
shellProcess.StartInfo.FileName = ShellCommandName;
shellProcess.StartInfo.Arguments = ShellCommandArguments;
shellProcess.StartInfo.WorkingDirectory = Path;
shellProcess.StartInfo.UseShellExecute = false;
shellProcess.StartInfo.CreateNoWindow = true;
shellProcess.StartInfo.RedirectStandardOutput = true;
shellProcess.StartInfo.RedirectStandardError = true;
var output = new StringBuilder();
shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };
shellProcess.Start();
shellProcess.BeginOutputReadLine();
shellProcess.BeginErrorReadLine();
shellProcess.WaitForExit();
return output.ToString().TrimEnd();
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
{
if (ShellCommand == null || ShellCommand == "") return "";
string ShellCommandName = ShellCommand.Split(' ')[0];
string ShellCommandArguments = "";
if (ShellCommand.Contains(" "))
{
ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
}
System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
if (Username != "")
{
shellProcess.StartInfo.UserName = Username;
shellProcess.StartInfo.Domain = Domain;
System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
foreach (char c in Preplacedword)
{
SecurePreplacedword.AppendChar(c);
}
shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
}
shellProcess.StartInfo.FileName = ShellCommandName;
shellProcess.StartInfo.Arguments = ShellCommandArguments;
shellProcess.StartInfo.WorkingDirectory = Path;
shellProcess.StartInfo.UseShellExecute = false;
shellProcess.StartInfo.CreateNoWindow = true;
shellProcess.StartInfo.RedirectStandardOutput = true;
shellProcess.StartInfo.RedirectStandardError = true;
var output = new StringBuilder();
shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };
shellProcess.Start();
shellProcess.BeginOutputReadLine();
shellProcess.BeginErrorReadLine();
shellProcess.WaitForExit();
return output.ToString().TrimEnd();
}
19
View Source File : GameObjectExamples.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
[Route("^/object/list.json$", @"(GET|HEAD)", true)]
public static void ListGameObjects(RequestContext context) {
#if !NETFX_CORE
string json = "[";
Object[] objects = Object.FindObjectsOfType(typeof(GameObject));
foreach (Object obj in objects) {
// FIXME object names need to be escaped.. use minijson or similar
json += string.Format("\"{0}\", ", obj.name);
}
json = json.TrimEnd(new char[] { ',', ' ' }) + "]";
context.Response.WriteString(json, "application/json");
#endif
}
19
View Source File : HttpContextExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
if (string.IsNullOrWhiteSpace(csvList))
return nullOrWhitespaceInputReturnsNull ? null : new List<string>();
return csvList
.TrimEnd(',')
.Split(',')
.AsEnumerable<string>()
.Select(s => s.Trim())
.ToList();
}
19
View Source File : ConsoleProgressBar.cs
License : MIT License
Project Creator : a-luna
License : MIT License
Project Creator : a-luna
private string GetProgressBarText(double currentProgress)
{
const string singleSpace = " ";
var numBlocksCompleted = (int) (currentProgress * NumberOfBlocks);
var completedBlocks =
Enumerable.Range(0, numBlocksCompleted).Aggregate(
string.Empty,
(current, _) => current + CompletedBlock);
var incompleteBlocks =
Enumerable.Range(0, NumberOfBlocks - numBlocksCompleted).Aggregate(
string.Empty,
(current, _) => current + IncompleteBlock);
var progressBar = $"{StartBracket}{completedBlocks}{incompleteBlocks}{EndBracket}";
var percent = $"{currentProgress:P0}".PadLeft(4, '\u00a0');
var animationFrame = AnimationSequence[AnimationIndex++ % AnimationSequence.Length];
var animation = $"{animationFrame}";
progressBar = DisplayBar
? progressBar + singleSpace
: string.Empty;
percent = DisplayPercentComplete
? percent + singleSpace
: string.Empty;
if (!DisplayAnimation || currentProgress is 1)
{
animation = string.Empty;
}
return (progressBar + percent + animation).TrimEnd();
}
19
View Source File : ProCamsLensDataTable.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void LoadLensData()
{
_filmFormats = new List<FilmFormatData>();
// Load in the data from Resources/CinemaSuite_LensData.txt
Textreplacedet textreplacedet = (Textreplacedet)(Resources.Load("CinemaSuite_LensData", typeof(Textreplacedet)));
if(textreplacedet == null)
{
Debug.LogError("File 'CinemaSuite_LensData.txt' is not found in Resources folder. Unable to load lens data.");
return;
}
FilmFormatData currentFormat = null;
string[] lines = textreplacedet.text.Split("\n"[0]);
int numLines = lines.Length;
for(int i = 0; i < numLines; ++i)
{
//Debug.Log("Line: " + i + "= " + lines[i]);
string line = lines[i].Trim();
if(line.StartsWith("#"))
{
continue;
}
int length = line.Length;
if(currentFormat == null)
{
// Look for "Name="
if(line.StartsWith("Name="))
{
// New section
int index = line.IndexOf("=") + 1;
if(index < length)
{
string name = line.Substring(index).Trim();
if(name.Length != 0)
{
// Create new film format with valid name
currentFormat = new FilmFormatData();
currentFormat._formatName = name;
}
}
}
else if(length != 0)
{
Debug.LogError("Invalid data at line: " + i);
}
}
else
{
// Look for film format section entries
if(length == 0)
{
// End of section
_filmFormats.Add(currentFormat);
//Debug.Log ("Added film format " + currentFormat._formatName);
currentFormat = null;
}
else if(line.StartsWith("Aspect="))
{
int index = line.IndexOf("=") + 1;
if(index < length)
{
string strAspect = line.Substring(index).Trim();
int colon = strAspect.IndexOf(":");
if(colon > 0 && colon < length)
{
string first = strAspect.Substring(0, colon).Trim();
string second = strAspect.Substring(colon + 1).Trim();
float w = 0;
float h = 0;
if(!float.TryParse(first, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out w) || w <= 0)
{
Debug.LogError("Invalid number: " + first + " at line " + (i + 1));
return;
}
if(!float.TryParse(second, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h) || h <= 0)
{
Debug.LogError("Invalid number: " + second + " at line " + (i + 1));
return;
}
currentFormat._aspect = w / h;
//Debug.Log ("Aspect: " + currentFormat._aspect);
}
}
}
else if(line.StartsWith("ScreenSize"))
{
int index = line.IndexOf("=") + 1;
if(index < length)
{
// ScreenSize=DI,1024
string[] strSizes = line.Substring(index).Split(","[0]);
if(strSizes == null || strSizes.Length != 2)
{
Debug.LogError("Invalid screen size entry at line " + (i + 1));
return;
}
string sizeName = strSizes[0].Trim();
int sizeValue = 0;
if(!int.TryParse(strSizes[1].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out sizeValue) || sizeValue <= 0)
{
Debug.LogError("Invalid screen size at line " + (i + 1));
return;
}
currentFormat._screenSizes.Add(new ScreenSize(sizeName, sizeValue));
//Debug.Log ("Screensize: " + sizeName + ", " + sizeValue);
}
}
else if(line.StartsWith("FocalLength"))
{
int index = line.IndexOf("=") + 1;
if(index < length)
{
// FocalLength=Cooke S4/i - T2,12mm,4.980,00.000,00.000
string[] strData = line.Substring(index).Split(","[0]);
if(strData == null || strData.Length != 5)
{
Debug.LogError("Invalid data for focal length at line " + (i + 1));
return;
}
string lensKit = strData[0].Trim();
if(lensKit.Length == 0)
{
Debug.LogError("Invalid lens kit name at line " + (i + 1));
return;
}
int focal = 0;
if(!int.TryParse(strData[1].TrimEnd('m'), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out focal) || focal <= 0)
{
Debug.LogError("Invalid focal length at line " + (i + 1));
return;
}
float nodal = 0;
if(!float.TryParse(strData[2].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out nodal) || nodal < 0)
{
Debug.LogError("Invalid nodal offset at line " + (i + 1));
return;
}
float realFOV = 0;
if(!float.TryParse(strData[3].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out realFOV) || realFOV <= 0)
{
Debug.LogError("Invalid real FOV at line " + (i + 1));
return;
}
float unityFOV = 0;
if(!float.TryParse(strData[4].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out unityFOV) || unityFOV <= 0)
{
Debug.LogError("Invalid Unity FOV at line " + (i + 1));
return;
}
currentFormat.AddFocalLengthData(lensKit, focal, nodal, realFOV, unityFOV);
//Debug.Log ("Focal Data: " + lensKit + ", " + focal + ", " + nodal + ", " + realFOV + ", " + unityFOV);
}
}
}
}
}
19
View Source File : XmlFoldingStrategy.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static void CreateCommentFold(TextDoreplacedent doreplacedent, List<NewFolding> foldMarkers, XmlReader reader)
{
string comment = reader.Value;
if (comment != null) {
int firstNewLine = comment.IndexOf('\n');
if (firstNewLine >= 0) {
// Take off 4 chars to get the actual comment start (takes
// into account the <!-- chars.
int startOffset = GetOffset(doreplacedent, reader) - 4;
int endOffset = startOffset + comment.Length + 7;
string foldText = String.Concat("<!--", comment.Substring(0, firstNewLine).TrimEnd('\r'), "-->");
foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText });
}
}
}
19
View Source File : IndentationReformatter.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static bool TrimEnd(IDoreplacedentAccessor doc)
{
string line = doc.Text;
if (!Char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
19
View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static void RemoveTestingFolders()
{
// If one of the leap test directories exists, then we replacedume the rest have not been deleted
if (Directory.Exists(Path.Combine(Application.dataPath, pathDifference, pathsToDelete[0])))
{
foreach (string path in pathsToDelete)
{
// Get the full path including the path difference in case the core replacedets are not imported to the root of the project
string fullPath = Path.Combine(Application.dataPath, pathDifference, path);
// If we are deleting a specific file, then we also need to remove the meta replacedociated with the file
if (File.Exists(fullPath) && fullPath.Contains(".cs"))
{
// Delete the test files
FileUtil.DeleteFileOrDirectory(fullPath);
// Also delete the meta files
FileUtil.DeleteFileOrDirectory(fullPath + ".meta");
}
if (Directory.Exists(fullPath))
{
// Delete the test directories
FileUtil.DeleteFileOrDirectory(fullPath);
// Delete the test directories meta files
FileUtil.DeleteFileOrDirectory(fullPath.TrimEnd('/') + ".meta");
}
}
}
}
19
View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static string JsonDictionaryToArray(string json)
{
string reformatted = "{\"items\": [";
string pattern = @"""(\w+)"":\s?(""?\w+""?)";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(json, pattern, options))
{
string key = m.Groups[1].Value;
string value = m.Groups[2].Value;
reformatted += $"{{\"key\":\"{key}\", \"value\":{value}}},";
}
reformatted = reformatted.TrimEnd(',');
reformatted += "]}";
return reformatted;
}
19
View Source File : DoubleExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static string FormatChance(this double chance)
{
if (chance == 1)
{
return "100%";
}
if (chance == 0)
{
return "0%";
}
double r = (chance * 100);
string p = r.ToString("F99").TrimEnd('0');
if (!p.StartsWith("0."))
{
int extra = 2;
if (p.IndexOf(".0") > -1 || p.EndsWith("."))
{
extra = 0;
}
return p.Substring(0, p.IndexOf('.') + extra) + "%";
}
int i = p.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });
if (i < 0)
{
return "0%";
}
return p.Substring(0, i + 1) + "%";
}
19
View Source File : AdvocateCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("bestow", AccessLevel.Advocate, CommandHandlerFlag.RequiresWorld, 2,
"Sets a character's Advocate Level.",
"<name> <level>\nAdvocates can bestow any level less than their own.")]
public static void HandleBestow(Session session, params string[] parameters)
{
var charName = string.Join(" ", parameters).Trim();
var level = parameters[parameters.Length - 1];
if (!int.TryParse(level, out var advocateLevel) || advocateLevel < 1 || advocateLevel > 7)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{level} is not a valid advocate level.", ChatMessageType.Broadcast));
return;
}
var advocateName = charName.TrimEnd((" " + level).ToCharArray());
var playerToFind = PlayerManager.FindByName(advocateName);
if (playerToFind != null)
{
if (playerToFind is Player player)
{
//if (!Advocate.IsAdvocate(player))
//{
// session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not an Advocate.", ChatMessageType.Broadcast));
// return;
//}
if (player.IsPK || PropertyManager.GetBool("pk_server").Item)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} in a Player Killer and cannot be an Advocate.", ChatMessageType.Broadcast));
return;
}
if (session.Player.AdvocateLevel <= player.AdvocateLevel)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they are equal to or out rank you.", ChatMessageType.Broadcast));
return;
}
if (advocateLevel >= session.Player.AdvocateLevel && !session.Player.IsAdmin)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot bestow {playerToFind.Name}'s Advocate rank to {advocateLevel} because that is equal to or higher than your rank.", ChatMessageType.Broadcast));
return;
}
if (advocateLevel == player.AdvocateLevel)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name}'s Advocate rank is already at level {advocateLevel}.", ChatMessageType.Broadcast));
return;
}
if (!Advocate.CanAcceptAdvocateItems(player, advocateLevel))
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they do not have capacity for the advocate items.", ChatMessageType.Broadcast));
return;
}
if (Advocate.Bestow(player, advocateLevel))
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is now an Advocate, level {advocateLevel}.", ChatMessageType.Broadcast));
else
session.Network.EnqueueSend(new GameMessageSystemChat($"Advocate bestowal of {playerToFind.Name} failed.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not online. Cannot complete bestowal process.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{advocateName} was not found in the database.", ChatMessageType.Broadcast));
}
19
View Source File : CommandParameterHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
{
string parameterBlob = "";
if (rawIncluded)
{
parameterBlob = aceParsedParameters.First();
}
else
{
parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
}
int commaCount = parameterBlob.Count(x => x == ',');
List<ACECommandParameter> acps = parameters.ToList();
for (int i = acps.Count - 1; i > -1; i--)
{
ACECommandParameter acp = acps[i];
acp.ParameterNo = i + 1;
if (parameterBlob.Length > 0)
{
try
{
switch (acp.Type)
{
case ACECommandParameterType.PositiveLong:
Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match4.Success)
{
if (!long.TryParse(match4.Groups[1].Value, out long val))
{
return false;
}
if (val <= 0)
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
}
break;
case ACECommandParameterType.Long:
Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match3.Success)
{
if (!long.TryParse(match3.Groups[1].Value, out long val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.ULong:
Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match2.Success)
{
if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.Location:
Position position = null;
Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
if (match.Success)
{
string ns = match.Groups[1].Value;
string ew = match.Groups[2].Value;
if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMessage);
}
return false;
}
else
{
acp.Value = position;
acp.Defaulted = false;
int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
}
}
break;
case ACECommandParameterType.OnlinePlayerName:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer == null)
{
string errorMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
else
{
acp.Value = targetPlayer;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerNameOrIid:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
if (!parameterBlob.Contains(' '))
{
if (uint.TryParse(parameterBlob, out uint iid))
{
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {iid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
break;
}
}
}
Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer3 == null)
{
string logMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer3;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerIid:
Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
if (matcha5.Success)
{
string strIid = "";
if (matcha5.Groups[2].Success)
{
strIid = matcha5.Groups[2].Value;
}
else if (matcha5.Groups[1].Success)
{
strIid = matcha5.Groups[1].Value;
}
try
{
uint iid = 0;
if (strIid.StartsWith("0x"))
{
iid = Convert.ToUInt32(strIid, 16);
}
else
{
iid = uint.Parse(strIid);
}
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {strIid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
}
catch (Exception)
{
string errorMsg = $"Unable to parse {strIid} into a player iid";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
}
break;
case ACECommandParameterType.PlayerName:
if (i != 0)
{
throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
if (string.IsNullOrWhiteSpace(parameterBlob))
{
break;
}
else
{
acp.Value = parameterBlob;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.Uri:
Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
if (match5.Success)
{
string strUri = match5.Groups[1].Value;
try
{
Uri url = new Uri(strUri);
acp.Value = url;
acp.Defaulted = false;
parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.DoubleQuoteEnclosedText:
Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
if (match6.Success)
{
string txt = match6.Groups[1].Value;
try
{
acp.Value = txt.Trim('"');
acp.Defaulted = false;
parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.CommaPrefixedText:
if (i == 0)
{
throw new Exception("this parameter type is not appropriate as the first parameter");
}
if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
{
break;
}
Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
if (match7.Success)
{
string txt = match7.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(new char[] { ' ', ',' });
acp.Defaulted = false;
parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.SimpleWord:
Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match8.Success)
{
string txt = match8.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(' ');
acp.Defaulted = false;
parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.Enum:
if (acp.PossibleValues == null)
{
throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
}
if (!acp.PossibleValues.IsEnum)
{
throw new Exception("PossibleValues must be an enum type");
}
Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match9.Success)
{
string txt = match9.Groups[1].Value;
try
{
txt = txt.Trim(new char[] { ' ', ',' });
Array etvs = Enum.GetValues(acp.PossibleValues);
foreach (object etv in etvs)
{
if (etv.ToString().ToLower() == txt.ToLower())
{
acp.Value = etv;
acp.Defaulted = false;
parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
break;
}
}
}
catch (Exception)
{
return false;
}
}
break;
}
}
catch
{
return false;
}
}
if (acp.Defaulted)
{
acp.Value = acp.DefaultValue;
}
if (acp.Required && acp.Defaulted)
{
if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(acp.ErrorMessage);
}
}
return false;
}
}
return true;
}
19
View Source File : ClientPacket.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public override string ToString()
{
return $"<<< {Header} {HeaderOptional}".TrimEnd();
}
19
View Source File : ServerPacket.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public override string ToString()
{
var c = Header.HasFlag(PacketHeaderFlags.EncryptedChecksum) ? $" CRC: {finalChecksum} XOR: {issacXor}" : "";
return $">>> {Header}{c}".TrimEnd();
}
19
View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task<long> CopyToContainerAsync(
RunnerActionPluginExecutionContext context,
String source,
CancellationToken cancellationToken)
{
//set maxConcurrentUploads up to 2 until figure out how to use WinHttpHandler.MaxConnectionsPerServer modify DefaultConnectionLimit
int maxConcurrentUploads = Math.Min(Environment.ProcessorCount, 2);
//context.Output($"Max Concurrent Uploads {maxConcurrentUploads}");
List<String> files;
if (File.Exists(source))
{
files = new List<String>() { source };
_sourceParentDirectory = Path.GetDirectoryName(source);
}
else
{
files = Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories).ToList();
_sourceParentDirectory = source.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
context.Output($"Uploading {files.Count()} files");
using (_uploadCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
// hook up reporting event from file container client.
_fileContainerHttpClient.UploadFileReportTrace += UploadFileTraceReportReceived;
_fileContainerHttpClient.UploadFileReportProgress += UploadFileProgressReportReceived;
try
{
// try upload all files for the first time.
UploadResult uploadResult = await ParallelUploadAsync(context, files, maxConcurrentUploads, _uploadCancellationTokenSource.Token);
if (uploadResult.RetryFiles.Count == 0)
{
// all files have been upload succeed.
context.Output("File upload complete.");
return uploadResult.TotalFileSizeUploaded;
}
else
{
context.Output($"{uploadResult.RetryFiles.Count} files failed to upload, retry these files after a minute.");
}
// Delay 1 min then retry failed files.
for (int timer = 60; timer > 0; timer -= 5)
{
context.Output($"Retry file upload after {timer} seconds.");
await Task.Delay(TimeSpan.FromSeconds(5), _uploadCancellationTokenSource.Token);
}
// Retry upload all failed files.
context.Output($"Start retry {uploadResult.RetryFiles.Count} failed files upload.");
UploadResult retryUploadResult = await ParallelUploadAsync(context, uploadResult.RetryFiles, maxConcurrentUploads, _uploadCancellationTokenSource.Token);
if (retryUploadResult.RetryFiles.Count == 0)
{
// all files have been upload succeed after retry.
context.Output("File upload complete after retry.");
return uploadResult.TotalFileSizeUploaded + retryUploadResult.TotalFileSizeUploaded;
}
else
{
throw new Exception("File upload failed even after retry.");
}
}
finally
{
_fileContainerHttpClient.UploadFileReportTrace -= UploadFileTraceReportReceived;
_fileContainerHttpClient.UploadFileReportProgress -= UploadFileProgressReportReceived;
}
}
}
19
View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
{
List<string> failedFiles = new List<string>();
long uploadedSize = 0;
string fileToUpload;
Stopwatch uploadTimer = new Stopwatch();
while (_fileUploadQueue.TryDequeue(out fileToUpload))
{
token.ThrowIfCancellationRequested();
try
{
using (FileStream fs = File.Open(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.Read))
{
string itemPath = (_containerPath.TrimEnd('/') + "/" + fileToUpload.Remove(0, _sourceParentDirectory.Length + 1)).Replace('\\', '/');
bool failAndExit = false;
try
{
uploadTimer.Restart();
using (HttpResponseMessage response = await _fileContainerHttpClient.UploadFileAsync(_containerId, itemPath, fs, _projectId, cancellationToken: token, chunkSize: 4 * 1024 * 1024))
{
if (response == null || response.StatusCode != HttpStatusCode.Created)
{
context.Output($"Unable to copy file to server StatusCode={response?.StatusCode}: {response?.ReasonPhrase}. Source file path: {fileToUpload}. Target server path: {itemPath}");
if (response?.StatusCode == HttpStatusCode.Conflict)
{
// fail upload task but continue with any other files
context.Error($"Error '{fileToUpload}' has already been uploaded.");
}
else if (_fileContainerHttpClient.IsFastFailResponse(response))
{
// Fast fail: we received an http status code where we should abandon our efforts
context.Output($"Cannot continue uploading files, so draining upload queue of {_fileUploadQueue.Count} items.");
DrainUploadQueue(context);
failedFiles.Clear();
failAndExit = true;
throw new UploadFailedException($"Critical failure uploading '{fileToUpload}'");
}
else
{
context.Debug($"Adding '{fileToUpload}' to retry list.");
failedFiles.Add(fileToUpload);
}
throw new UploadFailedException($"Http failure response '{response?.StatusCode}': '{response?.ReasonPhrase}' while uploading '{fileToUpload}'");
}
uploadTimer.Stop();
context.Debug($"File: '{fileToUpload}' took {uploadTimer.ElapsedMilliseconds} milliseconds to finish upload");
uploadedSize += fs.Length;
OutputLogForFile(context, fileToUpload, $"Detail upload trace for file: {itemPath}", context.Debug);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
context.Output($"File upload has been cancelled during upload file: '{fileToUpload}'.");
throw;
}
catch (Exception ex)
{
context.Output($"Fail to upload '{fileToUpload}' due to '{ex.Message}'.");
context.Output(ex.ToString());
OutputLogForFile(context, fileToUpload, $"Detail upload trace for file that fail to upload: {itemPath}", context.Output);
if (failAndExit)
{
context.Debug("Exiting upload.");
throw;
}
}
}
Interlocked.Increment(ref _uploadFilesProcessed);
}
catch (Exception ex)
{
context.Output($"File error '{ex.Message}' when uploading file '{fileToUpload}'.");
throw ex;
}
}
return new UploadResult(failedFiles, uploadedSize);
}
19
View Source File : PipelineDirectoryManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public TrackingConfig UpdateRepositoryDirectory(
IExecutionContext executionContext,
string repositoryFullName,
string repositoryPath,
bool workspaceRepository)
{
// Validate parameters.
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNullOrEmpty(repositoryFullName, nameof(repositoryFullName));
ArgUtil.NotNullOrEmpty(repositoryPath, nameof(repositoryPath));
// we need the repository for the pipeline, since the tracking file is based on the workflow repository
var pipelineRepoFullName = executionContext.GetGitHubContext("repository");
ArgUtil.NotNullOrEmpty(pipelineRepoFullName, nameof(pipelineRepoFullName));
// Load the existing tracking file.
string trackingFile = Path.Combine(
HostContext.GetDirectory(WellKnownDirectory.Work),
Constants.Pipeline.Path.PipelineMappingDirectory,
pipelineRepoFullName,
Constants.Pipeline.Path.TrackingConfigFile);
Trace.Verbose($"Loading tracking config if exists: {trackingFile}");
var trackingManager = HostContext.GetService<ITrackingManager>();
TrackingConfig existingConfig = trackingManager.LoadIfExists(executionContext, trackingFile);
ArgUtil.NotNull(existingConfig, nameof(existingConfig));
Trace.Info($"Update repository {repositoryFullName}'s path to '{repositoryPath}'");
string pipelineDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), existingConfig.PipelineDirectory);
if (repositoryPath.StartsWith(pipelineDirectory + Path.DirectorySeparatorChar) || repositoryPath.StartsWith(pipelineDirectory + Path.AltDirectorySeparatorChar))
{
// The workspaceDirectory in tracking file is a relative path to runner's pipeline directory.
var repositoryRelativePath = repositoryPath.Substring(HostContext.GetDirectory(WellKnownDirectory.Work).Length + 1).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (!existingConfig.Repositories.ContainsKey(repositoryFullName))
{
existingConfig.Repositories[repositoryFullName] = new RepositoryTrackingConfig();
}
existingConfig.Repositories[repositoryFullName].RepositoryPath = repositoryRelativePath;
existingConfig.Repositories[repositoryFullName].LastRunOn = DateTimeOffset.Now;
if (workspaceRepository)
{
Trace.Info($"Update workspace to '{repositoryPath}'");
existingConfig.WorkspaceDirectory = repositoryRelativePath;
executionContext.SetGitHubContext("workspace", repositoryPath);
}
// Update the tracking config files.
Trace.Info("Updating repository tracking.");
trackingManager.Update(executionContext, existingConfig, trackingFile);
return existingConfig;
}
else
{
throw new ArgumentException($"Repository path '{repositoryPath}' should be located under runner's pipeline directory '{pipelineDirectory}'.");
}
}
19
View Source File : ScriptHandler.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public override void PrintActionDetails(ActionRunStage stage)
{
if (stage == ActionRunStage.Post)
{
throw new NotSupportedException("Script action should not have 'Post' job action.");
}
Inputs.TryGetValue("script", out string contents);
contents = contents ?? string.Empty;
if (Action.Type == Pipelines.ActionSourceType.Script)
{
var firstLine = contents.TrimStart(' ', '\t', '\r', '\n');
var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
if (firstNewLine >= 0)
{
firstLine = firstLine.Substring(0, firstNewLine);
}
ExecutionContext.Output($"##[group]Run {firstLine}");
}
else
{
throw new InvalidOperationException($"Invalid action type {Action.Type} for {nameof(ScriptHandler)}");
}
var multiLines = contents.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
foreach (var line in multiLines)
{
// Bright Cyan color
ExecutionContext.Output($"\x1b[36;1m{line}\x1b[0m");
}
string argFormat;
string shellCommand;
string shellCommandPath = null;
bool validateShellOnHost = !(StepHost is ContainerStepHost);
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{
// TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
runDefaults.TryGetValue("shell", out shell);
}
}
if (string.IsNullOrEmpty(shell))
{
#if OS_WINDOWS
shellCommand = "pwsh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
if (string.IsNullOrEmpty(shellCommandPath))
{
shellCommand = "powershell";
Trace.Info($"Defaulting to {shellCommand}");
shellCommandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
}
}
#else
shellCommand = "sh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
}
#endif
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
else
{
var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
shellCommand = parsed.shellCommand;
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(parsed.shellCommand, true, Trace, prependPath);
}
argFormat = $"{parsed.shellArgs}".TrimStart();
if (string.IsNullOrEmpty(argFormat))
{
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
}
if (!string.IsNullOrEmpty(shellCommandPath))
{
ExecutionContext.Output($"shell: {shellCommandPath} {argFormat}");
}
else
{
ExecutionContext.Output($"shell: {shellCommand} {argFormat}");
}
if (this.Environment?.Count > 0)
{
ExecutionContext.Output("env:");
foreach (var env in this.Environment)
{
ExecutionContext.Output($" {env.Key}: {env.Value}");
}
}
ExecutionContext.Output("##[endgroup]");
}
19
View Source File : VssFileStorage.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public string PathKeyCombine(params string[] paths)
{
StringBuilder combinedPath = new StringBuilder();
foreach (string segment in paths)
{
if (segment != null)
{
string trimmedSegment = segment.TrimEnd(PathSeparator);
if (trimmedSegment.Length > 0)
{
if (combinedPath.Length > 0)
{
combinedPath.Append(PathSeparator);
}
combinedPath.Append(trimmedSegment);
}
}
}
return combinedPath.ToString();
}
19
View Source File : PathUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static String Combine(String path1, String path2)
{
if (String.IsNullOrEmpty(path1))
{
return path2;
}
if (String.IsNullOrEmpty(path2))
{
return path1;
}
Char separator = path1.Contains("/") ? '/' : '\\';
Char[] trimChars = new Char[] { '\\', '/' };
return path1.TrimEnd(trimChars) + separator.ToString() + path2.TrimStart(trimChars);
}
19
View Source File : LocationCacheManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void LoadServicesData(LocationServiceData locationServiceData, Boolean allServicesIncluded)
{
m_accessLock.EnterWriteLock();
try
{
// If the server is telling us our client cache isn't fresh and we agree
// with it, clear the storage. The reason we check to see if we agree with it
// is that because of the way we cache based on filters, we may sometimes
// tell the server that our last change id is -1 because we don't have a given
// filter cached. In this case, the server will tell us our cache is out of
// date even though it isn't.
if (!locationServiceData.ClientCacheFresh && locationServiceData.LastChangeId != m_lastChangeId)
{
m_accessMappings = new Dictionary<String, AccessMapping>(VssStringComparer.AccessMappingMoniker);
m_services = new Dictionary<String, Dictionary<Guid, ServiceDefinition>>(VssStringComparer.ServiceType);
m_cachedMisses = new HashSet<String>(VssStringComparer.ServiceType);
m_lastChangeId = -1;
m_cacheExpirationDate = DateTime.MinValue;
}
else
{
EnsureDiskCacheLoadedHelper();
}
// We have to update the lastChangeId outside of the above if check because there
// are cases such as a register service where we cause the lastChangeId to be incremented
// and our cache isn't out of date.
SetLastChangeId(locationServiceData.LastChangeId, allServicesIncluded);
// Use the client value if provided (this lets clients override the server)
// otherwise just use the server specified TTL.
Int32 clientCacheTimeToLive = (ClientCacheTimeToLive != null) ? ClientCacheTimeToLive.Value : locationServiceData.ClientCacheTimeToLive;
m_cacheExpirationDate = DateTime.UtcNow.AddSeconds(clientCacheTimeToLive);
ICollection<AccessMapping> accessMappings = locationServiceData.AccessMappings;
if (accessMappings != null && accessMappings.Count > 0)
{
// Get all of the access mappings
foreach (AccessMapping accessMapping in accessMappings)
{
// We can't remove this compat code from the client library yet since
// we still support newer clients talking to older TFS servers
// which might not send VirtualDirectory
// Older server means earlier than TFS 2015 CU2
if (accessMapping.VirtualDirectory == null &&
!String.IsNullOrEmpty(WebApplicationRelativeDirectory))
{
String absoluteUriTrimmed = accessMapping.AccessPoint.TrimEnd('/');
String relativeDirectoryTrimmed = WebApplicationRelativeDirectory.TrimEnd('/');
if (VssStringComparer.ServerUrl.EndsWith(absoluteUriTrimmed, relativeDirectoryTrimmed))
{
accessMapping.AccessPoint = absoluteUriTrimmed.Substring(0, absoluteUriTrimmed.Length - relativeDirectoryTrimmed.Length);
}
}
// if we can find it, update the values so the objects that reference this
// access mapping are updated as well
AccessMapping existingAccessMapping;
if (m_accessMappings.TryGetValue(accessMapping.Moniker, out existingAccessMapping))
{
existingAccessMapping.DisplayName = accessMapping.DisplayName;
existingAccessMapping.AccessPoint = accessMapping.AccessPoint;
existingAccessMapping.VirtualDirectory = accessMapping.VirtualDirectory;
}
else
{
// We didn't find it, so just set it
existingAccessMapping = accessMapping;
m_accessMappings[accessMapping.Moniker] = accessMapping;
}
}
DetermineClientAndDefaultZones(locationServiceData.DefaultAccessMappingMoniker);
}
if (locationServiceData.ServiceDefinitions != null)
{
// Get all of the services
foreach (ServiceDefinition definition in locationServiceData.ServiceDefinitions)
{
Dictionary<Guid, ServiceDefinition> definitions = null;
if (!m_services.TryGetValue(definition.ServiceType, out definitions))
{
definitions = new Dictionary<Guid, ServiceDefinition>();
m_services[definition.ServiceType] = definitions;
}
definitions[definition.Identifier] = definition;
}
}
// Even if the cache file wasn't previously available, let's give ourselves another opportunity to update the cache.
m_cacheAvailable = true;
WriteCacheToDisk();
}
finally
{
Debug.replacedert(m_lastChangeId == -1 || m_services.Count > 0);
m_accessLock.ExitWriteLock();
}
}
19
View Source File : LocationCacheManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void DetermineClientAndDefaultZones(String defaultAccessMappingMoniker)
{
Debug.replacedert(m_accessLock.IsWriteLockHeld);
m_defaultAccessMapping = null;
m_clientAccessMapping = null;
// For comparisons below we MUST use .ToString() here instead of .AbsoluteUri. .AbsoluteUri will return the path
// portion of the query string as encoded if it contains characters that are unicode, .ToString()
// will not return them encoded. We must not have them encoded so that the comparison below works
// correctly. Also, we do not need to worry about the downfalls of using ToString() instead of AbsoluteUri
// here because any urls that are generated with the generated access point will be placed back into a
// Uri object before they are used in a web request.
String relativeDirectoryTrimmed = (WebApplicationRelativeDirectory != null) ? WebApplicationRelativeDirectory.TrimEnd('/') : String.Empty;
foreach (AccessMapping accessMapping in m_accessMappings.Values)
{
if (VssStringComparer.ServerUrl.StartsWith(m_connectionBaseUrl.ToString(), accessMapping.AccessPoint.TrimEnd('/')) &&
(accessMapping.VirtualDirectory == null ||
VssStringComparer.UrlPath.Equals(accessMapping.VirtualDirectory, relativeDirectoryTrimmed)))
{
m_clientAccessMapping = accessMapping;
}
}
m_defaultAccessMapping = m_accessMappings[defaultAccessMappingMoniker];
if (m_clientAccessMapping == null)
{
String accessPoint = m_connectionBaseUrl.ToString().TrimEnd('/');
String virtualDirectory = String.Empty;
if (!String.IsNullOrEmpty(WebApplicationRelativeDirectory))
{
if (VssStringComparer.ServerUrl.EndsWith(accessPoint, relativeDirectoryTrimmed))
{
accessPoint = accessPoint.Substring(0, accessPoint.Length - relativeDirectoryTrimmed.Length);
virtualDirectory = relativeDirectoryTrimmed;
}
}
// Looks like we are in an unregistered zone, make up our own.
m_clientAccessMapping = new AccessMapping()
{
Moniker = accessPoint,
DisplayName = accessPoint,
AccessPoint = accessPoint,
VirtualDirectory = virtualDirectory
};
}
}
19
View Source File : VssHttpUriUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri ConcatUri(Uri baseUri, String relativeUri)
{
StringBuilder sbCombined = new StringBuilder(baseUri.GetLeftPart(UriPartial.Path).TrimEnd('/'));
sbCombined.Append('/');
sbCombined.Append(relativeUri.TrimStart('/'));
sbCombined.Append(baseUri.Query);
return new Uri(sbCombined.ToString());
}
19
View Source File : DotnetsdkDownloadScriptL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async Task EnsureDotnetsdkBashDownloadScriptUpToDate()
{
if ((DateTime.UtcNow.Month - 1) % 3 != 0)
{
// Only check these script once a quater.
return;
}
string shDownloadUrl = "https://dot.net/v1/dotnet-install.sh";
using (HttpClient downloadClient = new HttpClient())
{
var response = await downloadClient.GetAsync("https://www.bing.com");
if (!response.IsSuccessStatusCode)
{
return;
}
string shScript = await downloadClient.GetStringAsync(shDownloadUrl);
string existingShScript = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(), "Misc/dotnet-install.sh"));
bool shScriptMatched = string.Equals(shScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingShScript.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"));
//replacedert.True(shScriptMatched, "Fix the test by updating Src/Misc/dotnet-install.sh with content from https://dot.net/v1/dotnet-install.sh");
}
}
19
View Source File : DotnetsdkDownloadScriptL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
public async Task EnsureDotnetsdkPowershellDownloadScriptUpToDate()
{
if ((DateTime.UtcNow.Month - 1) % 3 != 0)
{
// Only check these script once a quater.
return;
}
string ps1DownloadUrl = "https://dot.net/v1/dotnet-install.ps1";
using (HttpClient downloadClient = new HttpClient())
{
var response = await downloadClient.GetAsync("https://www.bing.com");
if (!response.IsSuccessStatusCode)
{
return;
}
string ps1Script = await downloadClient.GetStringAsync(ps1DownloadUrl);
string existingPs1Script = File.ReadAllText(Path.Combine(TestUtil.GetSrcPath(), "Misc/dotnet-install.ps1"));
bool ps1ScriptMatched = string.Equals(ps1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"), existingPs1Script.TrimEnd('\n', '\r', '\0').Replace("\r\n", "\n").Replace("\r", "\n"));
//replacedert.True(ps1ScriptMatched, "Fix the test by updating Src/Misc/dotnet-install.ps1 with content from https://dot.net/v1/dotnet-install.ps1");
}
}
19
View Source File : CustomShellService.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private string CombineCloudStorageParsingNames(params string[] relativeParsingNames) {
if (relativeParsingNames is null || relativeParsingNames.Length == 0)
return null;
string parsingName = relativeParsingNames[0].TrimEnd(CloudStorageParsingNameSeparator.ToCharArray());
for (int i = 1; i < relativeParsingNames.Length; i++) {
parsingName += CloudStorageParsingNameSeparator + relativeParsingNames[i].Trim(CloudStorageParsingNameSeparator.ToCharArray());
}
return parsingName;
}
19
View Source File : CustomTreeListBoxItemAdapter.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private static string JoinItemFullPaths(TreeListBox toolboxControl, IEnumerable<object> items) {
var fullPaths = new StringBuilder();
foreach (var item in items)
fullPaths.Append(toolboxControl.GetFullPath(item)).Append('\n');
return fullPaths.ToString().TrimEnd();
}
19
View Source File : BankIdSupportedDeviceOsVersion.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
public override string ToString()
{
return $"{MajorVersion}.{MinorVersion}.{Patch}".TrimEnd('.');
}
19
View Source File : BqlFormatterTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private string Normalize(string text)
{
return String.Join(EndOfLine,
text
.Split(new[] { EndOfLine }, StringSplitOptions.None)
.Select(line => line.TrimEnd()));
}
19
View Source File : ChangeEventHandlerSignatureToGenericRefactoring.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private (string DacName, string FieldName) ParseMethodName(string methodName, EventType eventType)
{
var match = Regex.Match(methodName, @"([\w-[_]]+)_(\w+_){0,1}" + eventType,
RegexOptions.CultureInvariant | RegexOptions.Singleline);
if (match.Success)
{
string dacName = match.Groups[1].Value;
string fieldName = match.Groups[2].Success ? match.Groups[2].Value.TrimEnd('_') : null;
if (!String.IsNullOrEmpty(fieldName))
fieldName = Char.ToLowerInvariant(fieldName[0]) + fieldName.Substring(1, fieldName.Length - 1);
return (dacName, fieldName);
}
return (null, null);
}
19
View Source File : PXRegexColorizerTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void GetBQLOperandTags(ITextSnapshot newSnapshot, string bqlCommand, int offset)
{
var matches = RegExpressions.DacOperandRegex.Matches(bqlCommand);
foreach (Match bqlOperandMatch in matches.OfType<Match>().Skip(1))
{
string bqlOperand = bqlOperandMatch.Value.TrimEnd('<');
CreateTag(newSnapshot, bqlOperandMatch, offset, bqlOperand, Provider[PXCodeType.BqlOperator]);
}
}
19
View Source File : PXRegexColorizerTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void GetFieldTag(ITextSnapshot newSnapshot, Match match, int offset, string[] dacParts)
{
string fieldPart = dacParts[1].TrimEnd(',', '>');
CreateTag(newSnapshot, match, offset, fieldPart, Provider[PXCodeType.DacField]);
}
19
View Source File : ParamsHelper.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private static List<string> GetKeyParamtersInternal(string source)
{
var keyArray = new List<string>();
//获取key中附带的参数,格式:用 {} 包裹
var matchs = Regex.Matches(source, @"\{\w*\" + Separator + @"?\w*\}", RegexOptions.None);
foreach (Match match in matchs)
{
if (!match.Success)
{
continue;
}
keyArray.Add(match.Value.TrimStart('{').TrimEnd('}'));
}
return keyArray;
}
19
View Source File : Parser.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private static IEnumerable<string> GetUsingNamespaces(IEnumerable<string> lines)
{
const string start = Program.DirectiveMarker + "using";
lines = lines.Where(l => l.StartsWith(start, StringComparison.InvariantCulture));
// TODO error if no semicolon
return lines.Select(l => l.Substring(start.Length).TrimEnd(';').Trim());
}
19
View Source File : Parser.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private static string? GetConfig(IEnumerable<string> lines, string config)
{
var start = Program.DirectiveMarker + config;
var line = lines.SingleOrDefault(l => l.StartsWith(start, StringComparison.InvariantCulture));
line = line?.Substring(start.Length);
line = line?.TrimEnd(';'); // TODO error if no semicolon
line = line?.Trim();
return line;
}
See More Examples