Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Match(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1454 Examples
19
View Source File : StringUtils.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
public static bool IsPhoneNumber(string number)
{
if (string.IsNullOrEmpty(number)) return false;
return Regex.Match(number, @"^(\+[0-9]{9})$").Success;
}
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Dictionary<string, string> Factorization(string expression)
{
var experssions = new Dictionary<string, string>();
var pattern = @"\([^\(\)]+\)";
var text = $"({expression})";
while (Regex.IsMatch(text, pattern))
{
var key = $"${experssions.Count}";
var value = Regex.Match(text, pattern).Value;
experssions.Add(key, value);
text = text.Replace(value, key);
}
return experssions;
}
19
View Source File : Core.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Shellcode_Handle(string raw)
{
string result = "";
//去掉所有换行 → 匹配出shellcode → 去掉所有空格 → 去掉引号、分号、括号 → 转换格式
raw = raw.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
if (raw.Contains(@"\x"))
{
//c 类型的shellcode
string pattern = @"=.*$";
string temp = Regex.Match(raw, pattern).Value;
result = temp.Replace(@"""", "").Replace(" ", "").Replace("=", "").Replace(";", "");
}
else if ((raw.Contains(@",0x")) || (raw.Contains(@", 0x")))
{
//c# 类型的shellcode
string pattern = @"{.*}";
string temp = Regex.Match(raw, pattern).Value;
result = temp.Replace("{", "").Replace(" ", "").Replace("}", "").Replace(";", "");
}
else
{
return "";
}
//转换成 c# 格式
if (result.Contains(@"\x"))
{
result = result.Replace(@"\x", ",0x").TrimStart(',');
}
return result;
}
19
View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void SetHost(string host)
{
if (string.IsNullOrEmpty(host?.Trim())) {
_ip = "127.0.0.1";
_port = 6379;
return;
}
host = host.Trim();
var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
{
_ip = ipv6.Groups[1].Value.Trim();
_port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
return;
}
var spt = (host ?? "").Split(':');
if (spt.Length == 1) //ipv4 or domain
{
_ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
_port = 6379;
return;
}
if (spt.Length == 2) //ipv4:port or domain:port
{
if (int.TryParse(spt.Last().Trim(), out var testPort2))
{
_ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
_port = testPort2;
return;
}
_ip = host;
_port = 6379;
return;
}
if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
{
_ip = host;
_port = 6379;
return;
}
if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
{
var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
{
_ip = testHost;
_port = 6379;
return;
}
}
_ip = host;
_port = 6379;
}
19
View Source File : DefaultRedisSocket.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static KeyValuePair<string, int> SplitHost(string host)
{
if (string.IsNullOrWhiteSpace(host?.Trim()))
return new KeyValuePair<string, int>("127.0.0.1", 6379);
host = host.Trim();
var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(),
int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);
var spt = (host ?? "").Split(':');
if (spt.Length == 1) //ipv4 or domain
return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);
if (spt.Length == 2) //ipv4:port or domain:port
{
if (int.TryParse(spt.Last().Trim(), out var testPort2))
return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);
return new KeyValuePair<string, int>(host, 6379);
}
if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
return new KeyValuePair<string, int>(host, 6379);
if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
{
var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
return new KeyValuePair<string, int>(testHost, 6379);
}
return new KeyValuePair<string, int>(host, 6379);
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static Color getTextColor(string str)
{
Color color = Color.DarkCyan;
if(!string.IsNullOrWhiteSpace(str)){
if (str.Trim() == "true" || str.Trim() == "false")
{
color = Color.Red;
}
else
{
Match m = Regex.Match(str.Trim(), @"^(-?\d+)(\.\d+)?$");
if (m.Success)
{
color = Color.YellowGreen;
}
}
}
return color;
}
19
View Source File : UpdateHandle.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private string getCoreVersion(string type)
{
try
{
var core = string.Empty;
var match = string.Empty;
if (type == "v2fly")
{
core = "v2ray.exe";
match = "V2Ray";
}
else if (type == "xray")
{
core = "xray.exe";
match = "Xray";
}
string filePath = Utils.GetPath(core);
if (!File.Exists(filePath))
{
string msg = string.Format(UIRes.I18N("NotFoundCore"), @"");
//ShowMsg(true, msg);
return "";
}
Process p = new Process();
p.StartInfo.FileName = filePath;
p.StartInfo.Arguments = "-version";
p.StartInfo.WorkingDirectory = Utils.StartupPath();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.Start();
p.WaitForExit(5000);
string echo = p.StandardOutput.ReadToEnd();
string version = Regex.Match(echo, $"{match} ([0-9.]+) \\(").Groups[1].Value;
return version;
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message);
return "";
}
}
19
View Source File : Util.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static string GetExternalIp()
{
var mc = Regex.Match(
new HttpClient().GetStringAsync("http://www.net.cn/static/customercare/yourip.asp").Result,
@"您的本地上网IP是:<h2>(\d+\.\d+\.\d+\.\d+)</h2>");
if (mc.Success && mc.Groups.Count > 1)
{
return mc.Groups[1].Value;
}
throw new Exception("获取IP失败");
}
19
View Source File : LyricsFetcher.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static void PopulateFromSrt(TextReader reader, List<Subreplacedle> subreplacedles)
{
// Parse using a simple state machine:
// 0: Parsing number
// 1: Parsing start / end time
// 2: Parsing text
byte state = 0;
float startTime = 0f,
endTime = 0f;
StringBuilder text = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
switch (state)
{
case 0:
if (string.IsNullOrEmpty(line))
// No number found; continue in same state.
continue;
if (!int.TryParse(line, out int _))
goto Invalid;
// Number found; continue to next state.
state = 1;
break;
case 1:
Match m = Regex.Match(line, @"(\d+):(\d+):(\d+,\d+) *--> *(\d+):(\d+):(\d+,\d+)");
if (!m.Success)
goto Invalid;
startTime = int.Parse(m.Groups[1].Value) * 3600
+ int.Parse(m.Groups[2].Value) * 60
+ float.Parse(m.Groups[3].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);
endTime = int.Parse(m.Groups[4].Value) * 3600
+ int.Parse(m.Groups[5].Value) * 60
+ float.Parse(m.Groups[6].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);
// Subreplacedle start / end found; continue to next state.
state = 2;
break;
case 2:
if (string.IsNullOrEmpty(line))
{
// End of text; continue to next state.
subreplacedles.Add(new Subreplacedle(text.ToString(), startTime, endTime));
text.Length = 0;
state = 0;
}
else
{
// Continuation of text; continue in same state.
text.AppendLine(line);
}
break;
default:
// Shouldn't happen.
throw new Exception();
}
}
Invalid:
Debug.Log("[Beat Singer] Invalid subtiles file found, cancelling load...");
subreplacedles.Clear();
}
19
View Source File : FrmDoublePageReader.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public void StartUp(Manga m, FrmStartPage startPage)
{
this.root = m.mangaDirectory;
this.startPage = startPage;
foreach (DirectoryInfo dir in root.GetDirectories("*", SearchOption.TopDirectoryOnly)) // chapters
{
FileInfo[] files = dir.GetFiles("*");
ArrayList pages = new ArrayList();
foreach (FileInfo fi in files) // pages
{
string shortName = Path.GetFileNameWithoutExtension(fi.Name);
string num = Regex.Match(shortName, @"(\d+(\.\d+)?)|(\.\d+)").Value;
pages.Add(new Page(num, fi));
}
Chapter c = new Chapter(dir.Name, dir, SortPages((Page[])pages.ToArray(typeof(Page))));
if (dir.Name == m.currentChapter)
{
curChapter = c;
}
chapters.Add(c);
}
UpdateChapters();
UpdatePages(curChapter);
cmboPage.SelectedItem = m.currentPage;
}
19
View Source File : RegisterUserValidator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
bool IsValidPhoneNumber(string phoneNumber)
{
return Regex.Match(phoneNumber, @"^\+\(([0-9]{1,3})\)\s([0-9]{3})\-([0-9]{3})\-([0-9]{3})$").Success;
}
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 : 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 EffectArgument ParseEffectArgument(string filename, Effect effect, string operand)
{
var effectArgument = new EffectArgument();
effectArgument.Type = GetEffectArgumentType(effect, operand);
switch (effectArgument.Type)
{
case EffectArgumentType.Int:
if (!int.TryParse(operand, out effectArgument.IntVal))
{
if (effect.Quality != null && effect.Quality.StatType == StatType.Int && effect.Quality.StatIdx == (int)PropertyInt.ImbuedEffect && Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
effectArgument.IntVal = (int)imbuedEffectType;
else if (Enum.TryParse(operand, out WieldRequirement wieldRequirement))
effectArgument.IntVal = (int)wieldRequirement;
else if (Enum.TryParse(operand, out Skill skill))
effectArgument.IntVal = (int)skill;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}");
}
break;
case EffectArgumentType.Int64:
if (!long.TryParse(operand, out effectArgument.LongVal))
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}");
}
break;
case EffectArgumentType.Double:
if (!double.TryParse(operand, out effectArgument.DoubleVal))
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}");
}
break;
case EffectArgumentType.Quality:
effectArgument.StatType = GetStatType(operand);
switch (effectArgument.StatType)
{
case StatType.Int:
if (Enum.TryParse(operand, out PropertyInt propInt))
effectArgument.StatIdx = (int)propInt;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}");
break;
case StatType.Int64:
if (Enum.TryParse(operand, out PropertyInt64 propInt64))
effectArgument.StatIdx = (int)propInt64;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}");
break;
case StatType.Float:
if (Enum.TryParse(operand, out PropertyFloat propFloat))
effectArgument.StatIdx = (int)propFloat;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}");
break;
case StatType.Bool:
if (Enum.TryParse(operand, out PropertyBool propBool))
effectArgument.StatIdx = (int)propBool;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
break;
case StatType.DataID:
if (Enum.TryParse(operand, out PropertyDataId propDID))
effectArgument.StatIdx = (int)propDID;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
break;
default:
log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}");
break;
}
break;
case EffectArgumentType.Random:
var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)");
if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal))
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");
break;
case EffectArgumentType.Variable:
match = Regex.Match(operand, @"\[(\d+)\]");
if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal))
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");
break;
default:
log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}");
break;
}
return effectArgument;
}
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
public static bool IsNumber(string operand)
{
var match = Regex.Match(operand, @"([\d.-]+)");
return match.Success && match.Groups[1].Value.Equals(operand);
}
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 void CacheResourceNames()
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var resourceNames = replacedembly.GetManifestResourceNames();
foreach (var resourceName in resourceNames)
{
var pieces = resourceName.Split('.');
if (pieces.Length < 2)
{
log.Error($"MutationCache.CacheResourceNames() - unknown resource format {resourceName}");
continue;
}
var shortName = pieces[pieces.Length - 2];
var match = Regex.Match(shortName, @"([0-9A-F]{8})");
if (match.Success && uint.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var mutationId))
mutationIdToFilename[mutationId] = resourceName.Replace(prefix, "");
}
}
19
View Source File : LootParser.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 ChanceTable<SpellId> ParseChanceTable_Spell(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<SpellId>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"SpellId.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out SpellId spell) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((spell, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<WeenieClreplacedName> ParseChanceTable_Wcid(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<WeenieClreplacedName>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"WeenieClreplacedName.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out WeenieClreplacedName wcid) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((wcid, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<bool> ParseChanceTable_Bool(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<bool>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"\(\s+([^,]+),\s+([\d.]+)");
if (!match.Success || !bool.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((val, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<TreasureHeritageGroup> ParseChanceTable_Heritage(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<TreasureHeritageGroup>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"TreasureHeritageGroup.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureHeritageGroup heritage) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((heritage, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<TreasureItemType_Orig> ParseChanceTable_ItemType(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<TreasureItemType_Orig>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"TreasureItemType_Orig.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureItemType_Orig itemType) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((itemType, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<TreasureArmorType> ParseChanceTable_ArmorType(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<TreasureArmorType>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"TreasureArmorType.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureArmorType armorType) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((armorType, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 ChanceTable<TreasureWeaponType> ParseChanceTable_WeaponType(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<TreasureWeaponType>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"TreasureWeaponType.([^,]+),\s+([\d.]+)");
if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureWeaponType weaponType) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((weaponType, chance));
}
return chanceTable;
}
19
View Source File : LootParser.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 TreasureTableType GetTableType(string line)
{
var match = Regex.Match(line, @"<([^>]+)");
if (!match.Success)
return TreasureTableType.Undef;
switch (match.Groups[1].Value)
{
case "int":
return TreasureTableType.ChanceInt;
case "SpellId":
return TreasureTableType.ChanceSpell;
case "WeenieClreplacedName":
return TreasureTableType.ChanceWcid;
case "bool":
return TreasureTableType.ChanceBool;
case "TreasureHeritageGroup":
return TreasureTableType.ChanceHeritage;
case "TreasureItemType_Orig":
return TreasureTableType.ChanceItemType;
case "TreasureArmorType":
return TreasureTableType.ChanceArmorType;
case "TreasureWeaponType":
return TreasureTableType.ChanceWeaponType;
}
return TreasureTableType.Undef;
}
19
View Source File : LootParser.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 GetTableName(string line)
{
var match = Regex.Match(line, @"> ([^ ]+)");
if (!match.Success)
return null;
return match.Groups[1].Value;
}
19
View Source File : LootParser.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 ChanceTable<int> ParseChanceTable_Int(string[] lines, int startLine)
{
var chanceTable = new ChanceTable<int>();
for (var i = startLine + 1; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line.Length < 2)
continue;
if (line.Length == 2)
break;
if (line.StartsWith("//"))
continue;
var match = Regex.Match(line, @"(\d+),\s+([\d.]+)");
if (!match.Success || !int.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
{
Console.WriteLine($"Couldn't parse {line}");
continue;
}
chanceTable.Add((val, chance));
}
return chanceTable;
}
19
View Source File : RenameManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public static string IncrementLast(string val, string search, string replace)
{
var match = Regex.Match(val, search);
if (match.Success) {
var matchLength = match.Groups[2].Value.Length;
if (int.TryParse(match.Groups[2].Value, out int n) && int.TryParse(replace, out int incVal)) {
var i = n + incVal;
string pad = string.Empty;
if (i > 0) {
for (int j = (int)Math.Floor(Math.Log10(i)); j < (matchLength - 1); j++) {
pad += "0";
}
}
return Regex.Replace(val, search, m => m.Groups[1].Value + pad + i);
}
}
return val;
}
19
View Source File : RenameManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public static string Increment(string val, string search, string replace)
{
if (string.IsNullOrEmpty(val) || string.IsNullOrEmpty(search)) {
return val;
}
var match = Regex.Match(val, search);
if (match.Success) {
var matchLength = match.Groups[1].Value.Length;
if (int.TryParse(match.Groups[1].Value, out int n) && int.TryParse(replace, out int incVal)) {
var i = n + incVal;
var firstPart = val.Substring(0, match.Groups[1].Index);
var secondPart = val.Substring(match.Groups[1].Index + match.Groups[1].Length);
var pad = string.Empty;
if (i > 0) {
for (var j = (int)Math.Floor(Math.Log10(i)); j < (matchLength - 1); j++) {
pad += "0";
}
}
return firstPart + pad + i + secondPart;
}
}
return val;
}
19
View Source File : VssResponseContext.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public bool TryGetErrorCode(out string value)
{
value = null;
if (Exception == null)
{
return false;
}
var message = Exception.Message;
var match = Regex.Match(message, @"(TF[0-9]+)");
if (match.Success)
{
value = match.Value;
return true;
}
match = Regex.Match(message, @"(VSS[0-9]+)");
if (match.Success)
{
value = match.Value;
return true;
}
return false;
}
19
View Source File : SimpleEditor.cs
License : GNU General Public License v3.0
Project Creator : adam8797
License : GNU General Public License v3.0
Project Creator : adam8797
private void AutoIndent_InsertCheck(object sender, InsertCheckEventArgs e)
{
if (_styler != null)
{
if (e.Text.EndsWith("\r") || e.Text.EndsWith("\n"))
{
int startPos = Lines[LineFromPosition(CurrentPosition)].Position;
int endPos = e.Position;
string curLineText = GetTextRange(startPos, (endPos - startPos));
//Text until the caret so that the whitespace is always equal in every line.
Match indent = Regex.Match(curLineText, "^[ \\t]*");
e.Text = (e.Text + indent.Value);
if (Regex.IsMatch(curLineText, _styler.IndentChar + "\\s*$"))
{
e.Text = (e.Text + " ");
}
}
}
}
19
View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private static string ExpectedOutput(
string code,
string channel,
string testCasePath)
{
// First check if there is a file for the expected output
var match = Regex.Match(code, string.Format(CultureInfo.InvariantCulture, ExpectedOutputFileFormat, channel));
var path = match.Groups["file"]?.Captures.SingleOrDefault()?.Value;
if (path != null)
{
var testCaseDirectory = Path.GetDirectoryName(testCasePath) ?? throw new InvalidOperationException();
path = Path.Combine(testCaseDirectory, path);
return File.ReadAllText(path);
}
// Then look for inline expected output
match = Regex.Match(code, string.Format(CultureInfo.InvariantCulture, ExpectedOutputFormat, channel));
return match.Groups["output"]?.Captures.SingleOrDefault()?.Value ?? "";
}
19
View Source File : PortalRoutingModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected virtual void RewriteVirtualPath(object sender, EventArgs args)
{
if (!RewriteVirtualPathEnabled) return;
var application = sender as HttpApplication;
var context = application.Context;
var url = context.Request.Url.PathAndQuery;
var match = Regex.Match(url, @"~/.*");
if (match.Success)
{
var rewritePath = match.Value;
Tracing.FrameworkInformation("PortalRoutingModule", "RewriteVirtualPath", "Redirecting '{0}' to '{1}'", url, rewritePath);
// perform a redirect to prevent ~/ from appearing in the client address as well as redundant URLs
context.RedirectAndEndResponse(rewritePath);
}
}
19
View Source File : TerminalCommonNameValidator.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public static bool ValidateCertificate(string certificateSubject, Model.Enum.Environment environment)
{
var environmentName = environment.ToString().ToLower();
var regexPatternTerminalSpecificCert = _terminalApiCnRegex.Replace(_environmentWildcard, environmentName);
var regexPatternLegacyCert = _terminalApiLegacy.Replace(_environmentWildcard, environmentName);
var subject = certificateSubject.Split(',')
.Select(x => x.Split('='))
.ToDictionary(x => x[0].Trim(' '), x => x[1]);
if (subject.ContainsKey("CN"))
{
string commonNameValue = subject["CN"];
if (Regex.Match(commonNameValue, regexPatternTerminalSpecificCert).Success || string.Equals(commonNameValue, regexPatternLegacyCert))
{
return true;
}
}
return false;
}
19
View Source File : EpubViewer.cs
License : MIT License
Project Creator : Aeroblast
License : MIT License
Project Creator : Aeroblast
public static void SendDataWhenLoad(Object sender, LoadingStateChangedEventArgs e)
{
#if !DEBUG
try
{
#endif
if (e.IsLoading == true) return;
if (Program.epub.spine.pageProgressionDirection == "rtl")
{
chromium.ExecuteScriptAsync("direction = direction_rtl;");
}
string userDataCmd = string.Format("LoadUserSettings({0});", UserSettings.GetJson());
string initCmd = "";
string lengthDataCmd = "";
foreach (Itemref i in Program.epub.spine)
{
if (!i.linear) continue;
initCmd += string.Format(",'{0}'", "aeroepub://domain/book/" + i.ToString());
int l;
if (i.item.mediaType == "application/xhtml+xml")
{
l = (i.item.GetFile() as TextEpubFileEntry).text.Length;
}
else if (i.item.mediaType.Contains("image")) { l = 10; }
else
{
throw new Exception("Cannot Handle type in spine:" + i.item.mediaType);
}
lengthDataCmd += "," + l;
}
if (lengthDataCmd.Length == 0) throw new Exception("Spine is empty.");
lengthDataCmd = $"LoadScrollBar([{ lengthDataCmd.Substring(1)}],{new TocManager().GetPlainStructJSON()});";
initCmd = string.Format("Init([{0}],{1},{2});", initCmd.Substring(1), ResizeManage.index, ResizeManage.percent);
chromium.ExecuteScriptAsync(userDataCmd + lengthDataCmd + initCmd);
if (Program.epub.toc != null)
{
switch (Program.epub.toc.mediaType)
{
case "application/x-dtbncx+xml":
{
string toc = (Program.epub.toc.GetFile() as TextEpubFileEntry).text;
Match m = Regex.Match(toc, "<navMap>([\\s\\S]*?)</navMap>");
if (m.Success)
{
chromium.ExecuteScriptAsync("LoadTocNcx", m.Groups[1], Path.GetDirectoryName(Program.epub.toc.href));
}
else
{
Log.log("[Error]at TOC loading:" + Program.epub.toc);
}
}
break;
case "application/xhtml+xml":
{
string toc = (Program.epub.toc.GetFile() as TextEpubFileEntry).text;
toc = toc.Replace(" href=\"", " hraf=\"");
Match m = Regex.Match(toc, "<body[\\s\\S]*?>([\\s\\S]*?)</body>");
if (m.Success)
{
chromium.ExecuteScriptAsync("LoadTocNav", m.Groups[1], Path.GetDirectoryName(Program.epub.toc.href).Replace('\\', '/'));
}
else
{
Log.log("[Error]at TOC loading:" + Program.epub.toc);
}
}
break;
}
}
chromium.LoadingStateChanged -= SendDataWhenLoad;
#if !DEBUG
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
Application.Exit();
}
#endif
}
19
View Source File : FileUploadConverter.cs
License : MIT License
Project Creator : afaniuolo
License : MIT License
Project Creator : afaniuolo
public override string ConvertValue(string sourceValue)
{
// Parse the value to get the media item ID
// Example: sitecore://master/{A1207618-AFC1-465A-A45A-5F1C47A59B34}?lang=en&ver=1
var mediaItemRegexMatch = Regex.Match(sourceValue, @"sitecore:\/\/master\/(.*)\?lang=(.*)&ver=1");
var mediaItemId = mediaItemRegexMatch.Groups[1].Value;
var mediaItemLanguage = mediaItemRegexMatch.Groups[2].Value;
if (string.IsNullOrEmpty(mediaItemId) || !Guid.TryParse(mediaItemId, out var mediaItemGuid))
{
return sourceValue;
}
// Get the media item from source master db and map fields
var mediaItem = _sourceMasterRepository.GetSitecoreItem(mediaItemGuid);
if (string.IsNullOrEmpty(mediaItem.Name)) return sourceValue;
return mediaItemGuid.ToString("D");
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string returnData = sb.ToString();
string dataVer = Regex.Match(returnData, @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(returnData, @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(returnData, @"UpdateInfo\[(.*?)\]").Groups[1].Value));
string dataDownloadLink = Regex.Match(returnData, @"DownloadLink\[(.*?)\]").Groups[1].Value;
string datareplacedytics = Regex.Match(returnData, @"Googlereplacedytics\[([A-Za-z\-0-9]*?)\]").Groups[1].Value;
string dataIPService = Regex.Match(returnData, @"IPService\[(.*?)\]").Groups[1].Value;
//MessageBox.Show(dataSafe);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause anti-cheat software to trigger a ban. " +
"For any information, please check github.com/AgentRev/CoD-FoV-Changers\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
updateAvailable = true;
if (chkUpdate.Checked && updateNotify)
{
MessageBox.Show(this, "Update v" + dataVer + " is available at MapModNews.com\nClicking the \"Help\" button below will take you to the download page." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nInfos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, (!String.IsNullOrEmpty(dataDownloadLink) ? dataDownloadLink : "http://ghostsfov.ftp.sh/"));
lblUpdateAvail.Text = "Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}
else
{
requestSent = false;
}
}));
}
if (!String.IsNullOrEmpty(datareplacedytics))
{
Greplacedytics.trackingID = datareplacedytics;
}
if (!String.IsNullOrEmpty(dataIPService))
{
Greplacedytics.ipService = dataIPService;
}
}
catch {}
try
{
Greplacedytics.Triggerreplacedytics((string)gameMode.GetValue("c_settingsDirName") + " v" + c_toolVer, firstTime);
}
catch {}
}
19
View Source File : GAnalytics.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
public static int GetUniqueID()
{
string commentForCodeLurkers = "This is to find the public IPv4 address of the client to use it as unique ID for replacedytics";
try
{
var client = new TimedWebClient();
var ipAddress = client.DownloadString(ipService);
ipAddress = Regex.Match(ipAddress, @"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})").Groups[1].Value;
return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
}
catch
{
Random rnd = new Random();
return rnd.Next(int.MinValue, int.MaxValue);
}
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x1000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]+)\]").Groups[1].Value;
string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]+)\]").Groups[1].Value;
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
DialogResult vacResult = MessageBox.Show("It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " +
"For any information, please check MapModNews.com.\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK) Application.Exit();
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
lblUpdateAvail.Text = "└ Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
if (updateChk) MessageBox.Show("Update v" + dataVer + " for the FoV Changer is available at MapModNews.com",
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information);
TimerBlink.Start();
}
}
catch { }
requestSent = false;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void UpdateResponse(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream resStream = response.GetResponseStream();
string tempString;
int count;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[0x2000];
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value;
string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value;
string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(sb.ToString(), @"UpdateInfo\[(.*?)\]").Groups[1].Value));
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected")
{
this.Invoke(new Action(() =>
{
DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " +
"For any information, please check MapModNews.com.\n\n" +
"Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.",
"Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (vacResult == DialogResult.OK)
Application.Exit();
}));
}
//MessageBox.Show(dataVer);
if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer))
{
this.Invoke(new Action(() =>
{
if (updateChk)
MessageBox.Show(this, "Update v" + dataVer + " for the FoV Changer is available at MapModNews.com, or can be downloaded directly \nby clicking the \"Help\" button below." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nAdditional infos:\n" + dataInfo : ""),
"Update available", MessageBoxButtons.OK, MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1, 0, "http://mw3fov.ftp.sh/");
lblUpdateAvail.Text = " - Update v" + dataVer + " available";
lblUpdateAvail.Enabled = true;
lblUpdateAvail.Visible = true;
TimerBlink.Start();
}));
}
}
catch {}
requestSent = false;
}
19
View Source File : DomainUser.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static DomainUser Create(string str)
{
DomainUser user = null;
if (!string.IsNullOrEmpty(str))
{
var mc = Regex.Match(str, @"^(?<domain>.+)\\(?<user>.+)");
if (mc.Success)
{
user = new DomainUser()
{
Domain = mc.Groups["domain"].Value,
UserName = mc.Groups["user"].Value
};
}
else
{
user = new DomainUser()
{
Domain = Environment.MachineName.ToLower(),
UserName = str
};
}
}
return user;
}
19
View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static bool IsBuildInAccount(string account)
{
var sid = GetAccountSID(account);
return int.Parse(Regex.Match(sid, @"\d+$").Value) < 1000;
}
19
View Source File : DomainAccount.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static T Parse<T>(string str)
where T : DomainAccount, new()
{
T account = null;
if (!string.IsNullOrEmpty(str))
{
var mc = Regex.Match(str, @"^(?<domain>.+)\\(?<name>.+)");
if (mc.Success)
{
account = new T()
{
Domain = mc.Groups["domain"].Value,
Name = mc.Groups["name"].Value
};
}
else
{
account = new T()
{
Name = str
};
}
}
return account;
}
19
View Source File : GameSearch.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private List<string> ReadValueRegKey(RegistryKey key)
{
var dirs = new List<string>();
try
{
foreach (string valveSubKey in key.GetSubKeyNames())
{
using var subKey = key.OpenSubKey(valveSubKey);
var steamPath = subKey?.GetValue("InstallPath")?.ToString();
if (String.IsNullOrEmpty(steamPath))
continue;
var configPath = steamPath + "/steamapps/libraryfolders.vdf";
const string driveRegex = @"[A-Z]:\\";
if (File.Exists(configPath))
{
var configLines = File.ReadAllLines(configPath);
foreach (var line in configLines)
{
var match = Regex.Match(line, driveRegex);
if (line != string.Empty && match.Success)
{
var path = line.Substring(line.IndexOf(match.ToString()));
path = path.Replace("\\\\", "\\");
path = path.Replace("\"", "\\steamapps\\common\\");
dirs.Add(path);
}
}
dirs.Add(steamPath + "\\steamapps\\common\\");
}
}
}
catch { } //ignore errors
return dirs;
}
19
View Source File : ItemExchangeScrollParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
protected override List<ItemExchangeScrollMetadata> Parse()
{
List<ItemExchangeScrollMetadata> exchangeScroll = new();
foreach (PackFileEntry entry in Resources.XmlReader.Files)
{
if (!entry.Name.StartsWith("table/itemexchangescrolltable"))
{
continue;
}
XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
foreach (XmlNode node in doreplacedent.DoreplacedentElement.ChildNodes)
{
ItemExchangeScrollMetadata metadata = new();
if (node.Name == "exchange")
{
metadata.ExchangeId = int.Parse(node.Attributes["id"].Value);
metadata.Type = node.Attributes["type"].Value;
}
foreach (XmlNode childNode in node)
{
if (childNode.Name == "receipe")
{
metadata.RecipeId = int.Parse(childNode.Attributes["id"].Value);
metadata.RecipeRarity = byte.Parse(childNode.Attributes["rank"].Value);
metadata.RecipeAmount = short.Parse(childNode.Attributes["count"].Value);
}
else if (childNode.Name == "exchange")
{
metadata.RewardId = int.Parse(childNode.Attributes["id"].Value);
metadata.RewardRarity = byte.Parse(childNode.Attributes["rank"].Value);
metadata.RewardAmount = short.Parse(childNode.Attributes["count"].Value);
}
else if (childNode.Name == "require")
{
_ = int.TryParse(childNode.Attributes["meso"]?.Value ?? "0", out metadata.MesoCost);
foreach (XmlNode itemNode in childNode)
{
if (itemNode.Name != "item")
{
continue;
}
ItemRequirementMetadata item = new();
string[] parameters = itemNode.Attributes["id"].Value.Split(",");
parameters[0] = Regex.Match(parameters[0], @"\d+").Value; // remove text from item id
item.Id = int.Parse(parameters[0]);
item.Rarity = byte.Parse(parameters[1]);
item.Amount = short.Parse(parameters[2]);
metadata.ItemCost.Add(item);
}
}
}
exchangeScroll.Add(metadata);
}
}
return exchangeScroll;
}
19
View Source File : MapParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
private void AddMetadata(string xblock, IEnumerable<IMapEnreplacedy> enreplacedies)
{
if (xblock.EndsWith("_cn") || xblock.EndsWith("_jp") || xblock.EndsWith("_kr"))
{
return;
}
string mapIdStr = Regex.Match(xblock, @"\d{8}").Value;
if (string.IsNullOrEmpty(mapIdStr))
{
return;
}
MapMetadata metadata = new();
metadata.Id = int.Parse(mapIdStr);
metadata.XBlockName = xblock;
foreach (IMapEnreplacedy enreplacedy in enreplacedies)
{
if (enreplacedy is not IMS2CubeProp cube)
{
continue;
}
MapBlock mapBlock = new()
{
Coord = CoordS.From((short) cube.Position.X,
(short) cube.Position.Y,
(short) cube.Position.Z),
Type = cube.CubeType,
SaleableGroup = cube.CubeSalableGroup,
Attribute = cube.MapAttribute
};
metadata.Blocks.TryAdd(mapBlock.Coord, mapBlock);
}
if (metadata.Blocks.Count == 0)
{
return;
}
if (MapNames.ContainsKey(metadata.Id))
{
metadata.Name = MapNames[metadata.Id];
}
MapsList.Add(metadata);
}
19
View Source File : MagicPathParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
public static CoordF ParseCoordWithDuplicateDot(string input)
{
float[] floatArray = new float[input.Length];
for (int i = 0; i < input.Split(",").Length; i++)
{
floatArray[i] = float.Parse(Regex.Match(input.Split(",")[i], "[+-]?([0-9]*[.])?[0-9]+").Value);
}
return CoordF.From(floatArray[0], floatArray[1], floatArray[2]);
}
19
View Source File : MapEntityParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
private void BuildMetadata(string xblock, IEnumerable<IMapEnreplacedy> mapEnreplacedies)
{
if (xblock.EndsWith("_cn") || xblock.EndsWith("_jp") || xblock.EndsWith("_kr"))
{
return;
}
Match isParsableField = Regex.Match(xblock, @"^(\d{8})");
if (!isParsableField.Success)
{
// TODO: Handle these later, if we need them. They're xblock files with some other names like
// character_test.xblock, login.xblock,
return;
}
string mapId = isParsableField.Groups[1].Value;
if (Maps.ContainsKey(mapId))
{
return;
}
Maps.Add(mapId, xblock); // Only used to check if we've visited this node before.
// TODO: metadata should be keyed on xblock name, not mapId
MapEnreplacedyMetadata metadata = new(int.Parse(mapId));
foreach (IMapEnreplacedy enreplacedy in mapEnreplacedies)
{
switch (enreplacedy)
{
case IMS2Bounding bounding:
if (bounding.EnreplacedyName.EndsWith("0") && metadata.BoundingBox0.Equals(CoordS.From(0, 0, 0)))
{
metadata.BoundingBox0 = CoordS.FromVector3(bounding.Position);
}
else if (bounding.EnreplacedyName.EndsWith("1") && metadata.BoundingBox1.Equals(CoordS.From(0, 0, 0)))
{
metadata.BoundingBox1 = CoordS.FromVector3(bounding.Position);
}
break;
case IMS2PatrolData patrolData:
string patrolDataName = patrolData.EnreplacedyName.Replace("-", string.Empty);
List<string> wayPointIds = new();
foreach (KeyValuePair<string, string> entry in patrolData.WayPoints)
{
string wayPointId = entry.Value.Replace("-", string.Empty);
wayPointIds.Add(wayPointId);
}
List<string> arriveAnimations = new();
foreach (KeyValuePair<string, string> entry in patrolData.ArriveAnims)
{
arriveAnimations.Add(entry.Value);
}
List<string> approachAnimations = new();
foreach (KeyValuePair<string, string> entry in patrolData.ApproachAnims)
{
approachAnimations.Add(entry.Value);
}
List<int> arriveAnimationTimes = new();
foreach (KeyValuePair<string, uint> entry in patrolData.ArriveAnimsTime)
{
arriveAnimationTimes.Add((int) entry.Value);
}
metadata.PatrolDatas.Add(new(patrolDataName, wayPointIds, (int) patrolData.PatrolSpeed, patrolData.IsLoop, patrolData.IsAirWayPoint, arriveAnimations, approachAnimations, arriveAnimationTimes));
break;
case IMS2WayPoint wayPoint:
metadata.WayPoints.Add(new(wayPoint.EnreplacedyId, wayPoint.IsVisible, CoordS.FromVector3(wayPoint.Position), CoordS.FromVector3(wayPoint.Rotation)));
break;
// TODO: This can probably be more generally handled as IMS2RegionSkill
case IMS2HealingRegionSkillSound healingRegion:
if (healingRegion.Position == default)
{
continue;
}
metadata.HealingSpot.Add(CoordS.FromVector3(healingRegion.Position));
break;
case IMS2InteractObject interact:
InteractObjectType type = GetInteractObjectType(interact.interactID);
if (type == InteractObjectType.None)
{
continue;
}
switch (interact)
{
case IMS2SimpleUiObject uiObject:
metadata.InteractObjects.Add(new(uiObject.EnreplacedyId, uiObject.interactID, uiObject.Enabled, type));
break;
case IMS2InteractMesh interactMesh:
metadata.InteractObjects.Add(new(interactMesh.EnreplacedyId, interactMesh.interactID, interactMesh.IsVisible, type));
break;
case IMS2Telescope telescope:
metadata.InteractObjects.Add(new(telescope.EnreplacedyId, telescope.interactID, telescope.Enabled, type));
break;
case IMS2InteractActor interactActor:
metadata.InteractObjects.Add(new(interactActor.EnreplacedyId, interactActor.interactID, interactActor.IsVisible, type));
break;
case IMS2InteractDisplay interactDisplay:
metadata.InteractObjects.Add(new(interactDisplay.EnreplacedyId, interactDisplay.interactID, interactDisplay.IsVisible, type));
break;
}
break;
case ISpawnPoint spawn:
switch (spawn)
{
// TODO: Parse "value" from NPCList.
case IEventSpawnPointNPC eventSpawnNpc: // trigger mob/npc spawns
List<string> npcIds = new();
npcIds.AddRange(eventSpawnNpc.NpcList.Keys);
metadata.EventNpcSpawnPoints.Add(new(eventSpawnNpc.SpawnPointID, eventSpawnNpc.NpcCount, npcIds, eventSpawnNpc.SpawnAnimation, eventSpawnNpc.SpawnRadius,
CoordF.FromVector3(eventSpawnNpc.Position), CoordF.FromVector3(eventSpawnNpc.Rotation)));
break;
case ISpawnPointPC pcSpawn:
metadata.PlayerSpawns.Add(
new(CoordS.FromVector3(pcSpawn.Position), CoordS.FromVector3(pcSpawn.Rotation)));
break;
case ISpawnPointNPC npcSpawn:
// These tend to be vendors, shops, etc.
// If the name tag begins with SpawnPointNPC, I think these are mob spawn locations. Skipping these.
string npcIdStr = npcSpawn.NpcList.FirstOrDefault().Key ?? "0";
if (npcIdStr == "0" || !int.TryParse(npcIdStr, out int npcId))
{
continue;
}
MapNpc npc = new(npcId, npcSpawn.ModelName, npcSpawn.EnreplacedyName, CoordS.FromVector3(npcSpawn.Position),
CoordS.FromVector3(npcSpawn.Rotation), npcSpawn.IsSpawnOnFieldCreate, npcSpawn.dayDie, npcSpawn.nightDie);
// Parse some additional flat supplemented data about this NPC.
metadata.Npcs.Add(npc);
break;
}
break;
case IMS2RegionSpawnBase spawnBase:
switch (spawnBase)
{
case IMS2RegionBoxSpawn boxSpawn:
SpawnMetadata mobSpawnDataBox =
SpawnTagMap.ContainsKey(mapId) && SpawnTagMap[mapId].ContainsKey(boxSpawn.SpawnPointID)
? SpawnTagMap[mapId][boxSpawn.SpawnPointID]
: null;
int mobNpcCountBox = mobSpawnDataBox?.Population ?? 6;
int mobSpawnRadiusBox = 150;
// TODO: This previously relied in "NpcList" to be set. NpcList is impossible to be set on
// MS2RegionSpawn, it's only set for SpawnPointNPC.
List<int> mobNpcListBox = new()
{
21000025 // Placeholder
};
metadata.MobSpawns.Add(new(boxSpawn.SpawnPointID, CoordS.FromVector3(boxSpawn.Position),
mobNpcCountBox, mobNpcListBox, mobSpawnRadiusBox, mobSpawnDataBox));
// "QR_10000264_" is Quest Reward Chest? This is tied to a MS2TriggerAgent making this object appear.
break;
case IMS2RegionSpawn regionSpawn:
SpawnMetadata mobSpawnData =
SpawnTagMap.ContainsKey(mapId) && SpawnTagMap[mapId].ContainsKey(regionSpawn.SpawnPointID)
? SpawnTagMap[mapId][regionSpawn.SpawnPointID]
: null;
int mobNpcCount = mobSpawnData?.Population ?? 6;
// TODO: This previously relied in "NpcList" to be set. NpcList is impossible to be set on
// MS2RegionSpawn, it's only set for SpawnPointNPC.
List<int> mobNpcList = new()
{
21000025 // Placeholder
};
metadata.MobSpawns.Add(new(regionSpawn.SpawnPointID, CoordS.FromVector3(regionSpawn.Position),
mobNpcCount, mobNpcList, (int) regionSpawn.SpawnRadius, mobSpawnData));
break;
}
break;
case IPortal portal:
metadata.Portals.Add(new(portal.PortalID, portal.ModelName, portal.PortalEnable, portal.IsVisible, portal.MinimapIconVisible, portal.TargetFieldSN,
CoordS.FromVector3(portal.Position), CoordS.FromVector3(portal.Rotation), portal.TargetPortalID, (PortalTypes) portal.PortalType));
break;
case IMS2Breakable breakable:
switch (breakable)
{
case IMS2BreakableActor actor:
metadata.BreakableActors.Add(new(actor.EnreplacedyId, actor.Enabled, actor.hideTimer, actor.resetTimer));
break;
case IMS2BreakableNIF nif:
metadata.BreakableNifs.Add(new(nif.EnreplacedyId, nif.Enabled, (int) nif.TriggerBreakableID, nif.hideTimer, nif.resetTimer));
break;
}
break;
case IMS2TriggerObject triggerObject:
switch (triggerObject)
{
case IMS2TriggerMesh triggerMesh:
metadata.TriggerMeshes.Add(new(triggerMesh.TriggerObjectID, triggerMesh.IsVisible));
break;
case IMS2TriggerEffect triggerEffect:
metadata.TriggerEffects.Add(new(triggerEffect.TriggerObjectID, triggerEffect.IsVisible));
break;
case IMS2TriggerCamera triggerCamera:
metadata.TriggerCameras.Add(new(triggerCamera.TriggerObjectID, triggerCamera.Enabled));
break;
case IMS2TriggerBox triggerBox:
metadata.TriggerBoxes.Add(new(triggerBox.TriggerObjectID, CoordF.FromVector3(triggerBox.Position), CoordF.FromVector3(triggerBox.ShapeDimensions)));
break;
case IMS2TriggerLadder triggerLadder: // TODO: Find which parameters correspond to animationeffect (bool) and animation delay (int?)
metadata.TriggerLadders.Add(new(triggerLadder.TriggerObjectID, triggerLadder.IsVisible));
break;
case IMS2TriggerRope triggerRope: // TODO: Find which parameters correspond to animationeffect (bool) and animation delay (int?)
metadata.TriggerRopes.Add(new(triggerRope.TriggerObjectID, triggerRope.IsVisible));
break;
case IMS2TriggerPortal triggerPortal:
metadata.Portals.Add(new(triggerPortal.PortalID, triggerPortal.ModelName, triggerPortal.PortalEnable, triggerPortal.IsVisible, triggerPortal.MinimapIconVisible,
triggerPortal.TargetFieldSN, CoordS.FromVector3(triggerPortal.Position), CoordS.FromVector3(triggerPortal.Rotation), triggerPortal.TargetPortalID, (PortalTypes) triggerPortal.PortalType, triggerPortal.TriggerObjectID));
break;
case IMS2TriggerActor triggerActor:
metadata.TriggerActors.Add(new(triggerActor.TriggerObjectID, triggerActor.IsVisible, triggerActor.InitialSequence));
break;
case IMS2TriggerCube triggerCube:
metadata.TriggerCubes.Add(new(triggerCube.TriggerObjectID, triggerCube.IsVisible));
break;
case IMS2TriggerSound triggerSound:
metadata.TriggerSounds.Add(new(triggerSound.TriggerObjectID, triggerSound.Enabled));
break;
case IMS2TriggerSkill triggerSkill:
metadata.TriggerSkills.Add(new(triggerSkill.TriggerObjectID, triggerSkill.skillID,
(short) triggerSkill.skillLevel, (byte) triggerSkill.count, CoordF.FromVector3(triggerSkill.Position)));
break;
}
break;
case IMS2Liftable liftable:
metadata.LiftableObjects.Add(new(liftable.EnreplacedyId, (int) liftable.ItemID, liftable.MaskQuestID, liftable.MaskQuestState));
break;
case IMS2CubeProp prop:
if (prop.IsObjectWeapon)
{
List<int> weaponIds = prop.ObjectWeaponItemCode.Split(",").Select(int.Parse).ToList();
metadata.WeaponObjects.Add(new(CoordB.FromVector3(prop.Position), weaponIds));
}
break;
case IMS2Vibrate vibrate:
metadata.VibrateObjects.Add(new(vibrate.EnreplacedyId));
break;
}
/* NPC Objects have a modelName of 8 digits followed by an underscore and a name that's the same thing,
* but with a number (for each instance on that map) after it
*
* IM_ Prefixed items are Interactable Meshes supplemented by data in "xml/table/interactobject.xml"
* IA_ prefixed items are Interactable Actors (Doors, etc). Have an interactID, which is an event on interact.
* "mixinMS2MapProperties" is generic field items
* "mixinMS2SalePost" - is for sale signs. Does a packet need to respond to this item?
*/
/*
// Unhandled Items:
// "mixinEventSpawnPointNPC",
// "mixinMS2Actor" as in "fa_fi_funct_irondoor_A01_"
// MS2RegionSkill as in "SkillObj_co_Crepper_C03_" (Only on 8xxxx and 9xxxxx maps)
// "mixinMS2FunctionCubeKFM" as in "ry_functobj_lamp_B01_", "ke_functobj_bath_B01_"
// "mixinMS2FunctionCubeNIF"
// "MS2MapProperties"->"MS2PhysXProp" that's not a weapon. Standard
/*
* if (Regex.Match(modelName, @"^\d{8}_").Success && Regex.Match(name, @"\d{1,3}").Success)
* {
// Parse non-permanent NPCs. These have no .flat files to supplement them.
string npcListIndex = node.SelectSingleNode("property[@name='NpcList']")?.FirstChild.Attributes["index"].Value ?? "-1";
if (npcListIndex == "-1")
{
continue;
}
string npcPositionValue = node.SelectSingleNode("property[@name='Position']")?.FirstChild.Attributes["value"].Value ?? "0, 0, 0";
string npcRotationValue = node.SelectSingleNode("property[@name='Rotation']")?.FirstChild.Attributes["value"].Value ?? "0, 0, 0";
// metadata.Npcs.Add(new MapNpc(int.Parse(npcListIndex), modelName, name, ParseCoord(npcPositionValue), ParseCoord(npcRotationValue)));
}
*/
}
// No data on this map
if (metadata.Npcs.Count == 0 && metadata.Portals.Count == 0 && metadata.PlayerSpawns.Count == 0)
{
return;
}
Enreplacedies.Add(metadata);
}
19
View Source File : Auth.cs
License : MIT License
Project Creator : AlaricGilbert
License : MIT License
Project Creator : AlaricGilbert
private static async Task<string> EncryptPreplacedword(string preplacedWord)
{
string base64String;
string url = "https://preplacedport.bilibili.com/login?act=getkey&_=" + Common.TimeSpan;
using (HttpClient hc = new HttpClient())
{
var response = await hc.GetAsync(url);
var stringAsync = await response.Content.ReadreplacedtringAsync();
JObject jObjects = JObject.Parse(stringAsync);
string str = jObjects["hash"].ToString();
string str1 = jObjects["key"].ToString();
string str2 = string.Concat(str, preplacedWord);
string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
byte[] numArray = Convert.FromBase64String(str3);
Asn1Object obj = Asn1Object.FromByteArray(numArray);
DerSequence publicKeySequence = (DerSequence)obj;
DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
DerSequence publicKey = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());
DerInteger modulus = (DerInteger)publicKey[0];
DerInteger exponent = (DerInteger)publicKey[1];
RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parameters);
var result = rsa.Encrypt(Encoding.UTF8.GetBytes(str2), RSAEncryptionPadding.Pkcs1);
base64String = Convert.ToBase64String(result);
}
return base64String;
}
19
View Source File : Jsonizer.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
public static Pairs< string, object > Parse(string s)
{
var ret = new Pairs< string, object >();
s = s.Trim();
//check for enclosing brackets
if (!Regex.Match(s, @"^{.*}$").Success)
throw new InvalidOperationException("[Jsonizer] Bad json format while parsing '" + s + "'");
//remove enclosing brackets
s = s.Substring(1);
s = s.Substring(0, s.Length - 1);
//magic regex to parse exluding commas
var datas = Regex.Matches(s, @"([\""].+?[\""]|\S+)\s*:\s*([\(].+?[\)]|[^,]+)")
.Cast< Match >()
.Select(m => m.Value);
foreach (var data in datas)
ret.Add(ParsePart(data.Trim()));
return ret;
}
19
View Source File : DependenciesHunter.cs
License : MIT License
Project Creator : AlexeyPerov
License : MIT License
Project Creator : AlexeyPerov
public static bool IsValidForOutput(string path, List<string> ignoreInOutputPatterns)
{
return ignoreInOutputPatterns.All(pattern
=> string.IsNullOrEmpty(pattern) || !Regex.Match(path, pattern).Success);
}
19
View Source File : ADL.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static int ADL_Adapter_AdapterInfo_Get(ADLAdapterInfo[] info) {
int elementSize = Marshal.SizeOf(typeof(ADLAdapterInfo));
int size = info.Length * elementSize;
IntPtr ptr = Marshal.AllocHGlobal(size);
int result = _ADL_Adapter_AdapterInfo_Get(ptr, size);
for (int i = 0; i < info.Length; i++)
info[i] = (ADLAdapterInfo)
Marshal.PtrToStructure((IntPtr)((long)ptr + i * elementSize),
typeof(ADLAdapterInfo));
Marshal.FreeHGlobal(ptr);
// the ADLAdapterInfo.VendorID field reported by ADL is wrong on
// Windows systems (parse error), so we fix this here
for (int i = 0; i < info.Length; i++) {
// try Windows UDID format
Match m = Regex.Match(info[i].UDID, "PCI_VEN_([A-Fa-f0-9]{1,4})&.*");
if (m.Success && m.Groups.Count == 2) {
info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 16);
continue;
}
// if above failed, try Unix UDID format
m = Regex.Match(info[i].UDID, "[0-9]+:[0-9]+:([0-9]+):[0-9]+:[0-9]+");
if (m.Success && m.Groups.Count == 2) {
info[i].VendorID = Convert.ToInt32(m.Groups[1].Value, 10);
}
}
return result;
}
See More Examples