Here are the examples of the csharp api string.Split(string[], int, System.StringSplitOptions) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2566 Examples
19
View Source File : CelesteNetTCPUDPConnection.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void ReadTeapot(out string[] features, out uint token) {
features = Dummy<string>.EmptyArray;
token = 0;
using StreamReader reader = new(TCPReaderStream, Encoding.UTF8, false, 1024, true);
for (string line; !string.IsNullOrWhiteSpace(line = reader?.ReadLine() ?? "");) {
if (line.StartsWith(CelesteNetUtils.HTTPTeapotConFeatures)) {
features = line.Substring(CelesteNetUtils.HTTPTeapotConFeatures.Length).Trim().Split(CelesteNetUtils.ConnectionFeatureSeparators);
}
if (line.StartsWith(CelesteNetUtils.HTTPTeapotConToken)) {
token = uint.Parse(line.Substring(CelesteNetUtils.HTTPTeapotConToken.Length).Trim());
}
}
}
19
View Source File : ChatModule.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void Handle(CelesteNetConnection? con, DataChat msg) {
if (PrepareAndLog(con, msg) == null)
return;
if ((!msg.CreatedByServer || msg.Player == null) && msg.Text.StartsWith(Settings.CommandPrefix)) {
if (msg.Player != null) {
// Player should at least receive msg ack.
msg.Color = Settings.ColorCommand;
msg.Target = msg.Player;
ForceSend(msg);
}
// TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).
ChatCMDEnv env = new(this, msg);
string cmdName = env.FullText.Substring(Settings.CommandPrefix.Length);
cmdName = cmdName.Split(ChatCMD.NameDelimiters)[0].ToLowerInvariant();
if (cmdName.Length == 0)
return;
ChatCMD? cmd = Commands.Get(cmdName);
if (cmd != null) {
env.Cmd = cmd;
Task.Run(() => {
try {
cmd.ParseAndRun(env);
} catch (Exception e) {
env.Error(e);
}
});
} else {
env.Send($"Command {cmdName} not found!", color: Settings.ColorError);
}
return;
}
if (msg.Player != null && Server.PlayersByID.TryGetValue(msg.Player.ID, out CelesteNetPlayerSession? session) &&
Server.UserData.Load<UserChatSettings>(session.UID).AutoChannelChat) {
msg.Target = msg.Player;
Commands.Get<ChatCMDChannelChat>().ParseAndRun(new ChatCMDEnv(this, msg));
return;
}
Server.BroadcastAsync(msg);
}
19
View Source File : MyGui.cs
License : MIT License
Project Creator : 31
License : MIT License
Project Creator : 31
public void LineEdit_text_entered(string text)
{
AddLineBox.Text = string.Empty;
TreeItem checkRoot = _root;
var dirParts = text.Split("/");
foreach (var dirPart in dirParts)
{
TreeItem nest = null;
TreeItem check = checkRoot.GetChildren();
while (check != null)
{
if (check.GetText(0) == dirPart)
{
nest = check;
}
check = check.GetNext();
}
if (nest is null)
{
nest = _myTree.CreateItem(checkRoot);
nest.SetText(0, dirPart);
}
checkRoot = nest;
}
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static void Main(string[] args)
{
int ruleCount = 0;
int gradientMax = 0;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
LoadConfig(o);
if (!o.Suricata)
{
LoadMismatchSearchMatrix(o);
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
{
try
{
var dict = DeserializeYamlFile(ruleFilePath, o);
if (dict != null && dict.ContainsKey("tags"))
{
ruleCount++;
var tags = dict["tags"];
var categories = new List<string>();
string lastEntry = null;
foreach (string tag in tags)
{
//If its the technique id entry, then this adds the file name to the techniques map
if (tag.ToLower().StartsWith("attack.t"))
{
var techniqueId = tag.Replace("attack.", "").ToUpper();
if (!techniques.ContainsKey(techniqueId))
techniques[techniqueId] = new List<string>();
techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
if (techniques.Count > gradientMax)
gradientMax = techniques.Count;
//then if there are any categories so far, it checks for a mismatch for each one
if (categories.Count > 0 && o.Warning)
{
foreach (string category in categories)
if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
}
}
else
{
//if its the start of a new technique block, then clean categories and adds first category
if (lastEntry == null || lastEntry.StartsWith("attack.t"))
categories = new List<string>();
categories.Add(
tag.Replace("attack.", "")
.Replace("_", "-")
.ToLower());
}
lastEntry = tag;
}
}
}
catch (YamlException e)
{
Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
}
}
WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
PrintWarnings();
}
else
{
List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
{
res.Add(ParseRuleFile(ruleFilePath));
}
WriteSuricataFileResult(o,
res
.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key,
group => group.SelectMany(list => list).ToList()));
}
});
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static void WriteSigmaFileResult(Options o, int gradientMax, int ruleCount, Dictionary<string, List<string>> techniques)
{
try
{
var entries = techniques
.ToList()
.Select(entry => new
{
techniqueID = entry.Key,
score = entry.Value.Count,
comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
});
string filename = o.OutFile.EndsWith(".json") ? "sigma-coverage.json" : $"{o.OutFile}.json";
File.WriteAllText(filename, JsonConvert.SerializeObject(new
{
domain = "mitre-enterprise",
name = "Sigma signatures coverage",
gradient = new
{
colors = new[] { "#a0eab5", "#0f480f" },
maxValue = gradientMax,
minValue = 0
},
version = "4.2",
techniques = entries
}, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}));
Console.WriteLine($"[*] Layer file written in {filename} ({ruleCount} rules)");
}
catch (Exception e)
{
Console.WriteLine("Problem writing to file: " + e.Message);
}
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static void WriteSuricataFileResult(Options o, Dictionary<string, List<string>> techniques)
{
try
{
var entries = techniques
.ToList()
.Select(entry => new
{
techniqueID = entry.Key,
score = entry.Value.Count,
comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
});
string filename = o.OutFile.EndsWith(".json") ? "suricata-coverage.json" : $"{o.OutFile}.json";
File.WriteAllText(filename, JsonConvert.SerializeObject(new
{
domain = "mitre-enterprise",
name = "Suricata rules coverage",
gradient = new
{
colors = new[] { "#a0eab5", "#0f480f" },
maxValue = techniques
.Values
.Max(x => x.Count),
minValue = 0
},
version = "4.2",
techniques = entries
}, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}));
Console.WriteLine($"[*] Layer file written in {filename} ({entries.Count()} techniques covered)");
}
catch (Exception e)
{
Console.WriteLine("Problem writing to file: " + e.Message);
}
}
19
View Source File : SlackSender.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)
{
string ts;
try
{
if (memoryCache.TryGetValue(path, out var temp))
{
ts = await SendAlert(path.Split("/")[1], res, sourceIp, temp.ToString());
return _sender.GenerateSlackLink(ts);
}
ts = await SendAlert(path.Split("/")[1], res, sourceIp);
memoryCache.Set(path + "/" + guid, ts, new TimeSpan(0, 1, 0));
return _sender.GenerateSlackLink(ts);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
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 : Program.cs
License : MIT License
Project Creator : 8bitbytes
License : MIT License
Project Creator : 8bitbytes
private static void processCommand(string command)
{
var fgRestore = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
var cmdPart = command.Split(" ");
switch (cmdPart[0])
{
case "command":
{
Console.WriteLine("Ready to start accepting commands");
break;
}
case "takeoff":
{
Console.WriteLine("Initiating auto take off");
break;
}
case "land":
{
Console.WriteLine("Initiating auto landing");
break;
}
case "up":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move up. Up value not provided");
break;
}
Console.WriteLine($"Moving aricraft up {cmdPart[1]} cm");
break;
}
case "down":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move down. down value not provided");
break;
}
Console.WriteLine($"Moving aricraft down {cmdPart[1]} cm");
break;
}
case "left":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move left. Left value not provided");
break;
}
Console.WriteLine($"Moving aricraft left {cmdPart[1]} cm");
break;
}
case "right":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move right. Right value not provided");
break;
}
Console.WriteLine($"Moving aricraft right {cmdPart[1]} cm");
break;
}
case "forward":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move forward. Forward value not provided");
break;
}
Console.WriteLine($"Moving aricraft forward {cmdPart[1]} cm");
break;
}
case "back":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot move back. Back value not provided");
break;
}
Console.WriteLine($"Moving aricraft back {cmdPart[1]} cm");
break;
}
case "cw":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot rotate clockwise. Degree value not provided");
break;
}
Console.WriteLine($"Moving aricraft clockwise {cmdPart[1]} degrees");
break;
}
case "ccw":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot rotate counter-clockwise. Degree value not provided");
break;
}
Console.WriteLine($"Moving aricraft counter-clockwise {cmdPart[1]} degrees");
break;
}
case "flip":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot flip. Flip direction not provided");
break;
}
Console.WriteLine($"Flipping aricraft {cmdPart[1]}");
break;
}
case "speed":
{
if (cmdPart.Length == 1)
{
writeErrorMessage("Cannot set speed. Speed not provided");
break;
}
speed = Convert.ToInt32(cmdPart[1]);
Console.WriteLine($"Setting aircraft speed to {cmdPart[1]} cm/s");
break;
}
}
Console.ForegroundColor = fgRestore;
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<String> ImportMacroPattern(List<string> macrosToImport)
{
List<string> importedMacros = new List<string>();
foreach (var macro in macrosToImport)
{
List<string> cellContent = macro.Split(";").ToList();
//Replace the single ; separator with an unlikely separator like ;;;;; since shellcode can contain a single ;
string importedMacro = string.Join(MacroColumnSeparator, cellContent.Select(ImportCellFormula));
importedMacros.Add(importedMacro);
}
return importedMacros;
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static string ReplaceSelectActiveCellFormula(string cellFormula, string variableName = DefaultVariableName)
{
if (cellFormula.Contains("ACTIVE.CELL()"))
{
cellFormula = cellFormula.Replace("ACTIVE.CELL()", variableName);
}
string selectRegex = @"=SELECT\(.*?\)";
string selectRelativeRegex = @"=SELECT\(.*(R(\[\d+\]){0,1}C(\[\d+\]){0,1}).*?\)";
Regex sRegex = new Regex(selectRegex);
Regex srRegex = new Regex(selectRelativeRegex);
Match sRegexMatch = sRegex.Match(cellFormula);
if (sRegexMatch.Success)
{
Match srRegexMatch = srRegex.Match(cellFormula);
string selectStringMatch = sRegexMatch.Value;
//We have a line like =SELECT(,"R[1]C")
if (srRegexMatch.Success)
{
string relAddress = srRegexMatch.Groups[1].Value;
string relReplace = cellFormula.Replace(selectStringMatch,
string.Format("{0}=ABSREF(\"{1}\",{0})", variableName, relAddress));
return relReplace;
}
//We have a line like =SELECT(B1:B111,B1)
else
{
string targetCell = selectStringMatch.Split(",").Last().Split(')').First();
string varreplacedign = cellFormula.Replace(selectStringMatch,
string.Format("{0}={1}", variableName, targetCell));
return varreplacedign;
}
}
return cellFormula;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<BiffRecord> ConvertStringsToRecords_NoLoader(List<string> strings, int rwStart, int colStart, int dstRwStart, int dstColStart,
int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
{
List<BiffRecord> formulaList = new List<BiffRecord>();
int curRow = rwStart;
int curCol = colStart;
int dstCurRow = dstRwStart;
int dstCurCol = dstColStart;
//TODO [Anti-replacedysis] Break generated formula apart with different RUN()/GOTO() actions
foreach (string str in strings)
{
string[] rowStrings = str.Split(MacroPatterns.MacroColumnSeparator);
List<BiffRecord> stringFormulas = new List<BiffRecord>();
for (int colOffset = 0; colOffset < rowStrings.Length; colOffset += 1)
{
//Skip empty strings
if (rowStrings[colOffset].Trim().Length == 0)
continue;
var formulas = ConvertStringToFormulas(rowStrings[colOffset], curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod);
stringFormulas.AddRange(formulas);
curRow += formulas.Count;
}
dstCurRow += 1;
formulaList.AddRange(stringFormulas);
}
return formulaList;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<BiffRecord> ConvertStringsToRecords(List<string> strings, int rwStart, int colStart, int dstRwStart, int dstColStart,
int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
{
List<BiffRecord> formulaList = new List<BiffRecord>();
int curRow = rwStart;
int curCol = colStart;
int dstCurRow = dstRwStart;
int dstCurCol = dstColStart;
//TODO [Anti-replacedysis] Break generated formula apart with different RUN()/GOTO() actions
foreach (string str in strings)
{
string[] rowStrings = str.Split(MacroPatterns.MacroColumnSeparator);
List<BiffRecord> stringFormulas = new List<BiffRecord>();
for (int colOffset = 0; colOffset < rowStrings.Length; colOffset += 1)
{
//Skip empty strings
if (rowStrings[colOffset].Trim().Length == 0)
{
continue;
}
string rowString = rowStrings[colOffset];
int maxCellLength = 0x2000;
//One Char can take up to 8 bytes
int concatCharLength = 8;
List<BiffRecord> formulas;
if ((rowString.Length * concatCharLength) > maxCellLength)
{
//Given that the max actual length for a cell is 255 bytes, this is unlikely to ever be used,
//but the logic is being kept in case there are edge cases or there ends up being a workaround
//for the limitation
List<string> chunks = rowString.SplitStringIntoChunks(250);
formulas = ConvertChunkedStringToFormulas(chunks, curRow, curCol, dstCurRow, dstCurCol, ixfe, packingMethod);
}
else
{
string curString = rowStrings[colOffset];
//If the string is technically 255 bytes, but needs additional encoding, we break it into two parts:
//ex: "=123456" becomes "=CHAR(=)&CHAR(1)&CHAR(2)&CHAR(3)&RandomCell" and =RandomVarName&"456"
if (curString.StartsWith(FormulaHelper.TOOLONGMARKER))
{
formulas = ConvertMaxLengthStringToFormulas(curString, curRow, curCol, dstCurRow,
dstCurCol + colOffset, ixfe, packingMethod);
}
else
{
formulas = ConvertStringToFormulas(rowStrings[colOffset], curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod);
}
}
stringFormulas.AddRange(formulas);
//If we're starting to get close to the max rowcount (0xFFFF in XLS), then move to the next row
if (curRow > 0xE000)
{
Formula nextRowFormula = FormulaHelper.GetGotoFormulaForCell(curRow + formulas.Count, curCol, 0, curCol + 1);
stringFormulas.Add(nextRowFormula);
curRow = 0;
curCol += 1;
}
else
{
curRow += formulas.Count;
}
}
dstCurRow += 1;
formulaList.AddRange(stringFormulas);
}
return formulaList;
}
19
View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private replacedembly Missing_replacedemblyResolver(object sender, ResolveEventArgs args)
{
// var asm = args.Name.Split(",")[0];
var asm = args.Requestingreplacedembly.FullName.Split(",")[0];
var a = replacedembly.Load(asm);
return a;
}
19
View Source File : ServiceContext.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public void Logined()
{
if (IntruderKeys != null)
{
if (Player.IntruderKeys == null) Player.IntruderKeys = "";
var lks = Player.IntruderKeys.Split("@@@")
.Where(k => k.Length > 3)
.ToList();
var add = IntruderKeys.Split("@@@")
.Where(k => k.Length > 3)
.Where(k => !lks.Contains(k))
.ToList();
if (add.Count > 0) Player.IntruderKeys = lks.Union(add).Aggregate((r, k) => r + "@@@" + k);
}
}
19
View Source File : RectangleSelection.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException("newText");
using (textArea.Doreplacedent.RunUpdate()) {
TextViewPosition start = new TextViewPosition(doreplacedent.GetLocation(topLeftOffset), GetVisualColumnFromXPos(startLine, startXPos));
TextViewPosition end = new TextViewPosition(doreplacedent.GetLocation(bottomRightOffset), GetVisualColumnFromXPos(endLine, endXPos));
int insertionLength;
int totalInsertionLength = 0;
int firstInsertionLength = 0;
int editOffset = Math.Min(topLeftOffset, bottomRightOffset);
TextViewPosition pos;
if (NewLineFinder.NextNewLine(newText, 0) == SimpleSegment.Invalid) {
// insert same text into every line
foreach (SelectionSegment lineSegment in this.Segments.Reverse()) {
ReplaceSingleLineText(textArea, lineSegment, newText, out insertionLength);
totalInsertionLength += insertionLength;
firstInsertionLength = insertionLength;
}
int newEndOffset = editOffset + totalInsertionLength;
pos = new TextViewPosition(doreplacedent.GetLocation(editOffset + firstInsertionLength));
textArea.Selection = new RectangleSelection(textArea, pos, Math.Max(startLine, endLine), GetXPos(textArea, pos));
} else {
string[] lines = newText.Split(NewLineFinder.NewlineStrings, segments.Count, StringSplitOptions.None);
int line = Math.Min(startLine, endLine);
for (int i = lines.Length - 1; i >= 0; i--) {
ReplaceSingleLineText(textArea, segments[i], lines[i], out insertionLength);
firstInsertionLength = insertionLength;
}
pos = new TextViewPosition(doreplacedent.GetLocation(editOffset + firstInsertionLength));
textArea.ClearSelection();
}
textArea.Caret.Position = textArea.TextView.GetPosition(new Point(GetXPos(textArea, pos), textArea.TextView.GetVisualTopByDoreplacedentLine(Math.Max(startLine, endLine)))).GetValueOrDefault();
}
}
19
View Source File : Parser.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
static Process Parse(int pid, string source) {
var items = source.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var arrival = int.Parse(items[0]);
var list = new Queue<Burst>();
for (var i = 2; i < items.Length; i++) {
var type = i % 2 == 0 ? Resource.CPU : Resource.IO;
var duration = int.Parse(items[i]);
list.Enqueue(new Burst(type, duration));
}
return new Process(pid, list, arrival);
}
19
View Source File : CategoryBuilder.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static Category FromString(string source)
{
return new Category { Items = source.Split('/', StringSplitOptions.RemoveEmptyEntries) };
}
19
View Source File : FeatureBuilder.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static Feature FromString(string source)
{
return new Feature { Items = source.Split(',', StringSplitOptions.RemoveEmptyEntries) };
}
19
View Source File : KeywordBuilder.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static Keyword FromString(string source)
{
return new Keyword { Items = source.Split(';', StringSplitOptions.RemoveEmptyEntries) };
}
19
View Source File : MarkdownRenderService.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
static string? MediaLink(Uri uri)
{
string path = uri.AbsolutePath;
var items = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (items.Length >= 2 && items[0] is "video")
{
return $"//player.bilibili.com/player.html?bvid={items[1]}";
}
else
{
return null;
}
}
19
View Source File : ObjectTextual.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static (TMeta, string) Parse<TMeta>(string rawText) where TMeta : new()
{
TMeta meta = new TMeta();
var lines = rawText.Replace("\r\n", "\n").Replace("\r", "\n").Split("\n");
int contentBg = 0;
if (lines.Length > 0)
{
if (lines[0] is MetaSplitter)
{
int l = 1, r = 1;
for (; r < lines.Length; r++)
{
if (lines[r] == lines[0])
break;
}
var metastr = string.Join('\n', lines[l..r]);
contentBg = r;
try
{
meta = YamlDeserializer.Deserialize<TMeta>(metastr);
}
catch (Exception ex)
{
throw new Exception("Failed to parse metadata.", ex);
}
}
else
{
contentBg = -1;
}
}
if (contentBg + 1 < lines.Length)
{
var datastr = string.Join('\n', lines[(contentBg + 1)..]);
return (meta, datastr);
}
else
{
return (meta, string.Empty);
}
}
19
View Source File : TokenGenerator.cs
License : MIT License
Project Creator : Accedia
License : MIT License
Project Creator : Accedia
public string GetFormattedPrivateKey(string keyString)
{
StringBuilder cleanedKey = new StringBuilder();
var keyLines = keyString.Split(GlobalConstants.NewLineSeparators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < keyLines.Length; i++)
{
if (!keyLines[i].Contains("PRIVATE"))
{
cleanedKey.Append(keyLines[i]);
}
}
return cleanedKey.ToString();
}
19
View Source File : PostFSRepo.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public PostMetadata GetDefaultMetadata(string id)
{
string path = GetPath(id);
PostMetadata metadata = new PostMetadata
{
id = id,
creationTime = System.IO.File.GetCreationTime(path).ToString(),
modificationTime = System.IO.File.GetLastWriteTime(path).ToString()
};
{
var relpath = Path.GetDirectoryName(id)?.Replace("\\", "/");
var items = relpath?.Split("/", StringSplitOptions.RemoveEmptyEntries);
metadata.category = items ?? Array.Empty<string>();
}
return metadata;
}
19
View Source File : SentinelCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("boot", AccessLevel.Sentinel, CommandHandlerFlag.None, 2,
"Boots the character out of the game.",
"[account | char | iid] who (, reason) \n"
+ "This command boots the specified character out of the game. You can specify who to boot by account, character name, or player instance id. 'who' is the account / character / instance id to actually boot. You can optionally include a reason for the boot.\n"
+ "Example: @boot char Character Name\n"
+ " @boot account AccountName\n"
+ " @boot iid 0x51234567\n"
+ " @boot char Character Name, Reason for being booted\n")]
public static void HandleBoot(Session session, params string[] parameters)
{
// usage: @boot { account,char, iid} who
// This command boots the specified character out of the game.You can specify who to boot by account, character name, or player instance id. 'who' is the account / character / instance id to actually boot.
// @boot - Boots the character out of the game.
var whomToBoot = parameters[1];
string specifiedReason = null;
if (parameters.Length > 1)
{
var parametersAfterBootType = "";
for (var i = 1; i < parameters.Length; i++)
{
parametersAfterBootType += parameters[i] + " ";
}
parametersAfterBootType = parametersAfterBootType.Trim();
var completeBootNamePlusCommaSeperatedReason = parametersAfterBootType.Split(",");
whomToBoot = completeBootNamePlusCommaSeperatedReason[0].Trim();
if (completeBootNamePlusCommaSeperatedReason.Length > 1)
specifiedReason = parametersAfterBootType.Replace($"{whomToBoot},", "").Trim();
}
string whatToBoot = null;
Session sessionToBoot = null;
switch (parameters[0].ToLower())
{
case "char":
whatToBoot = "character";
sessionToBoot = PlayerManager.GetOnlinePlayer(whomToBoot)?.Session;
break;
case "account":
whatToBoot = "account";
sessionToBoot = NetworkManager.Find(whomToBoot);
break;
case "iid":
whatToBoot = "instance id";
if (!whomToBoot.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
return;
}
if (uint.TryParse(whomToBoot.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var iid))
{
sessionToBoot = PlayerManager.GetOnlinePlayer(iid)?.Session;
}
else
{
CommandHandlerHelper.WriteOutputInfo(session, $"That is not a valid Instance ID (IID). IIDs must be between 0x{ObjectGuid.PlayerMin:X8} and 0x{ObjectGuid.PlayerMax:X8}", ChatMessageType.Broadcast);
return;
}
break;
default:
CommandHandlerHelper.WriteOutputInfo(session, "You must specify what you are booting with char, account, or iid as the first parameter.", ChatMessageType.Broadcast);
return;
}
if (sessionToBoot == null)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Cannot boot \"{whomToBoot}\" because that {whatToBoot} is not currently online or cannot be found. Check syntax/spelling and try again.", ChatMessageType.Broadcast);
return;
}
// Boot the player
var bootText = $"Booting {whatToBoot} {whomToBoot}.{(specifiedReason != null ? $" Reason: {specifiedReason}" : "")}";
CommandHandlerHelper.WriteOutputInfo(session, bootText, ChatMessageType.Broadcast);
sessionToBoot.Terminate(SessionTerminationReason.AccountBooted, new GameMessageBootAccount($"{(specifiedReason != null ? $" - {specifiedReason}" : null)}"), null, specifiedReason);
//CommandHandlerHelper.WriteOutputInfo(session, $"...Result: Success!", ChatMessageType.Broadcast);
PlayerManager.BroadcastToAuditChannel(session?.Player, bootText);
}
19
View Source File : CommandManager.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 void ParseCommand(string commandLine, out string command, out string[] parameters)
{
if (commandLine == "/" || commandLine == "")
{
command = null;
parameters = null;
return;
}
var commandSplit = commandLine.Split(' ',StringSplitOptions.RemoveEmptyEntries);
command = commandSplit[0];
// remove leading '/' or '@' if erroneously entered in console
if(command.StartsWith("/") || command.StartsWith("@"))
command = command.Substring(1);
parameters = new string[commandSplit.Length - 1];
Array.Copy(commandSplit, 1, parameters, 0, commandSplit.Length - 1);
if (commandLine.Contains("\""))
{
var listParameters = new List<string>();
for (int start = 0; start < parameters.Length; start++)
{
if (!parameters[start].StartsWith("\"") || parameters[start].EndsWith("\"")) // Make sure we catch parameters like: "someParam"
listParameters.Add(parameters[start].Replace("\"", ""));
else
{
listParameters.Add(parameters[start].Replace("\"", ""));
for (int end = start + 1; end < parameters.Length; end++)
{
if (!parameters[end].EndsWith("\""))
listParameters[listParameters.Count - 1] += " " + parameters[end];
else
{
listParameters[listParameters.Count - 1] += " " + parameters[end].Replace("\"", "");
start = end;
break;
}
}
}
}
Array.Resize(ref parameters, listParameters.Count);
parameters = listParameters.ToArray();
}
}
19
View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static MutationFilter BuildMutation(string filename)
{
var lines = ReadScript(filename);
if (lines == null)
{
log.Error($"MutationCache.BuildMutation({filename}) - embedded resource not found");
return null;
}
string prevMutationLine = null;
string mutationLine = null;
var mutationFilter = new MutationFilter();
Mutation mutation = null;
MutationOutcome outcome = null;
EffectList effectList = null;
var totalChance = 0.0M;
var timer = Stopwatch.StartNew();
foreach (var _line in lines)
{
var line = _line;
var commentIdx = line.IndexOf("//");
if (commentIdx != -1)
line = line.Substring(0, commentIdx);
if (line.Contains("Mutation #", StringComparison.OrdinalIgnoreCase))
{
prevMutationLine = mutationLine;
mutationLine = line;
continue;
}
if (line.Contains("Tier chances", StringComparison.OrdinalIgnoreCase))
{
if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
log.Error($"MutationCache.BuildMutation({filename}) - {prevMutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");
mutation = new Mutation();
mutationFilter.Mutations.Add(mutation);
var tierPieces = line.Split(',');
foreach (var tierPiece in tierPieces)
{
var match = Regex.Match(tierPiece, @"([\d.]+)");
if (match.Success && float.TryParse(match.Groups[1].Value, out var tierChance))
{
mutation.Chances.Add(tierChance);
}
else
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse tier chances for {mutationLine}: {tierPiece}");
mutation.Chances.Add(0.0f);
}
}
outcome = new MutationOutcome();
mutation.Outcomes.Add(outcome);
totalChance = 0.0M;
continue;
}
if (line.Contains("- Chance", StringComparison.OrdinalIgnoreCase))
{
if (totalChance >= 1.0M)
{
if (totalChance > 1.0M)
log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {totalChance}, expected 1.0");
outcome = new MutationOutcome();
mutation.Outcomes.Add(outcome);
totalChance = 0.0M;
}
effectList = new EffectList();
outcome.EffectLists.Add(effectList);
var match = Regex.Match(line, @"([\d.]+)");
if (match.Success && decimal.TryParse(match.Groups[1].Value, out var chance))
{
totalChance += chance / 100;
effectList.Chance = (float)totalChance;
}
else
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line} for {mutationLine}");
}
continue;
}
if (!line.Contains("="))
continue;
var effect = new Effect();
effect.Type = GetMutationEffectType(line);
var firstOperator = GetFirstOperator(effect.Type);
var pieces = line.Split(firstOperator, 2);
if (pieces.Length != 2)
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
continue;
}
pieces[0] = pieces[0].Trim();
pieces[1] = pieces[1].Trim();
var firstStatType = GetStatType(pieces[0]);
/*if (firstStatType == StatType.Undef)
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't determine StatType for {pieces[0]} in {line}");
continue;
}*/
effect.Quality = ParseEffectArgument(filename, effect, pieces[0]);
var hreplacedecondOperator = HreplacedecondOperator(effect.Type);
if (!hreplacedecondOperator)
{
effect.Arg1 = ParseEffectArgument(filename, effect, pieces[1]);
}
else
{
var secondOperator = GetSecondOperator(effect.Type);
var subpieces = pieces[1].Split(secondOperator, 2);
if (subpieces.Length != 2)
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
continue;
}
subpieces[0] = subpieces[0].Trim();
subpieces[1] = subpieces[1].Trim();
effect.Arg1 = ParseEffectArgument(filename, effect, subpieces[0]);
effect.Arg2 = ParseEffectArgument(filename, effect, subpieces[1]);
}
effectList.Effects.Add(effect);
}
if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");
timer.Stop();
// scripts take about ~2ms to compile
//Console.WriteLine($"Compiled {filename} in {timer.Elapsed.TotalMilliseconds}ms");
return mutationFilter;
}
19
View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static void CheckForWorldDatabaseUpdate()
{
log.Info($"Automatic World Database Update started...");
try
{
var worldDb = new Database.WorldDatabase();
var currentVersion = worldDb.GetVersion();
log.Info($"Current World Database version: Base - {currentVersion.BaseVersion} | Patch - {currentVersion.PatchVersion}");
var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "ACE.Server";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
var html = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic json = JsonConvert.DeserializeObject(html);
string tag = json[0].tag_name;
string dbURL = json[0].replacedets[0].browser_download_url;
string dbFileName = json[0].replacedets[0].name;
if (currentVersion.PatchVersion != tag)
{
var patchVersionSplit = currentVersion.PatchVersion.Split(".");
var tagSplit = tag.Split(".");
int.TryParse(patchVersionSplit[0], out var patchMajor);
int.TryParse(patchVersionSplit[1], out var patchMinor);
int.TryParse(patchVersionSplit[2], out var patchBuild);
int.TryParse(tagSplit[0], out var tagMajor);
int.TryParse(tagSplit[1], out var tagMinor);
int.TryParse(tagSplit[2], out var tagBuild);
if (tagMajor > patchMajor || tagMinor > patchMinor || (tagBuild > patchBuild && patchBuild != 0))
{
log.Info($"Latest patch version is {tag} -- Update Required!");
UpdateToLatestWorldDatabase(dbURL, dbFileName);
var newVersion = worldDb.GetVersion();
log.Info($"Updated World Database version: Base - {newVersion.BaseVersion} | Patch - {newVersion.PatchVersion}");
}
else
{
log.Info($"Latest patch version is {tag} -- No Update Required!");
}
}
else
{
log.Info($"Latest patch version is {tag} -- No Update Required!");
}
}
catch (Exception ex)
{
log.Info($"Unable to continue with Automatic World Database Update due to the following error: {ex}");
}
log.Info($"Automatic World Database Update complete.");
}
19
View Source File : StringHelper.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public static Guid UniqueIdToGuid(string uniqueId)
{
if (string.IsNullOrEmpty(uniqueId))
{
return Guid.Empty;
}
Guid newGuid;
if (Guid.TryParse(uniqueId, out newGuid))
{ return newGuid; }
else if (uniqueId.Contains(Core.Common.Constants.MagicStrings.GuidSeparator))
{
string[] guids = uniqueId.Split(Core.Common.Constants.MagicStrings.GuidSeparator);
if (Guid.TryParse(guids[0], out newGuid))
{ return newGuid; }
}
return Guid.Empty;
}
19
View Source File : FeatureDefinitionFactory.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public static FeatureDefinition GetFaultyDefinition(
string uniqueIdentifier,
Scope scope,
Version version
)
{
if (string.IsNullOrEmpty(uniqueIdentifier))
{
return null;
}
Guid featureId;
int compatibilityLevel;
string sandBoxedSolutionLocation;
var splittedId = uniqueIdentifier.Split(Common.Constants.MagicStrings.GuidSeparator);
if (splittedId.Length >= 1)
{
var featureIdreplacedtring = splittedId[0];
if (!Guid.TryParse(featureIdreplacedtring, out featureId))
{
return null;
}
}
else
{
return null;
}
if (splittedId.Length >= 2)
{
var compatibilityLevelreplacedtring = splittedId[1];
if (!Int32.TryParse(compatibilityLevelreplacedtring, out compatibilityLevel))
{
compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
}
}
else
{
compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
}
if (splittedId.Length >= 3)
{
sandBoxedSolutionLocation = splittedId[2];
}
else
{
sandBoxedSolutionLocation = null;
}
var featureDefinition = new FeatureDefinition(
featureId,
compatibilityLevel,
Common.Constants.Labels.FaultyFeatureDescription,
Common.Constants.Labels.FaultyFeatureName,
false,
Common.Constants.Labels.FaultyFeatureName,
null,
scope,
Common.Constants.Labels.FaultyFeatureName,
Guid.Empty,
Common.Constants.Labels.FaultyFeatureUiVersion,
version,
sandBoxedSolutionLocation
);
return featureDefinition;
}
19
View Source File : ProcessExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable)
{
var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions));
Dictionary<string, string> env = new Dictionary<string, string>();
if (Directory.Exists("/proc"))
{
string envFile = $"/proc/{process.Id}/environ";
trace.Info($"Read env from {envFile}");
string envContent = File.ReadAllText(envFile);
if (!string.IsNullOrEmpty(envContent))
{
// on linux, environment variables are seprated by '\0'
var envList = envContent.Split('\0', StringSplitOptions.RemoveEmptyEntries);
foreach (var envStr in envList)
{
// split on the first '='
var keyValuePair = envStr.Split('=', 2);
if (keyValuePair.Length == 2)
{
env[keyValuePair[0]] = keyValuePair[1];
trace.Verbose($"PID:{process.Id} ({keyValuePair[0]}={keyValuePair[1]})");
}
}
}
}
else
{
// On OSX, there is no /proc folder for us to read environment for given process,
// So we have call `ps e -p <pid> -o command` to print out env to STDOUT,
// However, the output env are not format in a parseable way, it's just a string that concatenate all envs with space,
// It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs.
// So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space)
trace.Info($"Read env from output of `ps e -p {process.Id} -o command`");
List<string> psOut = new List<string>();
object outputLock = new object();
using (var p = hostContext.CreateService<IProcessInvoker>())
{
p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)
{
if (!string.IsNullOrEmpty(stdout.Data))
{
lock (outputLock)
{
psOut.Add(stdout.Data);
}
}
};
p.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr)
{
if (!string.IsNullOrEmpty(stderr.Data))
{
lock (outputLock)
{
trace.Error(stderr.Data);
}
}
};
int exitCode = p.ExecuteAsync(workingDirectory: hostContext.GetDirectory(WellKnownDirectory.Root),
fileName: "ps",
arguments: $"e -p {process.Id} -o command",
environment: null,
cancellationToken: CancellationToken.None).GetAwaiter().GetResult();
if (exitCode == 0)
{
trace.Info($"Successfully dump environment variables for {process.Id}");
if (psOut.Count > 0)
{
string psOutputString = string.Join(" ", psOut);
trace.Verbose($"ps output: '{psOutputString}'");
int varStartIndex = psOutputString.IndexOf(variable, StringComparison.Ordinal);
if (varStartIndex >= 0)
{
string rightPart = psOutputString.Substring(varStartIndex + variable.Length + 1);
if (rightPart.IndexOf(' ') > 0)
{
string value = rightPart.Substring(0, rightPart.IndexOf(' '));
env[variable] = value;
}
else
{
env[variable] = rightPart;
}
trace.Verbose($"PID:{process.Id} ({variable}={env[variable]})");
}
}
}
}
}
if (env.TryGetValue(variable, out string envVariable))
{
return envVariable;
}
else
{
return null;
}
}
19
View Source File : CheckUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
base.OnEventWritten(eventData);
lock (_lock)
{
if (_ignoredEvent.TryGetValue(eventData.EventSource.Name, out var ignored) &&
ignored.Contains(eventData.EventName))
{
return;
}
_logs.Add($"{DateTime.UtcNow.ToString("O")} [START {eventData.EventSource.Name} - {eventData.EventName}]");
_logs.AddRange(eventData.Payload.Select(x => string.Join(Environment.NewLine, x.ToString().Split(Environment.NewLine).Select(y => $"{DateTime.UtcNow.ToString("O")} {y}"))));
_logs.Add($"{DateTime.UtcNow.ToString("O")} [END {eventData.EventSource.Name} - {eventData.EventName}]");
}
}
19
View Source File : ConfigurationManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task<GitHubRunnerRegisterToken> GetJITRunnerTokenAsync(string githubUrl, string githubToken, string tokenType)
{
var githubApiUrl = "";
var gitHubUrlBuilder = new UriBuilder(githubUrl);
var path = gitHubUrlBuilder.Path.Split('/', '\\', StringSplitOptions.RemoveEmptyEntries);
if (path.Length == 1)
{
// org runner
if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/orgs/{path[0]}/actions/runners/{tokenType}-token";
}
else
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/orgs/{path[0]}/actions/runners/{tokenType}-token";
}
}
else if (path.Length == 2)
{
// repo or enterprise runner.
var repoScope = "repos/";
if (string.Equals(path[0], "enterprises", StringComparison.OrdinalIgnoreCase))
{
repoScope = "";
}
if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
}
else
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
}
}
else
{
throw new ArgumentException($"'{githubUrl}' should point to an org or repository.");
}
using (var httpClientHandler = HostContext.CreateHttpClientHandler())
using (var httpClient = new HttpClient(httpClientHandler))
{
var base64EncodingToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"github:{githubToken}"));
HostContext.SecretMasker.AddValue(base64EncodingToken);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", base64EncodingToken);
httpClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");
var response = await httpClient.PostAsync(githubApiUrl, new StringContent(string.Empty));
if (response.IsSuccessStatusCode)
{
Trace.Info($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
var jsonResponse = await response.Content.ReadreplacedtringAsync();
return StringUtil.ConvertFromJson<GitHubRunnerRegisterToken>(jsonResponse);
}
else
{
_term.WriteError($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
var errorResponse = await response.Content.ReadreplacedtringAsync();
_term.WriteError(errorResponse);
response.EnsureSuccessStatusCode();
return null;
}
}
}
19
View Source File : ActionPlugin.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void Debug(string message)
{
var debugString = Variables.GetValueOrDefault(DebugEnvironmentalVariable)?.Value;
if (StringUtil.ConvertToBoolean(debugString))
{
var multilines = message?.Replace("\r\n", "\n")?.Split("\n");
if (multilines != null)
{
foreach (var line in multilines)
{
Output($"##[debug]{Escape(line)}");
}
}
}
}
19
View Source File : ContainerInfo.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void ParseVolumeString(string volume)
{
var volumeSplit = volume.Split(":");
if (volumeSplit.Length == 3)
{
// source:target:ro
SourceVolumePath = volumeSplit[0];
TargetVolumePath = volumeSplit[1];
ReadOnly = String.Equals(volumeSplit[2], "ro", StringComparison.OrdinalIgnoreCase);
}
else if (volumeSplit.Length == 2)
{
if (String.Equals(volumeSplit[1], "ro", StringComparison.OrdinalIgnoreCase))
{
// target:ro
TargetVolumePath = volumeSplit[0];
ReadOnly = true;
}
else
{
// source:target
SourceVolumePath = volumeSplit[0];
TargetVolumePath = volumeSplit[1];
ReadOnly = false;
}
}
else
{
// target - or, default to preplaceding straight through
TargetVolumePath = volume;
ReadOnly = false;
}
}
19
View Source File : DockerUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static string ParsePathFromConfigEnv(IList<string> configEnvLines)
{
// Config format is VAR=value per line
foreach (var line in configEnvLines)
{
var keyValue = line.Split("=", 2);
if (keyValue.Length == 2 && string.Equals(keyValue[0], "PATH"))
{
return keyValue[1];
}
}
return "";
}
19
View Source File : OutputManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private string GetRepositoryPath(string filePath, int recursion = 0)
{
// Prevent the cache from growing too much
if (_directoryMap.Count > 100)
{
_directoryMap.Clear();
}
// Empty directory means we hit the root of the drive
var directoryPath = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(directoryPath) || recursion > _failsafe)
{
return null;
}
// Check the cache
if (_directoryMap.TryGetValue(directoryPath, out string repositoryPath))
{
return repositoryPath;
}
try
{
// Check if .git/config exists
var gitConfigPath = Path.Combine(directoryPath, ".git", "config");
if (File.Exists(gitConfigPath))
{
// Check if the config contains the workflow repository url
var serverUrl = _executionContext.GetGitHubContext("server_url");
serverUrl = !string.IsNullOrEmpty(serverUrl) ? serverUrl : "https://github.com";
var host = new Uri(serverUrl, UriKind.Absolute).Host;
var nameWithOwner = _executionContext.GetGitHubContext("repository");
var patterns = new[] {
$"url = {serverUrl}/{nameWithOwner}",
$"url = git@{host}:{nameWithOwner}.git",
};
var content = File.ReadAllText(gitConfigPath);
foreach (var line in content.Split("\n").Select(x => x.Trim()))
{
foreach (var pattern in patterns)
{
if (String.Equals(line, pattern, StringComparison.OrdinalIgnoreCase))
{
repositoryPath = directoryPath;
break;
}
}
}
}
else
{
// Recursive call
repositoryPath = GetRepositoryPath(directoryPath, recursion + 1);
}
}
catch (Exception ex)
{
_executionContext.Debug($"Error when attempting to determine whether the path '{filePath}' is under the workflow repository: {ex.Message}");
}
_directoryMap[directoryPath] = repositoryPath;
return repositoryPath;
}
19
View Source File : FileCommandManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void ProcessCommand(IExecutionContext context, string filePath, ContainerInfo container)
{
try
{
var text = File.ReadAllText(filePath) ?? string.Empty;
var index = 0;
var line = ReadLine(text, ref index);
while (line != null)
{
if (!string.IsNullOrEmpty(line))
{
var equalsIndex = line.IndexOf("=", StringComparison.Ordinal);
var heredocIndex = line.IndexOf("<<", StringComparison.Ordinal);
// Normal style NAME=VALUE
if (equalsIndex >= 0 && (heredocIndex < 0 || equalsIndex < heredocIndex))
{
var split = line.Split(new[] { '=' }, 2, StringSplitOptions.None);
if (string.IsNullOrEmpty(line))
{
throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty");
}
SetEnvironmentVariable(context, split[0], split[1]);
}
// Heredoc style NAME<<EOF
else if (heredocIndex >= 0 && (equalsIndex < 0 || heredocIndex < equalsIndex))
{
var split = line.Split(new[] { "<<" }, 2, StringSplitOptions.None);
if (string.IsNullOrEmpty(split[0]) || string.IsNullOrEmpty(split[1]))
{
throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty and delimiter must not be empty");
}
var name = split[0];
var delimiter = split[1];
var startIndex = index; // Start index of the value (inclusive)
var endIndex = index; // End index of the value (exclusive)
var tempLine = ReadLine(text, ref index, out var newline);
while (!string.Equals(tempLine, delimiter, StringComparison.Ordinal))
{
if (tempLine == null)
{
throw new Exception($"Invalid environment variable value. Matching delimiter not found '{delimiter}'");
}
endIndex = index - newline.Length;
tempLine = ReadLine(text, ref index, out newline);
}
var value = endIndex > startIndex ? text.Substring(startIndex, endIndex - startIndex) : string.Empty;
SetEnvironmentVariable(context, name, value);
}
else
{
throw new Exception($"Invalid environment variable format '{line}'");
}
}
line = ReadLine(text, ref index);
}
}
catch (DirectoryNotFoundException)
{
context.Debug($"Environment variables file does not exist '{filePath}'");
}
catch (FileNotFoundException)
{
context.Debug($"Environment variables file does not exist '{filePath}'");
}
}
19
View Source File : ScriptHandlerHelpers.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal static (string shellCommand, string shellArgs) ParseShellOptionString(string shellOption)
{
var shellStringParts = shellOption.Split(" ", 2);
if (shellStringParts.Length == 2)
{
return (shellCommand: shellStringParts[0], shellArgs: shellStringParts[1]);
}
else if (shellStringParts.Length == 1)
{
return (shellCommand: shellStringParts[0], shellArgs: "");
}
else
{
throw new ArgumentException($"Failed to parse COMMAND [..ARGS] from {shellOption}");
}
}
19
View Source File : IdentityDescriptor.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static IdenreplacedyDescriptor FromString(string idenreplacedyDescriptorString)
{
if (string.IsNullOrEmpty(idenreplacedyDescriptorString))
{
return null;
}
string[] tokens;
try
{
tokens = idenreplacedyDescriptorString.Split(new[] { IdenreplacedyConstants.IdenreplacedyDescriptorPartsSeparator }, 2, StringSplitOptions.RemoveEmptyEntries);
}
catch
{
return new IdenreplacedyDescriptor(IdenreplacedyConstants.UnknownIdenreplacedyType, idenreplacedyDescriptorString);
}
if (tokens.Length == 2)
{
return new IdenreplacedyDescriptor(tokens[0], tokens[1]);
}
return new IdenreplacedyDescriptor(IdenreplacedyConstants.UnknownIdenreplacedyType, idenreplacedyDescriptorString);
}
19
View Source File : IdentityDescriptor.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
string descriptor = value as string;
string[] tokens = descriptor.Split(new[] { IdenreplacedyConstants.IdenreplacedyDescriptorPartsSeparator }, 2, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 2)
{
return new IdenreplacedyDescriptor(tokens[0], tokens[1]);
}
}
return base.ConvertFrom(context, culture, value);
}
19
View Source File : ExecutionContext.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static void Debug(this IExecutionContext context, string message)
{
if (context.Global.WriteDebug)
{
var multilines = message?.Replace("\r\n", "\n")?.Split("\n");
if (multilines != null)
{
foreach (var line in multilines)
{
context.Write(WellKnownTags.Debug, line);
}
}
}
}
19
View Source File : ConfigurationManagerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "ConfigurationManagement")]
public async Task CanEnsureConfigure()
{
using (TestHostContext tc = CreateTestContext())
{
Tracing trace = tc.GetTrace();
trace.Info("Creating config manager");
IConfigurationManager configManager = new ConfigurationManager();
configManager.Initialize(tc);
var userLabels = "userlabel1,userlabel2";
trace.Info("Preparing command line arguments");
var command = new CommandSettings(
tc,
new[]
{
"configure",
"--url", _expectedServerUrl,
"--name", _expectedAgentName,
"--runnergroup", _secondRunnerGroupName,
"--work", _expectedWorkFolder,
"--auth", _expectedAuthType,
"--token", _expectedToken,
"--labels", userLabels,
"--ephemeral",
});
trace.Info("Constructed.");
_store.Setup(x => x.IsConfigured()).Returns(false);
_configMgrAgentSettings = null;
trace.Info("Ensuring all the required parameters are available in the command line parameter");
await configManager.ConfigureAsync(command);
_store.Setup(x => x.IsConfigured()).Returns(true);
trace.Info("Configured, verifying all the parameter value");
var s = configManager.LoadSettings();
replacedert.NotNull(s);
replacedert.True(s.ServerUrl.Equals(_expectedServerUrl));
replacedert.True(s.AgentName.Equals(_expectedAgentName));
replacedert.True(s.PoolId.Equals(_secondRunnerGroupId));
replacedert.True(s.WorkFolder.Equals(_expectedWorkFolder));
replacedert.True(s.Ephemeral.Equals(true));
// validate GetAgentPoolsAsync gets called twice with automation pool type
_runnerServer.Verify(x => x.GetAgentPoolsAsync(It.IsAny<string>(), It.Is<TaskAgentPoolType>(p => p == TaskAgentPoolType.Automation)), Times.Exactly(2));
var expectedLabels = new List<string>() { "self-hosted", VarUtil.OS, VarUtil.OSArchitecture};
expectedLabels.AddRange(userLabels.Split(",").ToList());
_runnerServer.Verify(x => x.AddAgentAsync(It.IsAny<int>(), It.Is<TaskAgent>(a => a.Labels.Select(x => x.Name).ToHashSet().SetEquals(expectedLabels))), Times.Once);
}
}
19
View Source File : Versions.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
[Fact]
public static async Task RepoWithHistory()
{
// arrange
var historicalCommands =
@"git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0-beta.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-rc.1
git tag 1.0.0
git checkout -b foo
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1
git commit --allow-empty -m '.'
git checkout main
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-alpha.1
git commit --allow-empty -m '.'
git merge foo --no-edit
git commit --allow-empty -m '.'
git tag 1.1.0-beta.2
git tag 1.1.0-beta.10
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-rc.1
git tag 1.1.0 -a -m '.'";
var path = MethodBase.GetCurrentMethod().GetTestDirectory();
await EnsureEmptyRepositoryAndCommit(path);
foreach (var command in historicalCommands.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
var nameAndArgs = command.Split(" ", 2);
_ = await ReadAsync(nameAndArgs[0], nameAndArgs[1], path);
await Task.Delay(200);
}
// act
var versionCounts = new Dictionary<string, int>();
foreach (var sha in await GetCommitShas(path))
{
await Checkout(path, sha);
var version = Versioner.GetVersion(path, default, default, default, default, default, default);
var versionString = version.ToString();
var tagName = $"v/{versionString}";
_ = versionCounts.TryGetValue(versionString, out var oldVersionCount);
var versionCount = oldVersionCount + 1;
versionCounts[versionString] = versionCount;
tagName = versionCount > 1 ? $"v({versionCount})/{versionString}" : tagName;
await Tag(path, tagName, sha);
}
await Checkout(path, "main");
// replacedert
await replacedertFile.Contains("../../../versions.txt", await GetGraph(path));
}
19
View Source File : POComment.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public static bool TryParse(string value, out POReferenceComment result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var withinQuotes = false;
IEnumerable<string> parts = value
.Split(c =>
{
if (c == '"')
withinQuotes = !withinQuotes;
return !withinQuotes && char.IsWhiteSpace(c);
}, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim());
var references = new List<POSourceReference>();
foreach (var part in parts)
if (POSourceReference.TryParse(part, out POSourceReference reference))
references.Add(reference);
else
{
result = null;
return false;
}
result = new POReferenceComment { References = references };
return true;
}
19
View Source File : Settings.cs
License : MIT License
Project Creator : adlez27
License : MIT License
Project Creator : adlez27
public void LoadRecList()
{
if (init && File.Exists(RecListFile))
{
RecList.Clear();
HashSet<string> uniqueStrings = new HashSet<string>();
Encoding e;
if (ReadUnicode)
{
e = Encoding.UTF8;
}
else
{
e = CodePagesEncodingProvider.Instance.GetEncoding(932);
}
var ext = Path.GetExtension(RecListFile);
if (ext == ".txt")
{
if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
{
var rawText = File.ReadAllLines(RecListFile, e);
foreach(string rawLine in rawText)
{
var line = rawLine.Split("\t");
if (!uniqueStrings.Contains(line[0]))
{
RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
uniqueStrings.Add(line[0]);
}
}
}
else
{
string[] textArr;
if (SplitWhitespace)
{
var rawText = File.ReadAllText(RecListFile, e);
rawText = Regex.Replace(rawText, @"\s{2,}", " ");
textArr = Regex.Split(rawText, @"\s");
}
else
{
textArr = File.ReadAllLines(RecListFile, e);
}
foreach (string line in textArr)
{
if (!uniqueStrings.Contains(line))
{
RecList.Add(new RecLisreplacedem(this, line));
uniqueStrings.Add(line);
}
}
}
}
else if (ext == ".arl")
{
var rawText = File.ReadAllText(RecListFile, e);
var deserializer = new Deserializer();
var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
foreach (var item in tempDict)
{
RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
}
}
else if (ext == ".csv")
{
using (TextFieldParser parser = new TextFieldParser(RecListFile))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
var text = line[0].Substring(0,line[0].Length - 4);
if (!uniqueStrings.Contains(text))
{
RecList.Add(new RecLisreplacedem(this, text, line[1]));
uniqueStrings.Add(text);
}
}
}
CopyIndex();
}
else if (ext == ".reclist")
{
var rawText = File.ReadAllText(RecListFile, e);
var deserializer = new Deserializer();
var reclist = deserializer.Deserialize<WCTReclist>(rawText);
foreach(var line in reclist.Files)
{
if (!uniqueStrings.Contains(line.Filename))
{
RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
uniqueStrings.Add(line.Filename);
}
}
}
else if (ext == ".ust"){
var rawText = File.ReadAllLines(RecListFile, e);
foreach (var line in rawText)
{
if (line.StartsWith("Lyric="))
{
var lyric = line.Substring(6);
if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
{
RecList.Add(new RecLisreplacedem(this, lyric));
uniqueStrings.Add(lyric);
}
}
}
}
}
}
19
View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static Expression GetExpression(string op, string name, List<Expression> operands, Func<string, string, object> parseValue)
{
// check if this is a logical expression
if (op == "&")
{
if (operands == null || operands.Count == 0)
{
throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
}
return And(operands.ToArray());
}
if (op == "|")
{
if (operands == null || operands.Count == 0)
{
throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
}
return Or(operands.ToArray());
}
if (op == "!")
{
if (operands == null || operands.Count != 1)
{
throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
}
return Not(operands[0]);
}
if (op == null)
{
if (operands == null || operands.Count != 1)
{
throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
}
return NoOp(operands[0]);
}
// check if this is a conditional string
var ops = name.Split(new[] { op }, 2, StringSplitOptions.None);
if (ops.Length != 2)
{
throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
}
var attributeName = ops[0];
var text = ops[1];
var containsWildcard = text != null && (Regex.IsMatch(text, @"[^\\]\*") || text.StartsWith("*"));
var value = parseValue(attributeName, text);
// if an '*' is detected in an '=' expression, promote to 'like' expression
if ((op == "=" || op == "==") && containsWildcard)
{
op = "~=";
}
if (op == "=" || op == "==")
{
return Equals(attributeName, value);
}
if (op == "!=")
{
if (containsWildcard)
{
// if an '*' is detected in an '=' expression, promote to 'like' expression
return NotLike(attributeName, value);
}
return NotEquals(attributeName, value);
}
if (op == "~=")
{
return Like(attributeName, value);
}
if (op == "<")
{
return LessThan(attributeName, value);
}
if (op == "<=")
{
return LessThanOrEquals(attributeName, value);
}
if (op == ">")
{
return GreaterThan(attributeName, value);
}
if (op == ">=")
{
return GreaterThanOrEquals(attributeName, value);
}
throw new InvalidOperationException(string.Format("Unknown operator symbol {0}.", op));
}
19
View Source File : SettingsModel.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
public string Multiline(string text, int wordsPerLine = 5)
=> string.Join(Environment.NewLine,
text.Split(" ")
.Batch(wordsPerLine)
.Select(line => string.Join(" ", line)));
19
View Source File : LocationPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static void MakeSpouseRoom(FarmHouse fh, HashSet<string> appliedMapOverrides, SpouseRoomData srd, bool first = false)
{
Monitor.Log($"Loading spouse room for {srd.name}. shellStart {srd.startPos}, spouse offset {srd.spousePosOffset}. Type: {srd.shellType}");
var corner = srd.startPos + new Point(1, 1);
var spouse = srd.name;
var shellPath = srd.shellType;
var indexInSpouseMapSheet = srd.templateIndex;
var spouseSpot = srd.startPos + srd.spousePosOffset;
Rectangle shellAreaToRefurbish = new Rectangle(corner.X - 1, corner.Y - 1, 8, 12);
Misc.ExtendMap(fh, shellAreaToRefurbish.X + shellAreaToRefurbish.Width, shellAreaToRefurbish.Y + shellAreaToRefurbish.Height);
// load shell
if (appliedMapOverrides.Contains("spouse_room_" + spouse + "_shell"))
{
appliedMapOverrides.Remove("spouse_room_" + spouse + "_shell");
}
fh.ApplyMapOverride(shellPath, "spouse_room_" + spouse + "_shell", new Rectangle?(new Rectangle(0, 0, shellAreaToRefurbish.Width, shellAreaToRefurbish.Height)), new Rectangle?(shellAreaToRefurbish));
for (int x = 0; x < shellAreaToRefurbish.Width; x++)
{
for (int y = 0; y < shellAreaToRefurbish.Height; y++)
{
if (fh.map.GetLayer("Back").Tiles[shellAreaToRefurbish.X + x, shellAreaToRefurbish.Y + y] != null)
{
fh.map.GetLayer("Back").Tiles[shellAreaToRefurbish.X + x, shellAreaToRefurbish.Y + y].Properties["FloorID"] = "spouse_hall_" + (Config.DecorateHallsIndividually ? spouse : "floor");
}
}
}
Dictionary<string, string> room_data = Game1.content.Load<Dictionary<string, string>>("Data\\SpouseRooms");
string map_path = "spouseRooms";
if (indexInSpouseMapSheet == -1 && room_data != null && srd.templateName != null && room_data.ContainsKey(srd.templateName))
{
try
{
string[] array = room_data[srd.templateName].Split('/', StringSplitOptions.None);
map_path = array[0];
indexInSpouseMapSheet = int.Parse(array[1]);
}
catch (Exception)
{
}
}
if (indexInSpouseMapSheet == -1 && room_data != null && room_data.ContainsKey(spouse))
{
try
{
string[] array = room_data[spouse].Split('/', StringSplitOptions.None);
map_path = array[0];
indexInSpouseMapSheet = int.Parse(array[1]);
}
catch (Exception)
{
}
}
if (indexInSpouseMapSheet == -1)
{
if (srd.templateName != null && ModEntry.roomIndexes.ContainsKey(srd.templateName))
{
indexInSpouseMapSheet = ModEntry.roomIndexes[srd.templateName];
}
else if (ModEntry.roomIndexes.ContainsKey(spouse))
{
indexInSpouseMapSheet = ModEntry.roomIndexes[spouse];
}
else
{
Monitor.Log($"Could not find spouse room map for {spouse}", LogLevel.Debug);
return;
}
}
int width = fh.GetSpouseRoomWidth();
int height = fh.GetSpouseRoomHeight();
Rectangle areaToRefurbish = new Rectangle(corner.X, corner.Y, width, height);
Map refurbishedMap = Game1.game1.xTileContent.Load<Map>("Maps\\" + map_path);
int columns = refurbishedMap.Layers[0].LayerWidth / width;
int num2 = refurbishedMap.Layers[0].LayerHeight / height;
Point mapReader = new Point(indexInSpouseMapSheet % columns * width, indexInSpouseMapSheet / columns * height);
List<KeyValuePair<Point, Tile>> bottom_row_tiles = new List<KeyValuePair<Point, Tile>>();
Layer front_layer = fh.map.GetLayer("Front");
for (int x = areaToRefurbish.Left; x < areaToRefurbish.Right; x++)
{
Point point = new Point(x, areaToRefurbish.Bottom - 1);
Tile tile = front_layer.Tiles[point.X, point.Y];
if (tile != null)
{
bottom_row_tiles.Add(new KeyValuePair<Point, Tile>(point, tile));
}
}
if (appliedMapOverrides.Contains("spouse_room_" + spouse))
{
appliedMapOverrides.Remove("spouse_room_" + spouse);
}
fh.ApplyMapOverride(map_path, "spouse_room_" + spouse, new Rectangle?(new Rectangle(mapReader.X, mapReader.Y, areaToRefurbish.Width, areaToRefurbish.Height)), new Rectangle?(areaToRefurbish));
for (int x = 0; x < areaToRefurbish.Width; x++)
{
for (int y = 0; y < areaToRefurbish.Height; y++)
{
if (refurbishedMap.GetLayer("Buildings").Tiles[mapReader.X + x, mapReader.Y + y] != null)
{
Helper.Reflection.GetMethod(fh, "adjustMapLightPropertiesForLamp").Invoke(refurbishedMap.GetLayer("Buildings").Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Buildings");
}
if (y < areaToRefurbish.Height - 1 && refurbishedMap.GetLayer("Front").Tiles[mapReader.X + x, mapReader.Y + y] != null)
{
Helper.Reflection.GetMethod(fh, "adjustMapLightPropertiesForLamp").Invoke(refurbishedMap.GetLayer("Front").Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Front");
}
/*
if (fh.map.GetLayer("Back").Tiles[corner.X + x, corner.Y + y] != null)
{
fh.setTileProperty(corner.X + x, corner.Y + y, "Back", "FloorID", $"spouse_room_{spouse}");
}
*/
}
}
fh.ReadWallpaperAndFloorTileData();
bool spot_found = false;
for (int x3 = areaToRefurbish.Left; x3 < areaToRefurbish.Right; x3++)
{
for (int y2 = areaToRefurbish.Top; y2 < areaToRefurbish.Bottom; y2++)
{
if (fh.getTileIndexAt(new Point(x3, y2), "Paths") == 7)
{
spot_found = true;
if (first)
fh.spouseRoomSpot = new Point(x3, y2);
spouseSpot = new Point(x3, y2);
srd.spousePosOffset = spouseSpot - srd.startPos;
break;
}
}
if (spot_found)
{
break;
}
}
fh.setTileProperty(spouseSpot.X, spouseSpot.Y, "Back", "NoFurniture", "T");
foreach (KeyValuePair<Point, Tile> kvp in bottom_row_tiles)
{
front_layer.Tiles[kvp.Key.X, kvp.Key.Y] = kvp.Value;
}
ModEntry.currentRoomData[srd.name] = srd;
}
19
View Source File : BenchmarkTestBase.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private async Task StartNodeAsync()
{
var ownAddress = await _accountService.GetAccountAsync();
var callList = new List<ContractInitializationMethodCall>();
callList.Add(nameof(TokenContractContainer.TokenContractStub.Create), new CreateInput
{
Symbol = _nativeSymbol,
TokenName = "ELF_Token",
TotalSupply = TokenTotalSupply,
Decimals = 8,
Issuer = ownAddress,
IsBurnable = true
});
callList.Add(nameof(TokenContractContainer.TokenContractStub.SetPrimaryTokenSymbol),
new SetPrimaryTokenSymbolInput {Symbol = _nativeSymbol});
callList.Add(nameof(TokenContractContainer.TokenContractStub.Issue), new IssueInput
{
Symbol = _nativeSymbol,
Amount = TokenTotalSupply,
To = ownAddress,
Memo = "Issue"
});
var tokenContractCode = Codes.Single(kv => kv.Key.Split(",").First().Trim().EndsWith("Mulreplacedoken")).Value;
var dto = new OsBlockchainNodeContextStartDto
{
ZeroSmartContract = typeof(BasicContractZero),
ChainId = ChainHelper.ConvertBase58ToChainId("AELF"),
SmartContractRunnerCategory = KernelConstants.CodeCoverageRunnerCategory,
};
var genesisSmartContractDto = new GenesisSmartContractDto
{
Code = tokenContractCode,
SystemSmartContractName = TokenSmartContractAddressNameProvider.Name,
};
genesisSmartContractDto.AddGenesisTransactionMethodCall(callList.ToArray());
dto.InitializationSmartContracts.Add(genesisSmartContractDto);
await _osBlockchainNodeContextService.StartAsync(dto);
}
See More Examples