Here are the examples of the csharp api string.Trim() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
15004 Examples
19
Source : LootParser.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : LootParser.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : LootParser.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : LootParser.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : PacketHeaderOptional.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override string ToString()
{
if (Size == 0 || !IsValid)
{
return string.Empty;
}
string nice = "";
if (Header.HasFlag(PacketHeaderFlags.Flow))
{
nice = $" {FlowBytes} Interval: {FlowInterval}";
}
if (RetransmitData != null)
{
nice += $" requesting {RetransmitData.DefaultIfEmpty().Select(t => t.ToString()).Aggregate((a, b) => a + "," + b)}";
}
if (Header.HasFlag(PacketHeaderFlags.AckSequence))
{
nice += $" AckSeq: {AckSequence}";
}
return nice.Trim();
}
19
Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool TryParsePosition(string[] parameters, out string errorMessage, out Position position, int startingElement = 0)
{
errorMessage = string.Empty;
position = null;
if (parameters.Length - startingElement - 1 < 1)
{
errorMessage = "not enough parameters";
return false;
}
string northSouth = parameters[startingElement].ToLower().Replace(",", "").Trim();
string eastWest = parameters[startingElement + 1].ToLower().Replace(",", "").Trim();
if (!northSouth.EndsWith("n") && !northSouth.EndsWith("s"))
{
errorMessage = "Missing n or s indicator on first parameter";
return false;
}
if (!eastWest.EndsWith("e") && !eastWest.EndsWith("w"))
{
errorMessage = "Missing e or w indicator on second parameter";
return false;
}
if (!float.TryParse(northSouth.Substring(0, northSouth.Length - 1), out float coordNS))
{
errorMessage = "North/South coordinate is not a valid number.";
return false;
}
if (!float.TryParse(eastWest.Substring(0, eastWest.Length - 1), out float coordEW))
{
errorMessage = "East/West coordinate is not a valid number.";
return false;
}
if (northSouth.EndsWith("s"))
{
coordNS *= -1.0f;
}
if (eastWest.EndsWith("w"))
{
coordEW *= -1.0f;
}
try
{
position = new Position(coordNS, coordEW);
position.AdjustMapCoords();
}
catch (Exception e)
{
Console.WriteLine(e);
errorMessage = $"There was a problem with that location (bad coordinates?).";
return false;
}
return true;
}
19
Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void DoOutOfBoxSetup(string configFile)
{
var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
var configJsExample = Path.Combine(exeLocation, "Config.js.example");
var exampleFile = new FileInfo(configJsExample);
if (!exampleFile.Exists)
{
log.Error("config.js.example Configuration file is missing. Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
throw new Exception("missing config.js configuration file");
}
else
{
if (!IsRunningInContainer)
{
Console.WriteLine("config.js Configuration file is missing, cloning from example file.");
File.Copy(configJsExample, configFile, true);
}
else
{
Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container, cloning from docker file.");
var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
File.Copy(configJsDocker, configFile, true);
}
}
var fileText = File.ReadAllText(configFile);
var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));
Console.WriteLine("Performing setup for ACEmulator...");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
var variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.Server.WorldName = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
if (!string.IsNullOrWhiteSpace(variable))
{
var path = Path.GetFullPath(variable.Trim());
if (!Path.EndsInDirectorySeparator(path))
path += Path.DirectorySeparatorChar;
//path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");
config.Server.DatFilesDirectory = path;
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
Console.WriteLine("As before, pressing enter will use default value.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Database = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Host = variable.Trim();
config.MySql.Shard.Host = variable.Trim();
config.MySql.World.Host = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
}
Console.WriteLine();
}
else
{
Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "y";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Username = variable.Trim();
config.MySql.Shard.Username = variable.Trim();
config.MySql.World.Username = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Preplacedword = variable.Trim();
config.MySql.Shard.Preplacedword = variable.Trim();
config.MySql.World.Preplacedword = variable.Trim();
}
}
else
{
Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Preplacedword = variable.Trim();
}
Console.WriteLine("commiting configuration to memory...");
using (StreamWriter file = File.CreateText(configFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
//serializer.NullValueHandling = NullValueHandling.Ignore;
//serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
serializer.Serialize(file, config);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
for (; ; )
{
try
{
using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
{
Console.Write(".");
sqlTestConnection.Open();
}
break;
}
catch (MySql.Data.MySqlClient.MySqlException)
{
Console.Write(".");
Thread.Sleep(5000);
}
}
Console.WriteLine(" connected!");
if (IsRunningInContainer)
{
Console.Write("Clearing out temporary ace% database .... ");
var sqlDBFile = "DROP DATABASE `ace%`;";
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" done!");
}
Console.WriteLine("Searching for base SQL scripts .... ");
foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
{
Console.Write($"Found {file.Name} .... ");
var sqlDBFile = File.ReadAllText(file.FullName);
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
switch (file.Name)
{
case "AuthenticationBase":
sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
break;
case "ShardBase":
sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
break;
}
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" complete!");
}
Console.WriteLine("Base SQL scripts import complete!");
Console.WriteLine("Searching for Update SQL scripts .... ");
PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);
PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);
PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
if (IsRunningInContainer)
{
Console.WriteLine(" ");
Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
Console.WriteLine(" ");
}
Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");
// webrequest code provided by OptimShi
var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
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;
// webrequest code provided by OptimShi
Console.WriteLine($"Found {tag} !");
Console.Write($"Downloading {dbFileName} .... ");
using (var client = new WebClient())
{
client.DownloadFile(dbURL, dbFileName);
}
Console.WriteLine("download complete!");
Console.Write($"Extracting {dbFileName} .... ");
ZipFile.ExtractToDirectory(dbFileName, ".", true);
Console.WriteLine("extraction complete!");
Console.Write($"Deleting {dbFileName} .... ");
File.Delete(dbFileName);
Console.WriteLine("Deleted!");
var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
using (var sr = File.OpenText(sqlFile))
{
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");
var line = string.Empty;
var completeSQLline = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//do minimal amount of work here
if (line.EndsWith(";"))
{
completeSQLline += line + Environment.NewLine;
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
completeSQLline = string.Empty;
}
else
completeSQLline += line + Environment.NewLine;
}
}
Console.WriteLine(" complete!");
Console.Write($"Deleting {sqlFile} .... ");
File.Delete(sqlFile);
Console.WriteLine("Deleted!");
}
Console.WriteLine("exiting setup for ACEmulator.");
}
19
Source : TippingManager.cs
with MIT License
from acid-chicken
with MIT License
from acid-chicken
public static async Task<string> InvokeMethodAsync(params object[] args)
{
using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}))
using (var reader = process.StandardOutput)
{
var output = await reader.ReadToEndAsync().ConfigureAwait(false);
process.WaitForExit();
process.Close();
return output.Trim();
}
}
19
Source : MiscUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public static DateTime ToDateTime(string dateValue)
{
if (string.IsNullOrEmpty(dateValue))
{
return new DateTime();
}
var date = dateValue.Trim();
// ReSharper disable once InconsistentNaming
const string DateDelimiters = @"-.\/_ ";
char[] c = DateDelimiters.ToCharArray();
int d2 = date.LastIndexOfAny(c);
int d1 = date.IndexOfAny(c);
try
{
string year = string.Empty;
string month = string.Empty;
string day = string.Empty;
if (date.Length > d2 + 1)
{
year = date.Substring(d2 + 1);
}
if (date.Length > (d1 + 1) && (d2 - d1 - 1) < date.Length - (d1 + 1))
{
month = date.Substring(d1 + 1, d2 - d1 - 1);
}
if (date.Length > 0 && d1 <= date.Length)
{
day = date.Substring(0, d1);
}
return new DateTime(
Convert.ToInt32(year, CultureInfo.InvariantCulture),
Convert.ToInt32(month, CultureInfo.InvariantCulture),
Convert.ToInt32(day, CultureInfo.InvariantCulture));
}
catch (ArgumentOutOfRangeException e)
{
Debug.WriteLine("Error in ToDateTime:" + e.Message);
return new DateTime();
}
catch (FormatException e)
{
Debug.WriteLine("Error in ToDateTime:" + e.Message);
return new DateTime();
}
catch (OverflowException e)
{
Debug.WriteLine("Error in ToDateTime:" + e.Message);
return new DateTime();
}
}
19
Source : Hatch.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
private bool replacedignFillGridsFromString(string[] grids, double scale, double rotationAngle)
{
var newFillGrids = new List<FillGrid>();
foreach (string s in grids) {
if (string.IsNullOrEmpty(s.Trim()))
{
continue;
}
string[] segs = s.Split(',');
if (segs.Count() < 5)
{
return false;
}
var f = new FillGrid();
List<double> lineSegs = new List<double>();
if (!double.TryParse(segs[0], out var angle)) {
return false;
}
if (!double.TryParse(segs[1], out var x)) {
return false;
}
if (!double.TryParse(segs[2], out var y)) {
return false;
}
if (!double.TryParse(segs[3], out var shift)) {
return false;
}
if (!double.TryParse(segs[4], out var offset)) {
return false;
}
for (int i = 5; i < segs.Length; i++)
{
if (!double.TryParse(segs[i], out var individualSeg))
{
return false;
}
individualSeg *= scale;
lineSegs.Add(Math.Abs(individualSeg.ToFeet()));
}
x *= scale;
y *= scale;
shift *= scale;
offset *= scale;
angle += rotationAngle;
f.Angle = angle.ToRad();
f.Origin = new UV(x.ToFeet(), y.ToFeet());
f.Shift = shift.ToFeet();
f.Offset = offset.ToFeet();
f.SetSegments(lineSegs);
newFillGrids.Add(f);
}
fillPattern.SetFillGrids(newFillGrids);
return true;
}
19
Source : AboutViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public static string replacedemblyProduct()
{
object[] attributes = replacedembly.GetExecutingreplacedembly()
.GetCustomAttributes(typeof(replacedemblyProductAttribute), false);
return attributes.Length == 0 ? string.Empty : ((replacedemblyProductAttribute)attributes[0]).Product.Trim();
}
19
Source : Sheet.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public string RevitScaleWithoutFormatting()
{
var result = scale.Trim();
var i = 0;
if (result.Contains(":"))
{
i = result.IndexOf(':');
}
else
{
return "0";
}
return string.IsNullOrEmpty(result.Trim()) ? "0" : result.Substring(i + 2).Trim();
}
19
Source : HatchEditor.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public static List<Hatch> GetPatternFromFile(int startIndex, string[] array)
{
var result = new List<Hatch>();
for (int i = startIndex; i < array.Length - 2; i++)
{
if (array[i].Length > 1 && array[i].Trim().StartsWith(@"*", System.StringComparison.InvariantCulture)) {
var name = array[i].Substring(1).Trim();
i++;
var type = array[i].Trim();
var defs = new StringBuilder();
do
{
i++;
if (!array[i].StartsWith(@";", System.StringComparison.InvariantCulture)) {
defs.Append(array[i].Trim());
defs.Append(System.Environment.NewLine);
}
} while (i < (array.Length - 1) && !array[i + 1].Trim().StartsWith(@"*", System.StringComparison.InvariantCulture));
var hatch = new Hatch();
hatch.Name = name;
hatch.HatchPattern.Target = type.ToUpper(System.Globalization.CultureInfo.InvariantCulture).Contains("DRAFTING") ? FillPatternTarget.Drafting : FillPatternTarget.Model;
hatch.Definition = defs.ToString();
result.Add(hatch);
}
}
return result;
}
19
Source : ActionCommand.cs
with MIT License
from actions
with MIT License
from actions
public static bool TryParseV2(string message, HashSet<string> registeredCommands, out ActionCommand command)
{
command = null;
if (string.IsNullOrEmpty(message))
{
return false;
}
try
{
// the message needs to start with the keyword after trim leading space.
message = message.TrimStart();
if (!message.StartsWith(_commandKey))
{
return false;
}
// Get the index of the separator between the command info and the data.
int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
if (endIndex < 0)
{
return false;
}
// Get the command info (command and properties).
int cmdIndex = _commandKey.Length;
string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);
// Get the command name
int spaceIndex = cmdInfo.IndexOf(' ');
string commandName =
spaceIndex < 0
? cmdInfo
: cmdInfo.Substring(0, spaceIndex);
if (registeredCommands.Contains(commandName))
{
// Initialize the command.
command = new ActionCommand(commandName);
}
else
{
return false;
}
// Set the properties.
if (spaceIndex > 0)
{
string propertiesStr = cmdInfo.Substring(spaceIndex + 1).Trim();
string[] splitProperties = propertiesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string propertyStr in splitProperties)
{
string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
if (pair.Length == 2)
{
command.Properties[pair[0]] = UnescapeProperty(pair[1]);
}
}
}
command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
return true;
}
catch
{
command = null;
return false;
}
}
19
Source : CommandLineParser.cs
with MIT License
from actions
with MIT License
from actions
public void Parse(string[] args)
{
_trace.Info(nameof(Parse));
ArgUtil.NotNull(args, nameof(args));
_trace.Info("Parsing {0} args", args.Length);
string argScope = null;
foreach (string arg in args)
{
_trace.Info("parsing argument");
HasArgs = HasArgs || arg.StartsWith("--");
_trace.Info("HasArgs: {0}", HasArgs);
if (string.Equals(arg, "/?", StringComparison.Ordinal))
{
Flags.Add("help");
}
else if (!HasArgs)
{
_trace.Info("Adding Command: {0}", arg);
Commands.Add(arg.Trim());
}
else
{
// it's either an arg, an arg value or a flag
if (arg.StartsWith("--") && arg.Length > 2)
{
string argVal = arg.Substring(2);
_trace.Info("arg: {0}", argVal);
// this means two --args in a row which means previous was a flag
if (argScope != null)
{
_trace.Info("Adding flag: {0}", argScope);
Flags.Add(argScope.Trim());
}
argScope = argVal;
}
else if (!arg.StartsWith("-"))
{
// we found a value - check if we're in scope of an arg
if (argScope != null && !Args.ContainsKey(argScope = argScope.Trim()))
{
if (SecretArgNames.Contains(argScope))
{
_secretMasker.AddValue(arg);
}
_trace.Info("Adding option '{0}': '{1}'", argScope, arg);
// ignore duplicates - first wins - below will be val1
// --arg1 val1 --arg1 val1
Args.Add(argScope, arg);
argScope = null;
}
}
else
{
//
// ignoring the second value for an arg (val2 below)
// --arg val1 val2
// ignoring invalid things like empty - and --
// --arg val1 -- --flag
_trace.Info("Ignoring arg");
}
}
}
_trace.Verbose("done parsing arguments");
// handle last arg being a flag
if (argScope != null)
{
Flags.Add(argScope);
}
_trace.Verbose("Exiting parse");
}
19
Source : CorrectionCandidate.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public bool MoveNext()
{
while (originalWords != null && currentIndex < (originalWords.Length - 1))
{
currentIndex++;
// Continue if a number is found...
if (rgx.IsMatch(Currentreplacedtring)) {
continue;
}
if (autoReplacementList.ContainsKey(Currentreplacedtring)) {
string replacement;
if (autoReplacementList.TryGetValue(Currentreplacedtring, out replacement)) {
// FIXME this reaplces the first, not the current.
ReplaceCurrent(replacement);
continue;
}
}
if (!hunspell.Spell(originalWords[currentIndex].Trim())) {
return false;
}
}
// Reset here so any futures checks in this actually check the whole string.
Reset();
return true;
}
19
Source : ActionPlugin.cs
with MIT License
from actions
with MIT License
from actions
public VssConnection InitializeVssConnection()
{
var headerValues = new List<ProductInfoHeaderValue>();
headerValues.Add(new ProductInfoHeaderValue($"GitHubActionsRunner-Plugin", BuildConstants.RunnerPackage.Version));
headerValues.Add(new ProductInfoHeaderValue($"({RuntimeInformation.OSDescription.Trim()})"));
if (VssClientHttpRequestSettings.Default.UserAgent != null && VssClientHttpRequestSettings.Default.UserAgent.Count > 0)
{
headerValues.AddRange(VssClientHttpRequestSettings.Default.UserAgent);
}
VssClientHttpRequestSettings.Default.UserAgent = headerValues;
VssHttpMessageHandler.DefaultWebProxy = this.WebProxy;
ServiceEndpoint systemConnection = this.Endpoints.FirstOrDefault(e => string.Equals(e.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
ArgUtil.NotNull(systemConnection, nameof(systemConnection));
ArgUtil.NotNull(systemConnection.Url, nameof(systemConnection.Url));
VssCredentials credentials = VssUtil.GetVssCredential(systemConnection);
ArgUtil.NotNull(credentials, nameof(credentials));
return VssUtil.CreateConnection(systemConnection.Url, credentials);
}
19
Source : PromptManager.cs
with MIT License
from actions
with MIT License
from actions
public string ReadValue(
string argName,
string description,
bool secret,
string defaultValue,
Func<string, bool> validator,
bool unattended,
bool isOptional = false)
{
Trace.Info(nameof(ReadValue));
ArgUtil.NotNull(validator, nameof(validator));
string value = string.Empty;
// Check if unattended.
if (unattended)
{
// Return the default value if specified.
if (!string.IsNullOrEmpty(defaultValue))
{
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
// Otherwise throw.
throw new Exception($"Invalid configuration provided for {argName}. Terminating unattended configuration.");
}
// Prompt until a valid value is read.
while (true)
{
// Write the message prompt.
_terminal.Write($"{description} ");
if(!string.IsNullOrEmpty(defaultValue))
{
_terminal.Write($"[press Enter for {defaultValue}] ");
}
else if (isOptional){
_terminal.Write($"[press Enter to skip] ");
}
// Read and trim the value.
value = secret ? _terminal.ReadSecret() : _terminal.ReadLine();
value = value?.Trim() ?? string.Empty;
// Return the default if not specified.
if (string.IsNullOrEmpty(value))
{
if (!string.IsNullOrEmpty(defaultValue))
{
Trace.Info($"Falling back to the default: '{defaultValue}'");
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
}
// Return the value if it is not empty and it is valid.
// Otherwise try the loop again.
if (!string.IsNullOrEmpty(value))
{
if (validator(value))
{
return value;
}
else
{
Trace.Info("Invalid value.");
_terminal.WriteLine("Entered value is invalid", ConsoleColor.Yellow);
}
}
}
}
19
Source : VssUtil.cs
with MIT License
from actions
with MIT License
from actions
public static void InitializeVssClientSettings(List<ProductInfoHeaderValue> additionalUserAgents, IWebProxy proxy)
{
var headerValues = new List<ProductInfoHeaderValue>();
headerValues.AddRange(additionalUserAgents);
headerValues.Add(new ProductInfoHeaderValue($"({RuntimeInformation.OSDescription.Trim()})"));
if (VssClientHttpRequestSettings.Default.UserAgent != null && VssClientHttpRequestSettings.Default.UserAgent.Count > 0)
{
headerValues.AddRange(VssClientHttpRequestSettings.Default.UserAgent);
}
VssClientHttpRequestSettings.Default.UserAgent = headerValues;
VssHttpMessageHandler.DefaultWebProxy = proxy;
}
19
Source : DockerCommandManager.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command, List<string> output)
{
ArgUtil.NotNull(output, nameof(output));
string arg = $"exec {options} {containerId} {command}".Trim();
context.Command($"{DockerPath} {arg}");
object outputLock = new object();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
lock (outputLock)
{
output.Add(message.Data);
}
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
lock (outputLock)
{
output.Add(message.Data);
}
}
};
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
cancellationToken: CancellationToken.None);
}
19
Source : DockerCommandManager.cs
with MIT License
from actions
with MIT License
from actions
private async Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, IDictionary<string, string> environment, EventHandler<ProcessDataReceivedEventArgs> stdoutDataReceived, EventHandler<ProcessDataReceivedEventArgs> stderrDataReceived, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += stdoutDataReceived;
processInvoker.ErrorDataReceived += stderrDataReceived;
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: environment,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
cancellationToken: cancellationToken);
}
19
Source : DockerCommandManager.cs
with MIT License
from actions
with MIT License
from actions
private async Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, string workingDirectory, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: workingDirectory ?? context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
redirectStandardIn: null,
cancellationToken: cancellationToken);
}
19
Source : DockerCommandManager.cs
with MIT License
from actions
with MIT License
from actions
private async Task<List<string>> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options)
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
List<string> output = new List<string>();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
output.Add(message.Data);
context.Output(message.Data);
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
context.Output(message.Data);
}
};
await processInvoker.ExecuteAsync(
workingDirectory: context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: true,
outputEncoding: null,
cancellationToken: CancellationToken.None);
return output;
}
19
Source : OutputManager.cs
with MIT License
from actions
with MIT License
from 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
Source : TemplateValidationErrors.cs
with MIT License
from actions
with MIT License
from actions
public void Check(String prefix)
{
if (String.IsNullOrEmpty(prefix))
{
this.Check();
}
else if (m_errors.Count > 0)
{
var message = $"{prefix.Trim()} {String.Join(",", m_errors.Select(e => e.Message))}";
throw new TemplateValidationException(message, m_errors);
}
}
19
Source : ExpressionValue.cs
with MIT License
from actions
with MIT License
from actions
internal static String TrimExpression(String value)
{
var expression = value.Substring(2, value.Length - 3).Trim();
if (String.IsNullOrEmpty(expression))
{
throw new ArgumentException(PipelineStrings.ExpressionInvalid(value));
}
return expression;
}
19
Source : FlagsEnum.cs
with MIT License
from actions
with MIT License
from actions
public static object ParseKnownFlags(Type enumType, string stringValue)
{
ArgumentUtility.CheckForNull(enumType, nameof(enumType));
if (!enumType.IsEnum)
{
throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
}
// Check for the flags attribute in debug. Skip this reflection in release.
Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");
// The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
if (stringValue == null)
{
throw new ArgumentNullException(stringValue);
}
if (String.IsNullOrWhiteSpace(stringValue))
{
throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
}
if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
{
return Enum.Parse(enumType, stringValue);
}
var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
{
IDictionary<string, string> mappings = null;
foreach (var field in enumType.GetFields())
{
if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
{
if (mappings == null)
{
mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
}
}
return mappings;
});
var values = stringValue.Split(s_enumSeparatorCharArray);
var matches = new List<string>();
for (int i = 0; i < values.Length; i++)
{
string value = values[i].Trim();
if (String.IsNullOrEmpty(value))
{
throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
}
if (enumNames.Contains(value))
{
matches.Add(value);
}
else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
{
matches.Add(matchingValue);
}
}
if (!matches.Any())
{
return Enum.Parse(enumType, "0");
}
string matchesString = String.Join(", ", matches);
return Enum.Parse(enumType, matchesString, ignoreCase: true);
}
19
Source : ExpressionUtility.cs
with MIT License
from actions
with MIT License
from actions
internal static Double ParseNumber(String str)
{
// Trim
str = str?.Trim() ?? String.Empty;
// Empty
if (String.IsNullOrEmpty(str))
{
return 0d;
}
// Try parse
else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
{
return value;
}
// Check for 0x[0-9a-fA-F]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
{
return (Double)integer;
}
// Otherwise exceeds range
}
// Check for 0o[0-9]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integer = default(Int32?);
try
{
integer = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
}
// Success
if (integer != null)
{
return (Double)integer.Value;
}
}
// Infinity
else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
{
return Double.PositiveInfinity;
}
// -Infinity
else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
{
return Double.NegativeInfinity;
}
// Otherwise NaN
return Double.NaN;
}
19
Source : TemplateReader.cs
with MIT License
from actions
with MIT License
from actions
private ExpressionToken ParseExpression(
Int32? line,
Int32? column,
String value,
String[] allowedContext,
out Exception ex)
{
var trimmed = value.Trim();
// Check if the value is empty
if (String.IsNullOrEmpty(trimmed))
{
ex = new ArgumentException(TemplateStrings.ExpectedExpression());
return null;
}
// Try to find a matching directive
List<String> parameters;
if (MatchesDirective(trimmed, TemplateConstants.InsertDirective, 0, out parameters, out ex))
{
return new InsertExpressionToken(m_fileId, line, column);
}
else if (ex != null)
{
return null;
}
// Check if the value is an expression
if (!ExpressionToken.IsValidExpression(trimmed, allowedContext, out ex))
{
return null;
}
// Return the expression
return new BasicExpressionToken(m_fileId, line, column, trimmed);
}
19
Source : TemperatureTypeConverter.cs
with MIT License
from Actipro
with MIT License
from Actipro
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
string valueString = value as string;
if (null != valueString) {
valueString = valueString.Trim().ToUpperInvariant();
// Determine if Fahrenheit or Celsius
bool fahrenheit = true;
if (valueString.Length > 0) {
string scale = valueString.Substring(valueString.Length - 1);
bool removeLastChar = false;
if ("C" == scale) {
fahrenheit = false;
removeLastChar = true;
}
else if ("F" == scale) {
removeLastChar = true;
}
if (removeLastChar) {
if (valueString.Length > 1)
valueString = valueString.Substring(0, valueString.Length - 1).Trim();
else
valueString = string.Empty;
}
}
// Remove degree symbol, if it's there
if (valueString.Length > 0) {
string scale = valueString.Substring(valueString.Length - 1);
if ("°" == scale) {
if (valueString.Length > 1)
valueString = valueString.Substring(0, valueString.Length - 1).Trim();
else
valueString = string.Empty;
}
}
// Convert degrees portion using base clreplaced
double degrees = 0.0;
if (0 != valueString.Length)
degrees = (double)base.ConvertFrom(context, culture, valueString);
// Converter if needed
if (!fahrenheit)
degrees = degrees * 9 / 5 + 32.0;
return degrees;
}
return base.ConvertFrom(context, culture, value);
}
19
Source : UserAgentUtility.cs
with MIT License
from actions
with MIT License
from actions
private static List<ProductInfoHeaderValue> ConstructDefaultRestUserAgent()
{
// Pick up the replacedembly version from this dll
String fileVersion = "unavailable";
try
{
replacedemblyFileVersionAttribute attr = typeof(UserAgentUtility).GetTypeInfo().replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
if (attr != null)
{
fileVersion = attr.Version;
}
}
catch (Exception e)
{
Trace.WriteLine("DefaultUserAgent: Unable to get fileVersion: " + e.ToString());
}
String commentValue = string.Format("(NetStandard; {0})", RuntimeInformation.OSDescription.Replace('(', '[').Replace(')', ']').Trim());
return new List<ProductInfoHeaderValue> {
new ProductInfoHeaderValue("VSServices", fileVersion),
new ProductInfoHeaderValue(commentValue) };
}
19
Source : TraceFormat.cs
with GNU Affero General Public License v3.0
from active-logic
with GNU Affero General Public License v3.0
from active-logic
public static string LogTrace(LogTrace trace){
if(trace == null) return "?trace";
var @out = string.Format(
"{0}{1} {2}", trace.prefix ?? null,
trace.scope,
Reason(trace.reason, trace.isDecorator)
).Trim();
return trace.next == null ? @out : $"{@out} -> {LogTrace(trace.next)}";
}
19
Source : BankIdSupportedDeviceDetector.cs
with MIT License
from ActiveLogin
with MIT License
from ActiveLogin
public BankIdSupportedDevice Detect(string userAgent)
{
var normalizedUserAgent = userAgent?.ToLower().Trim() ?? string.Empty;
var deviceOs = GetDeviceOs(normalizedUserAgent);
var deviceOsVersion = GetDeviceOsVersion(normalizedUserAgent);
var deviceBrowser = GetDeviceBrowser(normalizedUserAgent);
var deviceType = GetDeviceType(deviceOs);
return new BankIdSupportedDevice(deviceType, deviceOs, deviceBrowser, deviceOsVersion);
}
19
Source : BankIdSupportedDeviceDetector.cs
with MIT License
from ActiveLogin
with MIT License
from ActiveLogin
private static BankIdSupportedDeviceOsVersion GetAndroidVersion(string userAgent)
{
if(string.IsNullOrWhiteSpace(userAgent))
{
return BankIdSupportedDeviceOsVersion.Empty;
}
try
{
//Example userAgent for Android "Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36";
const string Android = "android";
var versionNumber = userAgent.Substring(userAgent.IndexOf(Android, StringComparison.Ordinal) + Android.Length).Trim();
versionNumber = versionNumber.Substring(0, versionNumber.IndexOf(";", StringComparison.Ordinal));
var versionNumberList = versionNumber.Split('.').Select(v => int.TryParse(v, out var version) ? version : 0).ToArray();
return versionNumberList.Length switch
{
1 => new BankIdSupportedDeviceOsVersion(versionNumberList[0]),
2 => new BankIdSupportedDeviceOsVersion(versionNumberList[0], versionNumberList[1]),
3 => new BankIdSupportedDeviceOsVersion(versionNumberList[0], versionNumberList[1], versionNumberList[2]),
_ => BankIdSupportedDeviceOsVersion.Empty
};
}
19
Source : RoslynSyntaxUtils.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static SyntaxTrivia ToSingleLineComment(this string commentContent)
{
const string commentPrefix = "//";
string comment = commentContent.IsNullOrWhiteSpace()
? commentPrefix
: commentPrefix + " " + commentContent.Trim();
return SyntaxFactory.Comment(comment);
}
19
Source : RawPriceDataParser.cs
with MIT License
from adainrivers
with MIT License
from adainrivers
private static int? RomanToInt(string roman)
{
if (roman == null)
{
return null;
}
switch (roman.Trim().ToUpperInvariant())
{
case "I":
return 1;
case "II":
return 2;
case "III":
return 3;
case "IV":
return 4;
case "V":
return 5;
default:
return null;
}
}
19
Source : SimpleEditor.cs
with GNU General Public License v3.0
from adam8797
with GNU General Public License v3.0
from adam8797
private void AutoIndent_CharAdded(object sender, CharAddedEventArgs e)
{
if (_styler != null)
{
if (_styler.IndentChar == e.Char)
{
int curLine = LineFromPosition(CurrentPosition);
if (Lines[curLine].Text.Trim() == "}")
{
//Check whether the bracket is the only thing on the line.. For cases like "if() { }".
SetIndent(curLine, GetIndent(curLine) - 4);
}
}
else if (_styler.OutdentChar == e.Char)
{
int curLine = LineFromPosition(CurrentPosition);
if (Lines[curLine].Text.Trim() == "" + _styler.OutdentChar)
{
SetIndent(curLine, GetIndent(curLine) - 4);
}
}
}
}
19
Source : Parser.cs
with MIT License
from adamant
with MIT License
from adamant
private static string? GetConfig(IEnumerable<string> lines, string config)
{
var start = Program.DirectiveMarker + config;
var line = lines.SingleOrDefault(l => l.StartsWith(start, StringComparison.InvariantCulture));
line = line?.Substring(start.Length);
line = line?.TrimEnd(';'); // TODO error if no semicolon
line = line?.Trim();
return line;
}
19
Source : Parser.cs
with MIT License
from adamant
with MIT License
from adamant
private static IEnumerable<string> GetUsingNamespaces(IEnumerable<string> lines)
{
const string start = Program.DirectiveMarker + "using";
lines = lines.Where(l => l.StartsWith(start, StringComparison.InvariantCulture));
// TODO error if no semicolon
return lines.Select(l => l.Substring(start.Length).TrimEnd(';').Trim());
}
19
Source : Parser.cs
with MIT License
from adamant
with MIT License
from adamant
private static IEnumerable<GrammarRule> GetRules(List<string> lines)
{
var ruleLines = lines.Select(l => l.Trim())
.Where(l => !l.StartsWith(Program.DirectiveMarker, StringComparison.InvariantCulture)
&& !l.StartsWith("//", StringComparison.InvariantCulture)
&& !string.IsNullOrWhiteSpace(l))
.Select(l => l.TrimEnd(';')) // TODO error if no semicolon
.ToList()!;
foreach (var ruleLine in ruleLines)
{
var equalSplit = ruleLine.Split('=');
if (equalSplit.Length > 2)
throw new FormatException($"Too many equal signs on line: '{ruleLine}'");
var declaration = equalSplit[0];
var (nonterminal, parents) = ParseDeclaration(declaration);
var definition = equalSplit.Length == 2 ? equalSplit[1].Trim() : null;
var properties = ParseDefinition(definition).ToList();
if (properties.Select(p => p.Name).Distinct().Count() != properties.Count)
throw new FormatException($"Rule for {nonterminal} contains duplicate property definitions");
yield return new GrammarRule(nonterminal, parents, properties);
}
}
19
Source : ProcessNuPropsTask.cs
with MIT License
from adamecr
with MIT License
from adamecr
public override bool Execute()
{
if (DebugTasks)
{
//Wait for debugger
Log.LogMessage(
MessageImportance.High,
$"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");
while (!System.Diagnostics.Debugger.IsAttached)
{
Thread.Sleep(1000);
}
}
if (SourceFiles == null)
{
Log.LogMessage("No source code available");
return true; //nothing to process
}
//process the source files
var anyPackageAvailable = false;
foreach (var sourceFile in SourceFiles)
{
var fileNameFull = sourceFile.GetMetadata("FullPath");
var fileName = new FileInfo(fileNameFull).Name;
//Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
var sourceContent = File.ReadAllText(fileNameFull);
var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
//Extract all comments
var stringBuilder = new StringBuilder();
foreach (var contentLine in sourceLines)
{
var sourceLine = contentLine.Trim();
if (sourceLine.StartsWith("///"))
{
stringBuilder.AppendLine(sourceLine.Substring(3));
}
}
//Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
//Get NuProp comments
var nuPropElements = xDoreplacedent.Descendants()
.Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();
if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file
//Has some NuProp -> process
//<NuProp.Id></NuProp.Id> - package ID (mandatory)
//<NuProp.Version></NuProp.Version> - package version base (major.minor.patch) - optional
//<NuProp.Description></NuProp.Description> - package description (optional)
//<NuProp.Tags></NuProp.Tags> - package tags (optional)
//<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
//<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!
var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();
var nuPropsIncludes = IncludesEnum.None;
var nuPropIncludesStr = nuPropElements
.FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
.Attribute("type")?.Value;
// ReSharper disable once SwitchStatementMissingSomeCases
switch (nuPropIncludesStr)
{
case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
}
var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();
if (string.IsNullOrEmpty(nuPropId))
{
Log.LogWarning($"NuProp.Id not found for {fileName}");
continue;
}
//Build the partial NuSpec file
anyPackageAvailable = true;
var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
var outFile = fileNameFull + ".partnuspec";
var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
var outXDocStrOriginal = outXDoc.ToString();
var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);
SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set
GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
.Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
new XAttribute("include", "cs/**/*.*"),
new XAttribute("buildAction", "Compile")));
//Dependencies
var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
if (nuPropUsings.Count > 0)
{
//have some dependencies
foreach (var nuPropUsing in nuPropUsings)
{
// ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
var depId = nuPropUsing.Attribute("id").Value;
var depVersion = nuPropUsing.Attribute("version")?.Value;
var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
dependencyXElement.Add(new XAttribute("version", depVersion));
dependenciesXElement.Add(dependencyXElement);
}
}
else
{
//Clean dependencies
dependenciesXElement.Remove();
}
//<files>
// < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
// < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
//</ files >
var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
files.Add(
new XElement(ns + "file", new XAttribute("src", fileName),
new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
new XElement(ns + "file", new XAttribute("src", fileName),
new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));
if (nuPropsIncludes != IncludesEnum.None)
{
var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
Log.LogMessage($"MainItemDir:{mainItemDir}");
IEnumerable<ITaskItem> itemsToAdd;
switch (nuPropsIncludes)
{
case IncludesEnum.Folder:
itemsToAdd = SourceFiles.Where(itm =>
itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
itm.GetMetadata("FullPath") != fileNameFull);
break;
case IncludesEnum.FolderRecursive:
itemsToAdd = SourceFiles.Where(itm =>
(itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
itm.GetMetadata("FullPath") != fileNameFull);
break;
default:
throw new ArgumentOutOfRangeException();
}
foreach (var item in itemsToAdd)
{
var itemFileFull = item.GetMetadata("FullPath");
Log.LogMessage($"itemFileFull:{itemFileFull}");
var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
files.Add(
new XElement(ns + "file", new XAttribute("src", itemFileRel),
new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
new XElement(ns + "file", new XAttribute("src", itemFileRel),
new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
}
}
var outXDocStrNew = outXDoc.ToString();
if (outXDocStrNew == outXDocStrOriginal) continue;
//change - > save
File.WriteAllText(outFile, outXDocStrNew);
Log.LogMessage($"Generated/updated {outFile}");
}
if (!anyPackageAvailable)
{
Log.LogMessage("No source-only packages found");
}
return true;
}
19
Source : DmnDecisionTable.cs
with MIT License
from adamecr
with MIT License
from adamecr
private int GetIndexOfOutputValue(IList<string> allowedValues, object value, string correlationId)
{
//null value at the end
if (value == null) return int.MaxValue;
var strVal = value.ToString().Trim();
var idx = allowedValues.IndexOf(strVal);
//not found - exception, but should not happen
if (idx == -1) throw Logger.FatalCorr<DmnExecutorException>(
correlationId,
$"GetIndexOfOutputValue: Output value '{value}' is not in allowed values list ({string.Join(",", allowedValues)})");
return idx;
}
19
Source : DmnDefinitionFactory.cs
with MIT License
from adamecr
with MIT License
from adamecr
protected static string NormalizeVariableName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw Logger.Fatal<ArgumentException>($"{nameof(name)} is null or empty");
var retVal = name.Trim().Replace(' ', '_');
return retVal;
}
19
Source : InformationRequirement.cs
with MIT License
from adamecr
with MIT License
from adamecr
private static string ParseRef(string reference)
{
reference = reference?.Trim();
if (string.IsNullOrWhiteSpace(reference))
throw new DmnParserException("Can't parse InformationRequirement - reference is null or empty");
if (!reference.StartsWith("#"))
throw new DmnParserException("Can't parse InformationRequirement - reference doesn't start with #");
if (reference.Length < 2)
throw new DmnParserException("Can't parse InformationRequirement - reference too short/missing");
return reference.Substring(1);
}
19
Source : DmnParser.cs
with MIT License
from adamecr
with MIT License
from adamecr
public static DmnModel ParseString(string dmnDefinition, DmnVersionEnum dmnVersion = DmnVersionEnum.V1_1)
{
dmnDefinition = dmnDefinition?.Trim();
if (string.IsNullOrWhiteSpace(dmnDefinition)) throw Logger.Fatal<DmnParserException>("Missing DMN Model definition");
DmnModel def;
// ReSharper disable once replacedignNullToNotNullAttribute
using (var rdr = new StringReader(dmnDefinition))
{
try
{
Logger.Info($"Parsing DMN definition from given string...");
if (Logger.IsTraceEnabled)
Logger.Trace(dmnDefinition);
switch (dmnVersion)
{
case DmnVersionEnum.V1_1:
def = (DmnModel)DmnDefinitionsSerializer.Deserialize(rdr);
break;
case DmnVersionEnum.V1_3:
def = (DmnModel)DmnDefinitionsSerializer13.Deserialize(rdr);
break;
default:
throw new ArgumentOutOfRangeException(nameof(dmnVersion), dmnVersion, null);
}
Logger.Info($"Parsed DMN definition from given string");
}
catch (Exception ex)
{
throw Logger.Fatal<DmnParserException>($"Can't parse definition from given string: {ex.Message}", ex);
}
}
return def;
}
19
Source : SfeelParser.cs
with MIT License
from adamecr
with MIT License
from adamecr
public static string ParseInput(string expr, string leftSide)
{
if (string.IsNullOrWhiteSpace(expr)) throw Logger.Error<DmnParserException>($"Missing expression");
if (string.IsNullOrWhiteSpace(leftSide)) throw Logger.Error<DmnParserException>($"Missing left side of expression");
if (Logger.IsTraceEnabled)
Logger.Trace($"Parsing input expression {expr} for left side {leftSide}...");
expr = expr.Trim();
//custom functions translations
foreach (var translation in CustomFunctionTranslations)
{
expr = expr.Replace(translation.Key, translation.Value);
}
//check not(expr)
var isNegated = false;
if (expr.StartsWith("not(") && expr.EndsWith(")"))
{
expr = expr.Substring(4, expr.Length - 5);
isNegated = true;
}
//split to parts
var exprParts = Regex.Split(expr, @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");
var conditionParts = new List<string>();
foreach (var exprPart in exprParts)
{
var part = exprPart.Trim();
//<,<=,>=,>
if (part.StartsWith("<") || part.StartsWith(">"))
{
conditionParts.Add($"{leftSide}{part}");
continue;
}
//[xx..yy] (] )[
if ((part.StartsWith("[") || part.StartsWith("]") || part.StartsWith("(")) &&
(part.EndsWith("]") || part.EndsWith("[") || part.EndsWith(")")))
{
var partInner = part.Substring(1, part.Length - 2);
var partInnerSplit = partInner.Split(new[] { ".." }, StringSplitOptions.None);
// ReSharper disable once InvertIf
if (partInnerSplit.Length == 2)
{
var compLeft = part.StartsWith("[") ? ">=" : ">";
var compRight = part.EndsWith("]") ? "<=" : "<";
conditionParts.Add($"({leftSide}{compLeft}{partInnerSplit[0].Trim()} && {leftSide}{compRight}{partInnerSplit[1].Trim()})");
continue;
}
throw Logger.Error<DmnParserException>($"Wrong S-FEEL range {part}");
}
// string in "" "", number,variable name, .. - compare for eq
conditionParts.Add($"{leftSide}=={part}");
}
var condition = string.Join(" || ", conditionParts);
if (isNegated) condition = $"!({condition})";
if (Logger.IsTraceEnabled)
Logger.Trace($"Parsed input expression {expr} for variable {leftSide} - {condition}");
return condition;
}
19
Source : POComment.cs
with MIT License
from adams85
with MIT License
from adams85
public static POFlagsComment Parse(string value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var flags = value
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim())
.ToHashSet();
return new POFlagsComment { Flags = flags };
}
19
Source : POComment.cs
with MIT License
from adams85
with MIT License
from adams85
internal static bool TryParse(string value, string keyStringNewLine, out POPreviousValueComment result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
string idKindToken = null;
value = value.Trim();
var index = value.FindIndex(char.IsWhiteSpace);
if (index >= 0)
{
idKindToken = value.Remove(index);
value = value.Substring(index + 1).TrimStart();
}
int length;
POIdKind idKind;
StringBuilder sb;
if (index < 0 ||
(length = value.Length) < 2 || value[0] != '"' || value[length - 1] != '"' ||
(idKind = POKey.GetIdKind(idKindToken)) == POIdKind.Unknown ||
POString.Decode(sb = new StringBuilder(), value, 1, length - 2, keyStringNewLine) >= 0)
{
result = null;
return false;
}
result = new POPreviousValueComment { IdKind = idKind, Value = sb.ToString() };
return true;
}
19
Source : BigDecimal.cs
with MIT License
from AdamWhiteHat
with MIT License
from AdamWhiteHat
public static BigDecimal Parse(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return new BigInteger(0);
}
int exponent = 0;
int decimalPlace = 0;
bool isNegative = false;
string localInput = new string(input.Trim().Where(c => NumericCharacters.Contains(c)).ToArray());
if (localInput.StartsWith(BigDecimalNumberFormatInfo.NegativeSign))
{
isNegative = true;
localInput = localInput.Replace(BigDecimalNumberFormatInfo.NegativeSign, string.Empty);
}
if (localInput.Contains(BigDecimalNumberFormatInfo.NumberDecimalSeparator))
{
decimalPlace = localInput.IndexOf(BigDecimalNumberFormatInfo.NumberDecimalSeparator);
exponent = ((decimalPlace + 1) - (localInput.Length));
localInput = localInput.Replace(BigDecimalNumberFormatInfo.NumberDecimalSeparator, string.Empty);
}
BigInteger mantessa = BigInteger.Parse(localInput);
if (isNegative)
{
mantessa = BigInteger.Negate(mantessa);
}
return new BigDecimal(mantessa, exponent);
}
19
Source : BigDecimal.cs
with MIT License
from AdamWhiteHat
with MIT License
from AdamWhiteHat
private static int GetSignifigantDigits(BigInteger value)
{
if (value.IsZero)
{
return 0;
}
string valueString = value.ToString();
if (string.IsNullOrWhiteSpace(valueString))
{
return 0;
}
valueString = new string(valueString.Trim().Where(c => NumericCharacters.Contains(c)).ToArray());
valueString = valueString.Replace(BigDecimalNumberFormatInfo.NegativeSign, string.Empty);
valueString = valueString.Replace(BigDecimalNumberFormatInfo.PositiveSign, string.Empty);
valueString = valueString.TrimEnd(new char[] { '0' });
valueString = valueString.Replace(BigDecimalNumberFormatInfo.NumberDecimalSeparator, string.Empty);
return valueString.Length;
}
See More Examples