Skip to content

Instantly share code, notes, and snippets.

@chaojian-zhang
Last active November 5, 2022 18:58
Show Gist options
  • Save chaojian-zhang/88201881dcda7da4458e50b4a8445aee to your computer and use it in GitHub Desktop.
Save chaojian-zhang/88201881dcda7da4458e50b4a8445aee to your computer and use it in GitHub Desktop.
Useful stuff borrowed from [The Matrix](https://github.com/Charles-Zhang-Project-Nine/TheMatrix) project. #C#, #CSharp, #Utility
/*Dependency: Csv by Steven Hansen*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Utility
{
public static class StringHelper
{
public static string VariableNameToReadableString(this string name)
{
var words = Regex.Matches(name, @"([A-Z]+[a-z]+)")
.Cast<Match>()
.Select(m => m.Value);
var withSpaces = string.Join(" ", words);
return withSpaces;
}
public static void ParseCommandLineArguments(string commandLine, out string command, out string[] parameters, bool toLower = true)
{
string[] arguments = Csv.CsvReader.ReadFromText(commandLine, new Csv.CsvOptions()
{
HeaderMode = Csv.HeaderMode.HeaderAbsent,
Separator = ' '
}).First().Values;
command = toLower ? arguments.First().ToLower() : arguments.First();
parameters = arguments.Skip(1).ToArray();
}
public static Dictionary<string, string> ParseCommandArgumentsDictionary(string[] args, bool toLower = true)
{
if (args.Length % 2 != 0)
throw new ArgumentException("Wrong number of arguments - must be an even number and as key:value pairs.");
Dictionary<string, string> results = new Dictionary<string, string>();
for (int i = 0; i < args.Length; i+=2)
{
string key = args[i];
string value = args[i + 1];
if (toLower)
key = key.ToLower();
if (results.ContainsKey(key))
throw new ArgumentException($"Key `{key}` is already defined.");
if (!key.StartsWith('-'))
throw new ArgumentException($"Key `{key}` must starts with '-'");
results.Add(key, value);
}
return results;
}
}
}
public static class ObjectInspector
{
/// <summary>
/// Require properties instead of fields.
/// </summary>
public static ConsoleTable PrintObjectAsTable(this object value)
{
ConsoleTable table = new ConsoleTable("Property", "Value");
foreach (PropertyInfo property in value.GetType().GetProperties())
table.AddRow(property.Name, property.GetValue(value).ToString());
return table;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment