├── icon64.png ├── icon512.png ├── .editorconfig ├── SimpleCore ├── Pack, Push.bat ├── Utilities │ ├── Configuration │ │ ├── IConfig.cs │ │ ├── ConfigFieldAttribute.cs │ │ └── ConfigHandler.cs │ ├── Atomic.cs │ ├── Streams.cs │ ├── Enums.cs │ ├── StringConstants.cs │ ├── Tasks.cs │ ├── ColorHelper.cs │ ├── Collections.cs │ ├── Pastel.cs │ └── Strings.cs ├── Model │ ├── IViewable.cs │ ├── ExtendedStringBuilder.cs │ ├── ReadOnlyVirtualCollection.cs │ ├── Enumeration.cs │ ├── QString.cs │ └── ConsoleTable.cs ├── Diagnostics │ ├── LogCategories.cs │ ├── Log.cs │ └── Guard.cs ├── Internal │ └── Common.cs ├── SimpleCore - Backup.csproj ├── SimpleCore.csproj └── Numeric │ ├── MathHelper.cs │ └── Fraction.cs ├── TestBenchmark ├── Program.cs ├── Benchmarks1.cs ├── Benchmarks2.cs ├── Benchmarks3.cs └── TestBenchmark.csproj ├── README.md ├── SimpleCore.Selenium ├── Utilities │ ├── Highlights.cs │ ├── Selectors.cs │ ├── Scrolling.cs │ ├── Elements.cs │ ├── Waiting.cs │ └── Tabs.cs ├── SimpleCore.Selenium.csproj ├── ChromeDriverFactory.cs └── Highlight.cs ├── UnitTest ├── UnitTest.csproj └── UnitTest1.cs ├── SimpleCore.Net ├── Serializing.cs ├── GraphQLClient.cs ├── SimpleCore.Net.csproj ├── WebUtilities.cs ├── MediaTypes.cs └── Network.cs ├── SimpleCore.Cli ├── SimpleCore.Cli.csproj ├── NConsoleDialog.cs ├── NConsoleOption.cs ├── NConsoleProgress.cs └── NConsole.cs ├── Test ├── Test.csproj └── Program.cs ├── SimpleCore.sln └── .gitignore /icon64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Decimation/SimpleCore/HEAD/icon64.png -------------------------------------------------------------------------------- /icon512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Decimation/SimpleCore/HEAD/icon512.png -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | 3 | # RS1001: Missing diagnostic analyzer attribute. 4 | dotnet_diagnostic.RS1001.severity = none 5 | -------------------------------------------------------------------------------- /SimpleCore/Pack, Push.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | del *.nupkg 4 | 5 | dotnet pack -c Release -o %cd% 6 | 7 | 8 | dotnet nuget push "*.nupkg" 9 | 10 | pause -------------------------------------------------------------------------------- /SimpleCore/Utilities/Configuration/IConfig.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleCore.Utilities.Configuration 2 | { 3 | public interface IConfig 4 | { 5 | public string ConfigFile { get; } 6 | } 7 | } -------------------------------------------------------------------------------- /SimpleCore/Model/IViewable.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | // ReSharper disable UnusedMember.Global 3 | 4 | namespace SimpleCore.Model 5 | { 6 | public interface IViewable 7 | { 8 | public Dictionary View { get; } 9 | } 10 | } -------------------------------------------------------------------------------- /TestBenchmark/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using BenchmarkDotNet.Running; 3 | 4 | namespace TestBenchmark 5 | { 6 | public static class Program 7 | { 8 | private static void Main(string[] args) 9 | { 10 | //dotnet build -c Release & dotnet run -c Release 11 | BenchmarkRunner.Run(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /SimpleCore/Diagnostics/LogCategories.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable UnusedMember.Global 2 | 3 | namespace SimpleCore.Diagnostics 4 | { 5 | public static class LogCategories 6 | { 7 | public const string C_DEBUG = "[debug]"; 8 | 9 | public const string C_INFO = "[info]"; 10 | 11 | public const string C_SUCCESS = "[success]"; 12 | 13 | public const string C_WARN = "[warning]"; 14 | 15 | public const string C_ERROR = "[error]"; 16 | } 17 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Atomic.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Threading; 3 | 4 | namespace SimpleCore.Utilities 5 | { 6 | public static class Atomic 7 | { 8 | public static unsafe T Exchange(ref T location1, T location2) where T : unmanaged 9 | { 10 | fixed (T* p = &location1) { 11 | var value = Interlocked.Exchange(ref *(int*) p, Unsafe.Read(&location2)); 12 | 13 | return Unsafe.Read(&value); 14 | } 15 | 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SimpleCore 2 | [![nuget](https://img.shields.io/nuget/v/SimpleCore.svg?logo=NuGet)](https://www.nuget.org/packages/SimpleCore/) 3 | [![nuget dl](https://img.shields.io/nuget/dt/SimpleCore.svg?logo=NuGet)](https://www.nuget.org/packages/SimpleCore/) 4 | 5 | ![Icon](https://github.com/Decimation/SimpleCore/raw/master/icon64.png) 6 | 7 | .NET Core C# common library. This supersedes `SimpleSharp`. 8 | 9 | # License 10 | 11 | Icons made by Freepik 12 | -------------------------------------------------------------------------------- /TestBenchmark/Benchmarks1.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using SimpleCore.Numeric; 3 | 4 | namespace TestBenchmark 5 | { 6 | public class Benchmarks1 7 | { 8 | [Benchmark] 9 | public int Mul() 10 | { 11 | return MathHelper.Multiply(2, 2); 12 | } 13 | 14 | [Benchmark] 15 | public int Div() 16 | { 17 | return MathHelper.Divide(10, 5); 18 | } 19 | 20 | [Benchmark] 21 | public int Add() 22 | { 23 | return MathHelper.Add(1, 1); 24 | } 25 | 26 | [Benchmark] 27 | public int Sub() 28 | { 29 | return MathHelper.Subtract(1, 1); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /TestBenchmark/Benchmarks2.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace TestBenchmark 4 | { 5 | public class Benchmarks2 6 | { 7 | 8 | /* 9 | * | Method | Mean | Error | StdDev | Median | 10 | * |------- |----------:|----------:|----------:|-------:| 11 | * | a | 0.0002 ns | 0.0007 ns | 0.0006 ns | 0.0 ns | 12 | * | b | 0.0158 ns | 0.0226 ns | 0.0242 ns | 0.0 ns | 13 | */ 14 | 15 | 16 | public const int i = 3; 17 | 18 | [Benchmark] 19 | public bool a() 20 | { 21 | return (i & 1) ==1; 22 | } 23 | 24 | [Benchmark] 25 | public bool b() 26 | { 27 | return i % 2 == 1; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /TestBenchmark/Benchmarks3.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | using BenchmarkDotNet.Attributes; 3 | 4 | namespace TestBenchmark 5 | { 6 | public unsafe class Benchmarks3 7 | { 8 | [Benchmark] 9 | public int a() 10 | { 11 | return rg[1]; 12 | } 13 | 14 | //[Benchmark] 15 | //public int b() 16 | //{ 17 | // return p[1]; 18 | //} 19 | 20 | [Benchmark] 21 | public int b() 22 | { 23 | fixed (int* x = rg) { 24 | return x[1]; 25 | } 26 | } 27 | 28 | [Benchmark] 29 | public int c() 30 | { 31 | return *(int*) Marshal.UnsafeAddrOfPinnedArrayElement(rg, 1); 32 | } 33 | 34 | public int[] rg = new[] {1, 2, 3}; 35 | } 36 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Highlights.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | // ReSharper disable UnusedMember.Global 3 | namespace SimpleCore.Selenium.Utilities 4 | { 5 | public static class Highlights 6 | { 7 | public static void QHighlightClick(this IWebDriver driver, IWebElement element) 8 | { 9 | driver.QHighlightSelect(element); 10 | element.Click(); 11 | } 12 | 13 | public static void QHighlightSelect(this IWebDriver driver, IWebElement element) 14 | { 15 | var jsDriver = (IJavaScriptExecutor) driver; 16 | 17 | const string HIGHLIGHT_JS = 18 | @"$(arguments[0]).css({ ""border-width"" : ""2px"", ""border-style"" : ""solid"", ""border-color"" : ""red"" });"; 19 | jsDriver.ExecuteScript(HIGHLIGHT_JS, element); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /UnitTest/UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | JETBRAINS_ANNOTATIONS;TRACE 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /SimpleCore/Diagnostics/Log.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Runtime.CompilerServices; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using JetBrains.Annotations; 9 | using static SimpleCore.Internal.Common; 10 | // ReSharper disable UnusedMember.Global 11 | 12 | #nullable enable 13 | namespace SimpleCore.Diagnostics 14 | { 15 | public static class Log 16 | { 17 | [Conditional(TRACE_COND)] 18 | public static void WriteLine(string msg, string category, [CallerMemberName] string? caller = null) 19 | { 20 | Trace.WriteLine($"({caller}): {msg}", category); 21 | } 22 | 23 | 24 | [Conditional(TRACE_COND)] 25 | [StringFormatMethod(STRING_FORMAT_ARG)] 26 | public static void WriteLine(string msg, params object[] args) 27 | { 28 | Trace.WriteLine(String.Format(msg, args)); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /SimpleCore/Internal/Common.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime.CompilerServices; 4 | 5 | // ReSharper disable UnusedMember.Global 6 | 7 | [assembly: InternalsVisibleTo("Novus")] 8 | [assembly: InternalsVisibleTo("SimpleCore.Net")] 9 | [assembly: InternalsVisibleTo("SimpleCore.Cli")] 10 | 11 | namespace SimpleCore.Internal 12 | { 13 | /// 14 | /// Internal library common utilities, values, etc. 15 | /// 16 | internal static class Common 17 | { 18 | internal static readonly Random RandomInstance = new(); 19 | 20 | internal const string DEBUG_COND = "DEBUG"; 21 | 22 | internal const string TRACE_COND = "TRACE"; 23 | 24 | internal const string STRING_FORMAT_ARG = "msg"; 25 | 26 | /// 27 | /// Common integer value representing an invalid value, error, etc. 28 | /// 29 | internal const int INVALID = -1; 30 | } 31 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Streams.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | // ReSharper disable UnusedMember.Global 8 | 9 | namespace SimpleCore.Utilities 10 | { 11 | public static class Streams 12 | { 13 | public static string[] ReadAllLines(this StreamReader stream) 14 | { 15 | var list = new List(); 16 | 17 | while (!stream.EndOfStream) 18 | { 19 | string line = stream.ReadLine(); 20 | 21 | if (line != null) 22 | { 23 | list.Add(line); 24 | } 25 | } 26 | 27 | return list.ToArray(); 28 | } 29 | 30 | 31 | public static byte[] ToByteArray(this Stream stream) 32 | { 33 | stream.Position = 0; 34 | using var ms = new MemoryStream(); 35 | stream.CopyTo(ms); 36 | var rg = ms.ToArray(); 37 | 38 | return rg; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /TestBenchmark/TestBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | true 10 | 11 | 12 | 13 | true 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Selectors.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OpenQA.Selenium; 3 | // ReSharper disable UnusedMember.Global 4 | namespace SimpleCore.Selenium.Utilities 5 | { 6 | public static class Selectors 7 | { 8 | public static By ClassNameContains(string s) 9 | { 10 | return By.XPath(String.Format("//*[contains(@class, \"{0}\")]", s)); 11 | } 12 | 13 | // todo 14 | 15 | public static By ClassNameContainsCurrent(string s) 16 | { 17 | return By.XPath(String.Format(".//*[contains(@class, \"{0}\")]", s)); 18 | } 19 | 20 | /// 21 | /// Creates an XPath selector which selects anything whose text contains . 22 | /// 23 | public static By TextContains(string txt) 24 | { 25 | // //*[text()[contains(.,'ABC')]] 26 | return By.XPath(String.Format("//*[text()[contains(.,'{0}')]]", txt)); 27 | } 28 | 29 | public static By Parent() 30 | { 31 | return By.XPath("./.."); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /SimpleCore.Net/Serializing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Json; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using AngleSharp.Dom; 8 | using AngleSharp.Html.Dom; 9 | 10 | // ReSharper disable UnusedMember.Global 11 | 12 | namespace SimpleCore.Net 13 | { 14 | public static class Serializing 15 | { 16 | public static JsonValue TryGetKeyValue(this JsonValue value, string k) 17 | { 18 | return value.ContainsKey(k) ? value[k] : null; 19 | } 20 | 21 | public static string GetExclusiveText(this INode node) 22 | { 23 | return node.ChildNodes.OfType().Select(m => m.Text).FirstOrDefault(); 24 | } 25 | 26 | public static IEnumerable QuerySelectorAttributes(this IHtmlDocument document, string s, string a) 27 | { 28 | return document.QuerySelectorAll(s).Select(s => s.GetAttribute(a)); 29 | 30 | } 31 | 32 | public static string TryGetAttribute(this INode n, string s) 33 | { 34 | return ((IHtmlElement) n).GetAttribute(s); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/SimpleCore.Selenium.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | latest 6 | true 7 | JETBRAINS_ANNOTATIONS;TRACE 8 | latest 9 | Read Stanton (Decimation) 10 | Read Stanton (Decimation) 11 | 12 | HAA0601 13 | HAA0601, 14 | HAA0602, 15 | HAA0603, 16 | HAA0604, 17 | HAA0501, 18 | HAA0502, 19 | HAA0503, 20 | HAA0504, 21 | HAA0505, 22 | HAA0506, 23 | HAA0301, 24 | HAA0302, 25 | HAA0303, 26 | HAA0101, 27 | CS1591, 28 | 29 | true 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /SimpleCore/Utilities/Configuration/ConfigFieldAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using JetBrains.Annotations; 3 | 4 | namespace SimpleCore.Utilities.Configuration 5 | { 6 | [AttributeUsage(AttributeTargets.Field)] 7 | [MeansImplicitUse(ImplicitUseTargetFlags.Default)] 8 | public sealed class ConfigFieldAttribute : Attribute 9 | { 10 | public object DefaultValue { get; set; } 11 | 12 | /// 13 | /// Component name 14 | /// 15 | public string Id { get; set; } 16 | 17 | 18 | public bool SetDefaultIfNull { get; set; } 19 | 20 | 21 | /// 22 | /// Parameter name 23 | /// 24 | [CanBeNull] 25 | public string ParameterName { get; set; } 26 | 27 | 28 | public ConfigFieldAttribute(string id, string parameterName, object defaultValue, 29 | bool setDefaultIfNull) 30 | { 31 | Id = id; 32 | DefaultValue = defaultValue; 33 | SetDefaultIfNull = setDefaultIfNull; 34 | ParameterName = parameterName; 35 | } 36 | 37 | public ConfigFieldAttribute(string id, [CanBeNull] string parameterName, object defaultValue) : this( 38 | id, 39 | parameterName, defaultValue, false) { } 40 | 41 | 42 | public ConfigFieldAttribute(string id, object defaultValue) : this(id, null, defaultValue) { } 43 | } 44 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/ChromeDriverFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using OpenQA.Selenium.Chrome; 3 | // ReSharper disable UnusedMember.Global 4 | 5 | //https://github.com/Decimation/Bromine 6 | //C:\Users\Deci\RiderProjects\Bromine 7 | 8 | 9 | namespace SimpleCore.Selenium 10 | { 11 | /// 12 | /// Provides utilities for 13 | /// 14 | public static class ChromeDriverFactory 15 | { 16 | /// 17 | /// 18 | /// 19 | public const string NAME = "chromedriver"; 20 | 21 | public static ChromeDriver CreateQuietHeadless(params string[] extraArgs) 22 | { 23 | var list = extraArgs.ToList(); 24 | list.Add("--headless"); 25 | 26 | return CreateQuiet(list.ToArray()); 27 | } 28 | 29 | public static ChromeDriver CreateQuiet(params string[] extraArgs) 30 | { 31 | var co = new ChromeOptions(); 32 | 33 | co.AddArguments("--silent", "--log-level=3", "--disable-infobars"); 34 | co.AddArguments("--mute-audio", "--disable-gpu"); 35 | // co.AddArguments("--disable-extensions","start-maximized"); 36 | 37 | if (extraArgs?.Length > 0) 38 | co.AddArguments(extraArgs); 39 | 40 | // hide logs 41 | var service = ChromeDriverService.CreateDefaultService(); 42 | service.HideCommandPromptWindow = true; 43 | 44 | return new ChromeDriver(service, co); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Scrolling.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OpenQA.Selenium; 3 | using OpenQA.Selenium.Interactions; 4 | // ReSharper disable UnusedMember.Global 5 | namespace SimpleCore.Selenium.Utilities 6 | { 7 | public static class Scrolling 8 | { 9 | public static void ScrollToBottom(this IWebDriver driver) 10 | { 11 | ((IJavaScriptExecutor) driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight)"); 12 | } 13 | 14 | public static void ScrollToTop(this IWebDriver driver) 15 | { 16 | ((IJavaScriptExecutor) driver).ExecuteScript("window.scrollTo(document.body.scrollHeight, 0)"); 17 | } 18 | 19 | public static void ScrollBy(this IWebDriver driver, int x, int y) 20 | { 21 | ((IJavaScriptExecutor) driver).ExecuteScript(String.Format("scrollBy({0},{1})", x, y)); 22 | } 23 | 24 | public static void ScrollIntoView(this IWebDriver driver, IWebElement element) 25 | { 26 | // document.getElementById('Chk_3_4000001871527773').scrollIntoView() 27 | // .scrollIntoView() 28 | 29 | var js = (IJavaScriptExecutor) driver; 30 | js.ExecuteScript("arguments[0].scrollIntoView();", element); 31 | } 32 | 33 | public static void ScrollToElement(this IWebDriver driver, IWebElement element) 34 | { 35 | var actions = new Actions(driver); 36 | actions.MoveToElement(element); 37 | 38 | actions.Perform(); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /SimpleCore.Cli/SimpleCore.Cli.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Read Stanton (Decimation) 5 | JETBRAINS_ANNOTATIONS;TRACE 6 | 7 | net5.0 8 | latest 9 | 10 | HAA0601 11 | HAA0601, 12 | HAA0602, 13 | HAA0603, 14 | HAA0604, 15 | HAA0501, 16 | HAA0502, 17 | HAA0503, 18 | HAA0504, 19 | HAA0505, 20 | HAA0506, 21 | HAA0301, 22 | HAA0302, 23 | HAA0303, 24 | HAA0101, 25 | CS1591, 26 | 27 | true 28 | 29 | 30 | 31 | DEBUG;TRACE 32 | true 33 | 34 | 35 | 36 | true 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /SimpleCore/SimpleCore - Backup.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | true 6 | JETBRAINS_ANNOTATIONS;TRACE 7 | net5.0 8 | latest 9 | 10 | 11 | 12 | 13 | 14 | DEBUG;TRACE 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | SimpleCore 23 | 1.1.9 24 | Read Stanton (Decimation) 25 | Utilities common 26 | https://github.com/Decimation/SimpleCore 27 | icon64.png 28 | .NET Core C# common library 29 | 30 | 31 | 32 | 37 | 38 | -------------------------------------------------------------------------------- /SimpleCore.Cli/NConsoleDialog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using JetBrains.Annotations; 5 | 6 | namespace SimpleCore.Cli 7 | { 8 | public class NConsoleDialog 9 | { 10 | public IList Options { get; init; } 11 | 12 | public bool SelectMultiple { get; init; } 13 | 14 | public string Header { get; set; } 15 | 16 | [CanBeNull] 17 | public string Status { get; set; } 18 | 19 | [CanBeNull] 20 | public string Description { get; set; } 21 | 22 | 23 | protected bool Equals(NConsoleDialog other) 24 | { 25 | return Equals(Options, other.Options) 26 | && SelectMultiple == other.SelectMultiple 27 | && Header == other.Header 28 | && Status == other.Status 29 | && Description == other.Description; 30 | } 31 | 32 | public override bool Equals(object obj) 33 | { 34 | if (ReferenceEquals(null, obj)) return false; 35 | if (ReferenceEquals(this, obj)) return true; 36 | if (obj.GetType() != this.GetType()) return false; 37 | return Equals((NConsoleDialog) obj); 38 | } 39 | 40 | public override int GetHashCode() 41 | { 42 | var h=new HashCode(); 43 | 44 | var hx=Options.Select(o => (o.GetHashCode())); 45 | 46 | foreach (int i in hx) { 47 | h.Add(i); 48 | } 49 | h.Add(Status?.GetHashCode()); 50 | h.Add(Description?.GetHashCode()); 51 | h.Add(Header?.GetHashCode()); 52 | return h.ToHashCode(); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Enums.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | // ReSharper disable UnusedMember.Global 7 | 8 | namespace SimpleCore.Utilities 9 | { 10 | 11 | 12 | /// 13 | /// Utilities for enums (). 14 | /// 15 | public static class Enums 16 | { 17 | public static List GetSetFlags(TEnum value, bool excludeZero = true) where TEnum : Enum 18 | { 19 | var flags = Enum.GetValues(typeof(TEnum)) 20 | .Cast() 21 | .Where(f => value.HasFlag(f)) 22 | .ToList(); 23 | 24 | 25 | if (excludeZero) { 26 | flags.RemoveAll(e => Convert.ToInt32(e) == 0); 27 | 28 | } 29 | 30 | //flags.RemoveAll(e => e.Equals(value)); 31 | 32 | return flags; 33 | } 34 | 35 | 36 | public static TEnum SafeParse(string s) where TEnum : Enum 37 | { 38 | if (String.IsNullOrWhiteSpace(s)) { 39 | return default; 40 | } 41 | 42 | Enum.TryParse(typeof(TEnum), s, out object e); 43 | return (TEnum) e; 44 | } 45 | 46 | public static TEnum ReadFromSet(ISet set) where TEnum : Enum 47 | { 48 | var t = typeof(TEnum); 49 | 50 | if (t.GetCustomAttribute() != null) { 51 | string sz = set.QuickJoin(); 52 | Enum.TryParse(typeof(TEnum), sz, out object e); 53 | 54 | if (e == null) { 55 | return default; 56 | } 57 | 58 | return (TEnum) e; 59 | } 60 | 61 | return default; 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /SimpleCore.Net/GraphQLClient.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Net; 3 | using Newtonsoft.Json.Linq; 4 | using RestSharp; 5 | 6 | // ReSharper disable InconsistentNaming 7 | // ReSharper disable UnusedMember.Global 8 | // ReSharper disable RedundantAnonymousTypePropertyName 9 | #pragma warning disable IDE0037 10 | 11 | namespace SimpleCore.Net 12 | { 13 | /// 14 | /// Simple GraphQL client 15 | /// 16 | public class GraphQLClient 17 | { 18 | /* 19 | * Adapted from https://github.com/latheesan-k/simple-graphql-client 20 | */ 21 | 22 | 23 | private readonly RestClient _client; 24 | 25 | public GraphQLClient(string apiUrl) 26 | { 27 | _client = new RestClient(apiUrl); 28 | 29 | ServicePointManager.SecurityProtocol = 30 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; 31 | } 32 | 33 | public dynamic Execute(string query, object variables = null, 34 | Dictionary additionalHeaders = null, 35 | int timeout = 0) 36 | { 37 | var request = new RestRequest("/", Method.POST) 38 | { 39 | Timeout = timeout 40 | }; 41 | 42 | if (additionalHeaders is {Count: > 0}) { 43 | foreach ((string key, string value) in additionalHeaders) { 44 | request.AddHeader(key, value); 45 | } 46 | } 47 | 48 | request.AddJsonBody(new 49 | { 50 | query = query, 51 | variables = variables 52 | }); 53 | 54 | return JObject.Parse(_client.Execute(request).Content); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /SimpleCore/Model/ExtendedStringBuilder.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections; 4 | using System.Text; 5 | using SimpleCore.Utilities; 6 | 7 | // ReSharper disable UnusedMember.Global 8 | 9 | namespace SimpleCore.Model 10 | { 11 | public class ExtendedStringBuilder 12 | { 13 | public StringBuilder Builder { get; init; } 14 | 15 | 16 | public ExtendedStringBuilder() : this(new StringBuilder()) { } 17 | 18 | public ExtendedStringBuilder(StringBuilder builder) 19 | { 20 | Builder = builder; 21 | } 22 | 23 | public static implicit operator ExtendedStringBuilder(StringBuilder sb) 24 | { 25 | return new(sb); 26 | } 27 | 28 | public ExtendedStringBuilder Append(string value) 29 | { 30 | Builder.Append(value); 31 | return this; 32 | } 33 | 34 | public ExtendedStringBuilder AppendLine(string value) 35 | { 36 | Builder.AppendLine(value); 37 | return this; 38 | } 39 | 40 | public override string ToString() => Builder.ToString(); 41 | 42 | 43 | public ExtendedStringBuilder Append(string name, object? val, string? valStr = null, bool newLine = true) 44 | { 45 | if (val != null) { 46 | 47 | // Patterns are so epic 48 | 49 | switch (val) { 50 | case IList {Count: 0}: 51 | case string s when String.IsNullOrWhiteSpace(s): 52 | return this; 53 | 54 | default: 55 | { 56 | valStr ??= val.ToString(); 57 | 58 | 59 | string fs = $"{name}: {valStr}".Truncate(); 60 | 61 | if (newLine) { 62 | fs += "\n"; 63 | } 64 | 65 | Builder.Append(fs); 66 | break; 67 | } 68 | } 69 | 70 | } 71 | 72 | return this; 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /SimpleCore.Net/SimpleCore.Net.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | latest 6 | true 7 | JETBRAINS_ANNOTATIONS;TRACE 8 | latest 9 | Read Stanton (Decimation) 10 | Read Stanton (Decimation) 11 | 12 | HAA0601 13 | HAA0601, 14 | HAA0602, 15 | HAA0603, 16 | HAA0604, 17 | HAA0501, 18 | HAA0502, 19 | HAA0503, 20 | HAA0504, 21 | HAA0505, 22 | HAA0506, 23 | HAA0301, 24 | HAA0302, 25 | HAA0303, 26 | HAA0101, 27 | CS1591, 28 | 29 | true 30 | 31 | 32 | DEBUG;TRACE 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /SimpleCore/Utilities/StringConstants.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable UnusedMember.Global 2 | namespace SimpleCore.Utilities 3 | { 4 | public static class StringConstants 5 | { 6 | public const string JOIN_COMMA = ", "; 7 | 8 | /// 9 | /// Scope resolution operator 10 | /// 11 | public const string JOIN_SCOPE = "::"; 12 | 13 | public const string JOIN_SPACE = " "; 14 | 15 | public const string ELLIPSES = "..."; 16 | 17 | 18 | public const char PERIOD = '.'; 19 | public const char ASTERISK = '*'; 20 | public const char EXCLAMATION = '!'; 21 | public const char SPACE = ' '; 22 | 23 | public const char ARROW_DOWN = '\u2193'; 24 | public const char ARROW_LEFT = '\u2190'; 25 | public const char ARROW_LEFT_RIGHT = '\u2194'; 26 | public const char ARROW_RIGHT = '\u2192'; 27 | public const char ARROW_UP = '\u2191'; 28 | public const char ARROW_UP_DOWN = '\u2195'; 29 | 30 | public const char BALLOT_X = '\u2717'; 31 | public const char HEAVY_BALLOT_X = '\u2718'; 32 | 33 | public const char CHECK_MARK = '\u2713'; 34 | public const char HEAVY_CHECK_MARK = '\u2714'; 35 | 36 | public const char LOZENGE = '\u25ca'; 37 | 38 | public const char MUL_SIGN = '\u00D7'; 39 | public const char MUL_SIGN2 = '\u2715'; 40 | 41 | public const char NULL_CHAR = '\0'; 42 | 43 | public const char RAD_SIGN = '\u221A'; 44 | 45 | public const char RELOAD = '\u21bb'; 46 | 47 | public const char SUN = '\u263c'; 48 | 49 | 50 | public static readonly string NativeNewLine = '\n'.ToString(); 51 | 52 | public const string Alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 53 | 54 | /// 55 | /// Constant 56 | /// 57 | public const string Empty = ""; 58 | } 59 | } -------------------------------------------------------------------------------- /SimpleCore/Model/ReadOnlyVirtualCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | // ReSharper disable UnusedMember.Global 8 | 9 | namespace SimpleCore.Model 10 | { 11 | /// 12 | /// 13 | /// Represents a collection implemented by delegates. 14 | /// 15 | public class ReadOnlyVirtualCollection : IReadOnlyList 16 | { 17 | /// 18 | /// Retrieves an item with the name 19 | /// 20 | public delegate T GetItem(string name); 21 | 22 | /// 23 | /// Retrieves the items as an array. 24 | /// 25 | public delegate T[] GetItems(); 26 | 27 | private readonly GetItem m_fnGetItem; 28 | 29 | private readonly GetItems m_fnGetItems; 30 | 31 | public ReadOnlyVirtualCollection(GetItem fnGetItem, GetItems fnGetItems) 32 | { 33 | m_fnGetItem = fnGetItem; 34 | m_fnGetItems = fnGetItems; 35 | } 36 | 37 | /// 38 | /// Gets an item with the name 39 | /// 40 | /// Name of the item 41 | public T this[string name] => m_fnGetItem(name); 42 | 43 | /// 44 | /// Gets an item at index 45 | /// 46 | /// Index to retrieve the item 47 | public T this[int index] => m_fnGetItems()[index]; 48 | 49 | public IEnumerator GetEnumerator() 50 | { 51 | return ((IEnumerable) ToArray()).GetEnumerator(); 52 | } 53 | 54 | IEnumerator IEnumerable.GetEnumerator() 55 | { 56 | return GetEnumerator(); 57 | } 58 | 59 | public T[] ToArray() => m_fnGetItems(); 60 | 61 | public int Count => ToArray().Length; 62 | } 63 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Tasks.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | // ReSharper disable UnusedMember.Global 10 | 11 | namespace SimpleCore.Utilities 12 | { 13 | public static class Tasks 14 | { 15 | 16 | 17 | public static Task ForEachAsync(this IEnumerable sequence, Func action) 18 | { 19 | return Task.WhenAll(sequence.Select(action)); 20 | } 21 | 22 | /* 23 | * https://stackoverflow.com/questions/35645899/awaiting-task-with-timeout 24 | * https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=net-5.0 25 | * https://devblogs.microsoft.com/pfxteam/crafting-a-task-timeoutafter-method/ 26 | * https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time 27 | * https://stackoverflow.com/questions/20638952/cancellationtoken-and-cancellationtokensource-how-to-use-it 28 | * https://stackoverflow.com/questions/22637642/using-cancellationtoken-for-timeout-in-task-run-does-not-work 29 | * https://stackoverflow.com/questions/32520612/how-to-handle-task-cancellation-in-the-tpl 30 | */ 31 | 32 | public static async Task AwaitWithTimeout(this Task task, int timeout, Action success, Action error) 33 | { 34 | if (await Task.WhenAny(task, Task.Delay(timeout)) == task) { 35 | success(); 36 | } 37 | else { 38 | error(); 39 | } 40 | } 41 | 42 | public static TimeSpan MeasureAction(Action f) 43 | { 44 | var sw = Stopwatch.StartNew(); 45 | //var x=Environment.TickCount64; 46 | 47 | f(); 48 | //var d = Environment.TickCount64 - x; 49 | sw.Stop(); 50 | return sw.Elapsed; 51 | //return TimeSpan.FromTicks(d); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Elements.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OpenQA.Selenium; 3 | using OpenQA.Selenium.Support.UI; 4 | // ReSharper disable UnusedMember.Global 5 | 6 | namespace SimpleCore.Selenium.Utilities 7 | { 8 | public static class Elements 9 | { 10 | public static bool IsClickable(this IWebDriver driver, TimeSpan timeSpan, IWebElement element) 11 | { 12 | try { 13 | var wait = new WebDriverWait(driver, timeSpan); 14 | wait.Until(ExpectedConditions.ElementToBeClickable(element)); 15 | return true; 16 | } 17 | catch (Exception) { 18 | return false; 19 | } 20 | } 21 | 22 | /// 23 | /// An expectation for checking whether an element is visible. 24 | /// 25 | /// The locator used to find the element. 26 | /// The once it is located, visible and clickable. 27 | public static Func ElementIsClickable(By locator) 28 | { 29 | return driver => 30 | { 31 | var element = driver.FindElement(locator); 32 | return (element != null && element.Displayed && element.Enabled) ? element : null; 33 | }; 34 | } 35 | 36 | public static bool ElementExists(this IWebDriver driver, By by) 37 | { 38 | return driver.ElementExists(by, out _); 39 | } 40 | 41 | public static bool ElementExists(this IWebDriver driver, By by, out IWebElement element) 42 | { 43 | var elements = driver.FindElements(by); 44 | 45 | bool exists = elements.Count > 0; 46 | element = exists ? elements[0] : null; 47 | 48 | return exists; 49 | } 50 | 51 | public static bool IsElementPresent(this IWebDriver driver, By by) 52 | { 53 | try { 54 | driver.FindElement(by); 55 | return true; 56 | } 57 | catch (NoSuchElementException) { 58 | return false; 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /SimpleCore/Model/Enumeration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | // ReSharper disable UnusedMember.Global 7 | // ReSharper disable AutoPropertyCanBeMadeGetOnly.Local 8 | 9 | 10 | namespace SimpleCore.Model 11 | { 12 | public abstract class Enumeration : IComparable 13 | { 14 | public string Name { get; private init; } 15 | 16 | public int Id { get; private init; } 17 | 18 | protected Enumeration(int id, string name) 19 | { 20 | Id = id; 21 | Name = name; 22 | } 23 | 24 | 25 | 26 | public static int GetNextId() where T : Enumeration 27 | { 28 | var t = GetAll().Last(); 29 | return t.Id + 1; 30 | } 31 | 32 | public override string ToString() => $"{Name} ({Id})"; 33 | 34 | public static IEnumerable GetAll() where T : Enumeration 35 | { 36 | var fields = typeof(T).GetFields(BindingFlags.Public | 37 | BindingFlags.Static | 38 | BindingFlags.DeclaredOnly) 39 | .Where(r => r.FieldType == typeof(T)); 40 | 41 | return fields.Select(f => f.GetValue(null)).Cast(); 42 | } 43 | 44 | public override bool Equals(object obj) 45 | { 46 | var otherValue = obj as Enumeration; 47 | 48 | if (otherValue == null) 49 | return false; 50 | 51 | var typeMatches = GetType() == obj.GetType(); 52 | var valueMatches = Id.Equals(otherValue.Id); 53 | 54 | return typeMatches && valueMatches; 55 | } 56 | 57 | protected bool Equals(Enumeration other) 58 | { 59 | return Name == other.Name && Id == other.Id; 60 | } 61 | 62 | public override int GetHashCode() 63 | { 64 | return HashCode.Combine(Name, Id); 65 | } 66 | 67 | public int CompareTo(object other) => Id.CompareTo(((Enumeration) other).Id); 68 | 69 | // Other utility methods ... 70 | } 71 | } -------------------------------------------------------------------------------- /Test/Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | latest 7 | true 8 | JETBRAINS_ANNOTATIONS;TRACE 9 | 10 | 11 | 12 | true 13 | 14 | 15 | 16 | true 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /SimpleCore/SimpleCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | true 6 | JETBRAINS_ANNOTATIONS;TRACE 7 | net5.0 8 | latest 9 | 10 | HAA0601 11 | HAA0601, 12 | HAA0602, 13 | HAA0603, 14 | HAA0604, 15 | HAA0501, 16 | HAA0502, 17 | HAA0503, 18 | HAA0504, 19 | HAA0505, 20 | HAA0506, 21 | HAA0301, 22 | HAA0302, 23 | HAA0303, 24 | HAA0101, 25 | CS1591, 26 | 27 | true 28 | 29 | 30 | 31 | 32 | DEBUG;TRACE;JETBRAINS_ANNOTATIONS 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | True 44 | 45 | 46 | 47 | 48 | SimpleCore 49 | 1.2.2 50 | Read Stanton (Decimation) 51 | Utilities common 52 | https://github.com/Decimation/SimpleCore 53 | icon64.png 54 | .NET Core C# common library 55 | 56 | 57 | 58 | 63 | 64 | -------------------------------------------------------------------------------- /SimpleCore.Net/WebUtilities.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | // ReSharper disable UnusedMember.Global 12 | 13 | namespace SimpleCore.Net 14 | { 15 | public static class WebUtilities 16 | { 17 | public static string Download(string url, string folder) 18 | { 19 | string fileName = Path.GetFileName(url); 20 | 21 | using WebClient client = new(); 22 | client.Headers.Add("User-Agent: Other"); 23 | 24 | string dir = Path.Combine(folder, fileName); 25 | 26 | client.DownloadFile(url, dir); 27 | 28 | return dir; 29 | } 30 | 31 | public static string Download(string url) => 32 | Download(url, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); 33 | 34 | public static void OpenUrl(string url) 35 | { 36 | // https://stackoverflow.com/questions/4580263/how-to-open-in-default-browser-in-c-sharp 37 | // url must start with a protocol i.e. http:// 38 | 39 | try { 40 | Process.Start(url); 41 | } 42 | catch { 43 | // hack because of this: https://github.com/dotnet/corefx/issues/10361 44 | if (OperatingSystem.IsWindows()) { 45 | url = url.Replace("&", "^&"); 46 | 47 | Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") 48 | { 49 | CreateNoWindow = true 50 | }); 51 | } 52 | else { 53 | throw; 54 | } 55 | } 56 | } 57 | 58 | public static Stream GetStream(string url) 59 | { 60 | using var wc = new WebClient(); 61 | byte[] buffer = wc.DownloadData(url); 62 | 63 | return new MemoryStream(buffer); 64 | } 65 | 66 | public static string GetString(string url) 67 | { 68 | using var wc = new WebClient(); 69 | return wc.DownloadString(url); 70 | } 71 | 72 | public static bool TryGetString(string url, out string? e) 73 | { 74 | try { 75 | e = GetString(url); 76 | return true; 77 | } 78 | catch (Exception) { 79 | e = null; 80 | return false; 81 | } 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /SimpleCore/Model/QString.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | // ReSharper disable UnusedMember.Global 7 | 8 | namespace SimpleCore.Model 9 | { 10 | /// 11 | /// Mutable extended string type. 12 | /// 13 | public class QString 14 | { 15 | private readonly StringBuilder m_value; 16 | 17 | public QString() 18 | { 19 | m_value = new StringBuilder(); 20 | } 21 | 22 | public QString(StringBuilder value) : this() 23 | { 24 | Append(value.ToString()); 25 | } 26 | 27 | public QString(string value) : this() 28 | { 29 | Append(value); 30 | } 31 | 32 | public char this[int i] 33 | { 34 | get => m_value[i]; 35 | set => m_value[i] = value; 36 | } 37 | 38 | //public QString this[int startIndex, int length] => Value.Substring(startIndex, length); 39 | 40 | public char this[Index i] 41 | { 42 | get => m_value[i]; 43 | set => m_value[i] = value; 44 | } 45 | 46 | public QString this[Range r] => Value[r]; 47 | 48 | public void Clear() => m_value.Clear(); 49 | 50 | public int Length => m_value.Length; 51 | 52 | public string Value 53 | { 54 | get => m_value.ToString(); 55 | set 56 | { 57 | Clear(); 58 | Append(value); 59 | } 60 | } 61 | 62 | public void Replace(QString oldValue, QString newValue) 63 | { 64 | m_value.Replace((string) oldValue, (string) newValue); 65 | } 66 | 67 | public void Remove(int startIndex, int length) 68 | { 69 | m_value.Remove(startIndex, length); 70 | } 71 | 72 | /*public void Remove(Range r) 73 | { 74 | Remove(r.Start.Value, (r.End.Value - r.Start.Value)); 75 | }*/ 76 | 77 | public void Append(string value) 78 | { 79 | m_value.Append(value); 80 | } 81 | 82 | public void Append(QString value) 83 | { 84 | m_value.Append(value); 85 | } 86 | 87 | public static QString operator +(QString a, QString b) 88 | { 89 | a.Append(b); 90 | return a; 91 | } 92 | 93 | public static /*implicit*/ explicit operator string(QString value) => value.Value; 94 | 95 | public static implicit operator QString(string value) => new(value); 96 | 97 | public QString Copy() => new(m_value); 98 | 99 | public override string ToString() 100 | { 101 | return Value; 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Waiting.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using OpenQA.Selenium; 5 | using OpenQA.Selenium.Support.UI; 6 | // ReSharper disable UnusedMember.Global 7 | namespace SimpleCore.Selenium.Utilities 8 | { 9 | public static class Waiting 10 | { 11 | public static void WaitForLoad(this IWebDriver driver, int timeoutSec = 15) 12 | { 13 | var js = (IJavaScriptExecutor) driver; 14 | var wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec)); 15 | wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete"); 16 | } 17 | 18 | 19 | public static void Wait(this IWebDriver driver, double delay, double interval) 20 | { 21 | // Causes the WebDriver to wait for at least a fixed delay 22 | var now = DateTime.Now; 23 | var wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(delay)) 24 | { 25 | PollingInterval = TimeSpan.FromMilliseconds(interval) 26 | }; 27 | wait.Until(wd => (DateTime.Now - now) - TimeSpan.FromMilliseconds(delay) > TimeSpan.Zero); 28 | } 29 | 30 | public static void Wait(this IWebDriver driver, Func condition, double delay) 31 | { 32 | var ignoredExceptions = new List {typeof(StaleElementReferenceException)}; 33 | var wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(delay)); 34 | wait.IgnoreExceptionTypes(ignoredExceptions.ToArray()); 35 | wait.Until(condition); 36 | } 37 | 38 | // todo: did I write this correctly? 39 | public static TResult WaitFind(this IWebDriver driver, Func fn, 40 | int timeoutInSeconds = 2) 41 | { 42 | if (timeoutInSeconds > 0) { 43 | var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); 44 | return wait.Until(fn); 45 | } 46 | 47 | return fn(driver); 48 | } 49 | 50 | // @formatter:off 51 | public static ReadOnlyCollection WaitFindElements(this IWebDriver driver, By by, int timeoutInSeconds = 2) 52 | { 53 | if (timeoutInSeconds > 0) { 54 | var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); 55 | return wait.Until(drv => drv.FindElements(by)); 56 | } 57 | 58 | return driver.FindElements(by); 59 | } 60 | // @formatter:on 61 | 62 | public static IWebElement WaitFindElement(this IWebDriver driver, By by, int timeoutInSeconds = 2) 63 | { 64 | if (timeoutInSeconds > 0) { 65 | var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); 66 | return wait.Until(drv => drv.FindElement(by)); 67 | } 68 | 69 | return driver.FindElement(by); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Utilities/Tabs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using OpenQA.Selenium; 4 | using OpenQA.Selenium.Chrome; 5 | using OpenQA.Selenium.Interactions; 6 | // ReSharper disable UnusedMember.Global 7 | namespace SimpleCore.Selenium.Utilities 8 | { 9 | public static class Tabs 10 | { 11 | public static void LeftTab(this IWebDriver driver) 12 | { 13 | new Actions(driver).SendKeys(Keys.Control).SendKeys(Keys.Shift).SendKeys(Keys.Tab).Build().Perform(); 14 | } 15 | 16 | public static void RightTab(this IWebDriver driver) 17 | { 18 | new Actions(driver).SendKeys(Keys.Control).SendKeys(Keys.Tab).Build().Perform(); 19 | } 20 | 21 | public static void SelectTab(this IWebDriver driver, Predicate fn) 22 | { 23 | var current = driver.CurrentWindowHandle; 24 | foreach (string hnd in driver.WindowHandles) { 25 | if (fn(driver.SwitchTo().Window(hnd))) { 26 | return; 27 | } 28 | } 29 | 30 | driver.SwitchTo().Window(current); 31 | } 32 | 33 | public static void SwitchToTabByUrl(this IWebDriver driver, string url) 34 | { 35 | driver.SelectTab(tab => tab.Url.Contains(url)); 36 | } 37 | 38 | public static void SwitchToTabByTitle(this IWebDriver driver, string title) 39 | { 40 | driver.SelectTab(tab => tab.Title.Contains(title)); 41 | } 42 | 43 | public static void CreateNewTab(this IWebDriver webDriver, string url) 44 | { 45 | var windowHandles = webDriver.WindowHandles; 46 | var scriptExecutor = (IJavaScriptExecutor) webDriver; 47 | scriptExecutor.ExecuteScript(String.Format("window.open('{0}', '_blank');", url)); 48 | var newWindowHandles = webDriver.WindowHandles; 49 | var openedWindowHandle = newWindowHandles.Except(windowHandles).Single(); 50 | webDriver.SwitchTo().Window(openedWindowHandle); 51 | } 52 | 53 | public static bool TabExists(this IWebDriver driver, string title) 54 | { 55 | var current = driver.CurrentWindowHandle; 56 | foreach (string hnd in driver.WindowHandles) { 57 | if (driver.SwitchTo().Window(hnd).Title.Contains(title)) { 58 | driver.SwitchTo().Window(current); 59 | return true; 60 | } 61 | } 62 | 63 | driver.SwitchTo().Window(current); 64 | return false; 65 | } 66 | 67 | 68 | public static void CloseTab(this IWebDriver driver, string title) 69 | { 70 | driver.SwitchToTabByTitle(title); 71 | driver.Close(); 72 | } 73 | 74 | /// 75 | /// Creates a new tab. 76 | /// 77 | /// instance 78 | /// Destination 79 | /// window handle of previous tab 80 | public static string NewTab(this ChromeDriver driver, string url) 81 | { 82 | ((IJavaScriptExecutor) driver).ExecuteScript("window.open()"); 83 | 84 | var tabs = driver.WindowHandles; 85 | driver.SwitchTo().Window(tabs[1]); //switches to new tab 86 | driver.Url = (url); 87 | 88 | // Return previous tab handle 89 | return tabs[0]; 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/ColorHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | 5 | // ReSharper disable UnusedMember.Global 6 | 7 | namespace SimpleCore.Utilities 8 | { 9 | /// 10 | /// Color utilities. 11 | /// 12 | /// 13 | /// 14 | /// 15 | public static class ColorHelper 16 | { 17 | public static readonly Color AbsoluteRed = Color.FromArgb(Byte.MaxValue, Byte.MaxValue, 0, 0); 18 | public static readonly Color AbsoluteGreen = Color.FromArgb(Byte.MaxValue, 0, Byte.MaxValue, 0); 19 | public static readonly Color AbsoluteBlue = Color.FromArgb(Byte.MaxValue, 0, 0, Byte.MaxValue); 20 | 21 | 22 | /// 23 | /// Creates color with corrected brightness. 24 | /// 25 | /// Color to correct. 26 | /// The brightness correction factor. Must be between -1 and 1. 27 | /// Negative values produce darker colors. 28 | /// 29 | /// Corrected structure. 30 | /// 31 | public static Color ChangeBrightness(this Color color, float correctionFactor) 32 | { 33 | // Adapted from https://gist.github.com/zihotki/09fc41d52981fb6f93a81ebf20b35cd5 34 | 35 | float red = color.R; 36 | float green = color.G; 37 | float blue = color.B; 38 | 39 | if (correctionFactor < 0) { 40 | correctionFactor = 1 + correctionFactor; 41 | red *= correctionFactor; 42 | green *= correctionFactor; 43 | blue *= correctionFactor; 44 | } 45 | else { 46 | red = (Byte.MaxValue - red) * correctionFactor + red; 47 | green = (Byte.MaxValue - green) * correctionFactor + green; 48 | blue = (Byte.MaxValue - blue) * correctionFactor + blue; 49 | } 50 | 51 | return Color.FromArgb(color.A, (int) red, (int) green, (int) blue); 52 | } 53 | 54 | public static Color ToColor(this ConsoleColor c) 55 | { 56 | int cInt = (int) c; 57 | 58 | int brightnessCoefficient = ((cInt & 8) > 0) ? 2 : 1; 59 | int r = ((cInt & 4) > 0) ? 64 * brightnessCoefficient : 0; 60 | int g = ((cInt & 2) > 0) ? 64 * brightnessCoefficient : 0; 61 | int b = ((cInt & 1) > 0) ? 64 * brightnessCoefficient : 0; 62 | 63 | return Color.FromArgb(r, g, b); 64 | } 65 | 66 | public static IEnumerable GetGradients(Color start, Color end, int steps) 67 | { 68 | // https://stackoverflow.com/questions/2011832/generate-color-gradient-in-c-sharp 69 | 70 | int stepA = ((end.A - start.A) / (steps - 1)); 71 | int stepR = ((end.R - start.R) / (steps - 1)); 72 | int stepG = ((end.G - start.G) / (steps - 1)); 73 | int stepB = ((end.B - start.B) / (steps - 1)); 74 | 75 | for (int i = 0; i < steps; i++) { 76 | 77 | int startA = start.A + (stepA * i); 78 | int startR = start.R + (stepR * i); 79 | int startG = start.G + (stepG * i); 80 | int startB = start.B + (stepB * i); 81 | 82 | yield return Color.FromArgb(startA, startR, startG, startB); 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /SimpleCore.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30330.147 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleCore", "SimpleCore\SimpleCore.csproj", "{635E0746-EACB-473D-A71D-6F09AF61D04E}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{B98E7C26-7DA0-4DA2-B2E0-76E0B14320BB}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleCore.Net", "SimpleCore.Net\SimpleCore.Net.csproj", "{B397667E-0277-4129-8CF3-578C846CFFC2}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{279F4354-97DB-4E97-BFFC-F9C09E39F36E}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleCore.Cli", "SimpleCore.Cli\SimpleCore.Cli.csproj", "{B7B0C8EC-2E19-445D-911A-312E691336FD}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleCore.Selenium", "SimpleCore.Selenium\SimpleCore.Selenium.csproj", "{D9ADB010-34EF-4ED4-806C-C57F6707AA93}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTest", "UnitTest\UnitTest.csproj", "{34DF15B6-1334-4B08-B24E-E4BD83EF08BE}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestBenchmark", "TestBenchmark\TestBenchmark.csproj", "{2042E2F0-6FA3-47E5-B491-2CAD8A414269}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {635E0746-EACB-473D-A71D-6F09AF61D04E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {635E0746-EACB-473D-A71D-6F09AF61D04E}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {635E0746-EACB-473D-A71D-6F09AF61D04E}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {635E0746-EACB-473D-A71D-6F09AF61D04E}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {B98E7C26-7DA0-4DA2-B2E0-76E0B14320BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {B98E7C26-7DA0-4DA2-B2E0-76E0B14320BB}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {B98E7C26-7DA0-4DA2-B2E0-76E0B14320BB}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {B98E7C26-7DA0-4DA2-B2E0-76E0B14320BB}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {B397667E-0277-4129-8CF3-578C846CFFC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {B397667E-0277-4129-8CF3-578C846CFFC2}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {B397667E-0277-4129-8CF3-578C846CFFC2}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {B397667E-0277-4129-8CF3-578C846CFFC2}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {B7B0C8EC-2E19-445D-911A-312E691336FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {B7B0C8EC-2E19-445D-911A-312E691336FD}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {B7B0C8EC-2E19-445D-911A-312E691336FD}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {B7B0C8EC-2E19-445D-911A-312E691336FD}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {D9ADB010-34EF-4ED4-806C-C57F6707AA93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {D9ADB010-34EF-4ED4-806C-C57F6707AA93}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {D9ADB010-34EF-4ED4-806C-C57F6707AA93}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {D9ADB010-34EF-4ED4-806C-C57F6707AA93}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {34DF15B6-1334-4B08-B24E-E4BD83EF08BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {34DF15B6-1334-4B08-B24E-E4BD83EF08BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {34DF15B6-1334-4B08-B24E-E4BD83EF08BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {34DF15B6-1334-4B08-B24E-E4BD83EF08BE}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {2042E2F0-6FA3-47E5-B491-2CAD8A414269}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {2042E2F0-6FA3-47E5-B491-2CAD8A414269}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {2042E2F0-6FA3-47E5-B491-2CAD8A414269}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {2042E2F0-6FA3-47E5-B491-2CAD8A414269}.Release|Any CPU.Build.0 = Release|Any CPU 56 | EndGlobalSection 57 | GlobalSection(SolutionProperties) = preSolution 58 | HideSolutionNode = FALSE 59 | EndGlobalSection 60 | GlobalSection(ExtensibilityGlobals) = postSolution 61 | SolutionGuid = {D1A642F1-F624-442F-94E8-2B621607C04F} 62 | EndGlobalSection 63 | EndGlobal 64 | -------------------------------------------------------------------------------- /SimpleCore.Cli/NConsoleOption.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.CodeAnalysis; 5 | using System.Drawing; 6 | using System.Linq; 7 | using SimpleCore.Model; 8 | 9 | // ReSharper disable InconsistentNaming 10 | 11 | // ReSharper disable UnusedMember.Global 12 | 13 | 14 | #pragma warning disable CS8618 15 | 16 | namespace SimpleCore.Cli 17 | { 18 | public delegate object? NConsoleFunction(); 19 | 20 | 21 | /// 22 | /// Represents an interactive console/shell option 23 | /// 24 | public class NConsoleOption 25 | { 26 | /// 27 | /// Display name 28 | /// 29 | [MaybeNull] 30 | public virtual string Name { get; set; } 31 | 32 | /// 33 | /// Function to execute when selected 34 | /// 35 | public virtual NConsoleFunction Function { get; set; } 36 | 37 | /// 38 | /// Function to execute when selected with modifiers () 39 | /// 40 | public virtual NConsoleFunction? AltFunction { get; set; } 41 | 42 | /// 43 | /// Function to execute when selected with modifiers () 44 | /// 45 | public virtual NConsoleFunction? CtrlFunction { get; set; } 46 | 47 | /// 48 | /// Function to execute when selected with modifiers () 49 | /// 50 | public virtual NConsoleFunction? ShiftFunction { get; set; } 51 | 52 | /// 53 | /// Function to execute when selected with modifiers () 54 | /// 55 | public virtual NConsoleFunction? ComboFunction { get; set; } 56 | 57 | /// 58 | /// Information about this 59 | /// 60 | public virtual IViewable? Data { get; set; } 61 | 62 | 63 | public virtual Color? Color { get; set; } 64 | 65 | public static List FromList(IList values) => 66 | FromArray(values, arg => arg!.ToString()!).ToList(); 67 | 68 | protected bool Equals(NConsoleOption other) 69 | { 70 | return Name == other.Name && Function.Equals(other.Function) && Equals(AltFunction, other.AltFunction) && 71 | Equals(CtrlFunction, other.CtrlFunction) && Equals(ShiftFunction, other.ShiftFunction) && 72 | Equals(ComboFunction, other.ComboFunction) && Equals(Data, other.Data) && 73 | Nullable.Equals(Color, other.Color); 74 | } 75 | 76 | public override bool Equals(object? obj) 77 | { 78 | if (ReferenceEquals(null, obj)) return false; 79 | if (ReferenceEquals(this, obj)) return true; 80 | if (obj.GetType() != this.GetType()) return false; 81 | return Equals((NConsoleOption) obj); 82 | } 83 | 84 | public override int GetHashCode() 85 | { 86 | unchecked { 87 | int hashCode = Name.GetHashCode(); 88 | hashCode = (hashCode * 397) ^ Function.GetHashCode(); 89 | hashCode = (hashCode * 397) ^ (AltFunction != null ? AltFunction.GetHashCode() : 0); 90 | hashCode = (hashCode * 397) ^ (CtrlFunction != null ? CtrlFunction.GetHashCode() : 0); 91 | hashCode = (hashCode * 397) ^ (ShiftFunction != null ? ShiftFunction.GetHashCode() : 0); 92 | hashCode = (hashCode * 397) ^ (ComboFunction != null ? ComboFunction.GetHashCode() : 0); 93 | hashCode = (hashCode * 397) ^ (Data != null ? Data.GetHashCode() : 0); 94 | hashCode = (hashCode * 397) ^ Color.GetHashCode(); 95 | return hashCode; 96 | } 97 | } 98 | 99 | public static NConsoleOption[] FromArray(T[] values) => FromArray(values, arg => arg!.ToString()!); 100 | 101 | public static NConsoleOption[] FromArray(IList values, Func getName) 102 | { 103 | var rg = new NConsoleOption[values.Count]; 104 | 105 | for (int i = 0; i < rg.Length; i++) { 106 | var option = values[i]; 107 | 108 | string name = getName(option); 109 | 110 | rg[i] = new NConsoleOption 111 | { 112 | Name = name, 113 | Function = () => option 114 | }; 115 | } 116 | 117 | return rg; 118 | } 119 | 120 | public static NConsoleOption[] FromEnum() where TEnum : Enum 121 | { 122 | var options = (TEnum[]) Enum.GetValues(typeof(TEnum)); 123 | return FromArray(options, e => Enum.GetName(typeof(TEnum), e) ?? throw new InvalidOperationException()); 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /SimpleCore/Numeric/MathHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using BE = System.Linq.Expressions.BinaryExpression; 4 | using PE = System.Linq.Expressions.ParameterExpression; 5 | 6 | // ReSharper disable FieldCanBeMadeReadOnly.Local 7 | 8 | // ReSharper disable UnusedMember.Global 9 | 10 | namespace SimpleCore.Numeric 11 | { 12 | public enum MetricUnit 13 | { 14 | // Bit, 15 | // Byte, 16 | 17 | Kilo = 1, 18 | Mega, 19 | Giga, 20 | Tera, 21 | Peta, 22 | Exa, 23 | Zetta, 24 | Yotta 25 | } 26 | 27 | public static class MathHelper 28 | { 29 | /// 30 | /// SI 31 | /// 32 | public const double MAGNITUDE = 1000D; 33 | 34 | /// 35 | /// ISO/IEC 80000 36 | /// 37 | public const double MAGNITUDE2 = 1024D; 38 | 39 | /// 40 | /// Convert the given bytes to 41 | /// 42 | /// Value in bytes to be converted 43 | /// Unit to convert to 44 | /// Converted bytes 45 | public static double ConvertToUnit(double bytes, MetricUnit type) 46 | { 47 | // var rg = new[] { "k","M","G","T","P","E","Z","Y"}; 48 | // var pow = rg.ToList().IndexOf(type) +1; 49 | 50 | 51 | int pow = (int) type; 52 | double v = bytes / Math.Pow(MAGNITUDE, pow); 53 | 54 | 55 | return v; 56 | } 57 | 58 | /*public static bool IsPointerSub(this Type t) 59 | { 60 | return t == typeof(void*) || t.IsPointer || t == typeof(IntPtr); 61 | } 62 | 63 | public static bool IsNumeric(this Type t) 64 | { 65 | return t.IsInteger() || t.IsReal(); 66 | } 67 | 68 | public static bool IsReal(this Type t) 69 | { 70 | var nx = Type.GetTypeCode(t); 71 | bool realCode = nx is >= TypeCode.Single and <= TypeCode.Decimal; 72 | bool half = t == typeof(Half); 73 | 74 | return realCode || half; 75 | } 76 | 77 | public static bool IsInteger(this Type t) 78 | { 79 | var nx = Type.GetTypeCode(t); 80 | return nx is <= TypeCode.UInt64 and >= TypeCode.SByte; 81 | 82 | }*/ 83 | 84 | public static string ConvertToUnit(double len) 85 | { 86 | //https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net 87 | 88 | 89 | int order = 0; 90 | 91 | while (len >= MAGNITUDE2 && order < Sizes.Length - 1) { 92 | order++; 93 | len /= MAGNITUDE2; 94 | } 95 | 96 | // Adjust the format string to your preferences. For example "{0:0.#}{1}" would 97 | // show a single decimal place, and no space. 98 | string result = $"{len:0.##} {Sizes[order]}"; 99 | 100 | 101 | return result; 102 | } 103 | 104 | private static readonly string[] Sizes = {"B", "KB", "MB", "GB", "TB"}; 105 | 106 | public static T Add(T a, T b) => MathImplementation.Add(a, b); 107 | 108 | public static T Subtract(T a, T b) => MathImplementation.Sub(a, b); 109 | 110 | public static T Multiply(T a, T b) => MathImplementation.Mul(a, b); 111 | 112 | public static T Divide(T a, T b) => MathImplementation.Div(a, b); 113 | 114 | private static class MathImplementation 115 | { 116 | internal static readonly Func Add; 117 | internal static readonly Func Sub; 118 | internal static readonly Func Mul; 119 | internal static readonly Func Div; 120 | 121 | static MathImplementation() 122 | { 123 | Add = Create(Expression.Add); 124 | Sub = Create(Expression.Subtract); 125 | Mul = Create(Expression.Multiply); 126 | Div = Create(Expression.Divide); 127 | } 128 | 129 | private static Func Create(Func fx) 130 | { 131 | var paramA = Expression.Parameter(typeof(T)); 132 | var paramB = Expression.Parameter(typeof(T)); 133 | var body = fx(paramA, paramB); 134 | return Expression.Lambda>(body, paramA, paramB).Compile(); 135 | 136 | } 137 | } 138 | 139 | public static bool IsPrime(int number) 140 | { 141 | switch (number) { 142 | case <= 1: 143 | return false; 144 | case 2: 145 | return true; 146 | } 147 | 148 | if (number % 2 == 0) 149 | return false; 150 | 151 | int boundary = (int) Math.Floor(Math.Sqrt(number)); 152 | 153 | for (int i = 3; i <= boundary; i += 2) 154 | if (number % i == 0) 155 | return false; 156 | 157 | return true; 158 | 159 | /* 160 | * | Method | Mean | Error | StdDev | 161 | |---------:|---------:|----------:|----------:| 162 | | IsPrime | 2.098 ns | 0.0211 ns | 0.0187 ns | 163 | | IsPrime2 | 2.568 ns | 0.0074 ns | 0.0061 ns | 164 | */ 165 | 166 | /* 167 | * if (number == 1) return false; 168 | if (number == 2) return true; 169 | 170 | double limit = Math.Ceiling(Math.Sqrt(number)); //hoisting the loop limit 171 | 172 | for (int i = 2; i <= limit; ++i) 173 | if (number % i == 0) 174 | return false; 175 | return true; 176 | */ 177 | 178 | } 179 | 180 | public static float Distance(byte[] first, byte[] second) 181 | { 182 | int sum = 0; 183 | 184 | // We'll use which ever array is shorter. 185 | int length = first.Length > second.Length ? second.Length : first.Length; 186 | 187 | for (int x = 0; x < length; x++) { 188 | sum += (int) Math.Pow((first[x] - second[x]), 2); 189 | } 190 | 191 | return sum / (float) length; 192 | } 193 | } 194 | } -------------------------------------------------------------------------------- /UnitTest/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Drawing; 5 | using System.Globalization; 6 | using System.Linq; 7 | using System.Text.Unicode; 8 | using NUnit.Framework; 9 | using NUnit.Framework.Interfaces; 10 | using SimpleCore.Diagnostics; 11 | using SimpleCore.Model; 12 | using SimpleCore.Net; 13 | using SimpleCore.Numeric; 14 | using SimpleCore.Utilities; 15 | 16 | // ReSharper disable UnusedMember.Local 17 | 18 | // ReSharper disable InconsistentNaming 19 | #pragma warning disable 649, IDE0059 20 | 21 | namespace UnitTest 22 | { 23 | public class Tests 24 | { 25 | [SetUp] 26 | public void Setup() { } 27 | 28 | [Test] 29 | public void MathTest() 30 | { 31 | Assert.AreEqual(MathHelper.Add(1, 1), 2); 32 | Assert.AreEqual(MathHelper.Subtract(1, 1), 0); 33 | 34 | Assert.AreEqual(MathHelper.Multiply(2, 2), 4); 35 | Assert.AreEqual(MathHelper.Divide(10, 5), 2); 36 | } 37 | 38 | [Test] 39 | [TestCase(@"https://i.imgur.com/QtCausw.png", true)] 40 | [TestCase(@"http://tidder.xyz/?imagelink=https://i.imgur.com/QtCausw.png", false)] 41 | [TestCase(@"http://tidder.xyz/", false)] 42 | [TestCase(@"https://i.imgur.com/QtCausw.png", true)] 43 | public void UriAliveTest(string s, bool b) 44 | { 45 | Assert.AreEqual(b,Network.IsAlive(new Uri((s)))); 46 | } 47 | 48 | [Test] 49 | public void MediaTypesTest() 50 | { 51 | const string jpg = "https://i.ytimg.com/vi/r45a-l9Gqdk/hqdefault.jpg"; 52 | 53 | var i = MediaTypes.Identify(jpg); 54 | Assert.True(Network.IsUri(jpg, out var u)); 55 | Assert.True(MediaTypes.GetExtensions(i).Contains("jpe")); 56 | Assert.True(MediaTypes.GetTypeComponent(i) == "image"); 57 | Assert.True(MediaTypes.GetSubTypeComponent(i) == "jpeg"); 58 | 59 | 60 | } 61 | 62 | [Test] 63 | public void EnumTest() 64 | { 65 | var name1 = "combo1"; 66 | var p = Enum.Parse(name1); 67 | var flags = Enums.GetSetFlags(p, false); 68 | var str = flags.QuickJoin(); 69 | 70 | Assert.AreEqual(str, "a, b, c, combo1"); 71 | } 72 | 73 | [Flags] 74 | private enum MyEnum 75 | { 76 | a = 0, 77 | b = 1 << 0, 78 | c = 1 << 1, 79 | 80 | combo1 = b | c, 81 | } 82 | 83 | private class EnumerationTestType : Enumeration 84 | { 85 | public static string str; 86 | public string str2; 87 | 88 | public static readonly EnumerationTestType a1 = new(1, "g"); 89 | 90 | public EnumerationTestType(int id, string name) : base(id, name) { } 91 | } 92 | 93 | [Test] 94 | public void EnumerationTest() 95 | { 96 | var rg = Enumeration.GetAll().ToArray(); 97 | 98 | TestContext.WriteLine(rg.Length); 99 | 100 | foreach (var a in rg) { 101 | TestContext.WriteLine(a.ToString()); 102 | } 103 | 104 | TestContext.WriteLine(Enumeration.GetNextId()); 105 | } 106 | 107 | [Test] 108 | public void GuardTest() 109 | { 110 | Assert.Throws(() => 111 | { 112 | Guard.Assert(false); 113 | 114 | }); 115 | 116 | Assert.Throws(() => 117 | { 118 | Guard.AssertNotNull(null); 119 | 120 | }); 121 | 122 | Assert.Throws(() => 123 | { 124 | Guard.AssertArgumentNotNull(null); 125 | 126 | }); 127 | 128 | 129 | Assert.Throws(() => 130 | { 131 | Guard.AssertEqual("a", "b"); 132 | 133 | }); 134 | 135 | Assert.DoesNotThrow(() => 136 | { 137 | Guard.AssertEqual("a", "a"); 138 | 139 | }); 140 | 141 | Assert.Throws(() => 142 | { 143 | Guard.AssertArgument(false, "g"); 144 | }); 145 | 146 | Assert.Throws(() => 147 | { 148 | Guard.Fail(); 149 | }); 150 | } 151 | 152 | [Test] 153 | public void CharTest() 154 | { 155 | Assert.True(Strings.IsCharInRange(0x0400, UnicodeRanges.Cyrillic)); 156 | Assert.True(Strings.IsCharInRange(0x04FF, UnicodeRanges.Cyrillic)); 157 | 158 | Assert.False(Strings.IsCharInRange(0x04FF+1, UnicodeRanges.Cyrillic)); 159 | Assert.False(Strings.IsCharInRange(0x0, UnicodeRanges.Cyrillic)); 160 | Assert.True(Strings.IsCharInRange('A', UnicodeRanges.BasicLatin)); 161 | Assert.True(Strings.IsCharInRange(StringConstants.CHECK_MARK, UnicodeRanges.Dingbats)); 162 | 163 | } 164 | 165 | 166 | [Test] 167 | public void StringTest() 168 | { 169 | Assert.Null(Strings.NullIfNullOrWhiteSpace(" ")); 170 | Assert.Null(Strings.NullIfNullOrWhiteSpace("")); 171 | Assert.Null(Strings.NullIfNullOrWhiteSpace(null)); 172 | } 173 | 174 | [Test] 175 | public void CollectionsTest2() 176 | { 177 | var rg = new List() {1, 2, 3, 9, 9, 9, 1, 2, 3}; 178 | var search = new List() {1, 2, 3}; 179 | var replace = new List() {3, 2, 1}; 180 | 181 | var rg2 = rg.ReplaceAllSequences(search, replace); 182 | var rg2x = new List() {3, 2, 1, 9, 9, 9, 3, 2, 1}; 183 | 184 | Assert.True(rg2.SequenceEqual(rg2x)); 185 | } 186 | 187 | 188 | 189 | [Test] 190 | public void CollectionsTest() 191 | { 192 | var rg = new List() {1, 2, 3, 4, 5, 6, 3, 4, 5}; 193 | var search = new List() {3, 4, 5}; 194 | var replace = new List() {5, 4, 3}; 195 | 196 | 197 | rg.ReplaceAllSequences(search, replace); 198 | 199 | TestContext.WriteLine($"{rg.QuickJoin()}"); 200 | 201 | var rgNew = new List() {1, 2, 5, 4, 3, 6, 5, 4, 3}; 202 | 203 | Assert.True(rg.SequenceEqual(rgNew)); 204 | 205 | 206 | // var rg2 = new[] {"a", "foo", "bar", "hi"}; 207 | // var search2 = new[] {"foo", "bar"}; 208 | // var replace2 = new[] {"goo"}; 209 | // 210 | // 211 | // rg2 = rg2.ReplaceAllSequences(search2, replace2); 212 | // 213 | // //TestContext.WriteLine($"{rg2.QuickJoin()}"); 214 | // var rg2New = new[] {"a", "goo", "hi"}; 215 | // Assert.True(rg2.SequenceEqual(rg2New)); 216 | } 217 | } 218 | } -------------------------------------------------------------------------------- /SimpleCore/Diagnostics/Guard.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable IdentifierTypo 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Diagnostics.CodeAnalysis; 7 | using System.Linq; 8 | using System.Runtime.CompilerServices; 9 | using JetBrains.Annotations; 10 | using static SimpleCore.Internal.Common; 11 | 12 | // ReSharper disable UnusedMember.Local 13 | // ReSharper disable UnusedMember.Global 14 | #pragma warning disable IDE0051 15 | #pragma warning disable IDE0005 16 | #nullable enable 17 | 18 | #region Aliases 19 | 20 | using AC = JetBrains.Annotations.AssertionConditionAttribute; 21 | using ACT = JetBrains.Annotations.AssertionConditionType; 22 | using DNR = System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute; 23 | using DNRI = System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute; 24 | using AM = JetBrains.Annotations.AssertionMethodAttribute; 25 | using NNV = JetBrains.Annotations.NonNegativeValueAttribute; 26 | using NN = JetBrains.Annotations.NotNullAttribute; 27 | using NN2 = System.Diagnostics.CodeAnalysis.NotNullAttribute; 28 | using CBN = JetBrains.Annotations.CanBeNullAttribute; 29 | using NotNull = JetBrains.Annotations.NotNullAttribute; 30 | using DH = System.Diagnostics.DebuggerHiddenAttribute; 31 | using CA = JetBrains.Annotations.ContractAnnotationAttribute; 32 | using SFM = JetBrains.Annotations.StringFormatMethodAttribute; 33 | 34 | #endregion 35 | 36 | namespace SimpleCore.Diagnostics 37 | { 38 | /// 39 | /// Diagnostic utilities, conditions, contracts 40 | /// 41 | /// 42 | /// 43 | /// 44 | public static class Guard 45 | { 46 | /* 47 | * https://www.jetbrains.com/help/resharper/Contract_Annotations.html 48 | * https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis 49 | */ 50 | 51 | 52 | #region Contract annotations 53 | 54 | private const string VALUE_NULL_HALT = "value:null => halt"; 55 | 56 | private const string VALUE_NOTNULL_HALT = "value:notnull => halt"; 57 | 58 | private const string COND_FALSE_HALT = "condition:false => halt"; 59 | 60 | private const string UNCONDITIONAL_HALT = "=> halt"; 61 | 62 | #endregion 63 | 64 | [DH] 65 | [DNR] 66 | [AM] 67 | [CA(UNCONDITIONAL_HALT)] 68 | [SFM(STRING_FORMAT_ARG)] 69 | public static void Fail(string? msg = null, params object[] args) => Fail(msg, args); 70 | 71 | 72 | /// 73 | /// Root fail function 74 | /// 75 | [DH] 76 | [DNR] 77 | [AM] 78 | [CA(UNCONDITIONAL_HALT)] 79 | [SFM(STRING_FORMAT_ARG)] 80 | public static void Fail(string? msg = null, params object[] args) 81 | where TException : Exception, new() 82 | { 83 | TException exception; 84 | 85 | if (msg != null) { 86 | string s = String.Format(msg, args); 87 | 88 | exception = (TException) Activator.CreateInstance(typeof(TException), s)!; 89 | } 90 | else { 91 | exception = new TException(); 92 | } 93 | 94 | throw exception; 95 | } 96 | 97 | [DH] 98 | [AM] 99 | [CA(COND_FALSE_HALT)] 100 | public static void Assert([AC(ACT.IS_TRUE)] [DNRI(false)] bool condition, 101 | string? msg = null, params object[] args) 102 | { 103 | Assert(condition, msg, args); 104 | } 105 | 106 | 107 | /// 108 | /// Root assertion function 109 | /// 110 | [DH] 111 | [AM] 112 | [CA(COND_FALSE_HALT)] 113 | [SFM(STRING_FORMAT_ARG)] 114 | public static void Assert([AC(ACT.IS_TRUE)] [DNRI(false)] bool condition, 115 | string? msg = null, params object[] args) 116 | where TException : Exception, new() 117 | { 118 | if (!condition) { 119 | Fail(msg, args); 120 | } 121 | } 122 | 123 | [DH] 124 | [AM] 125 | [CA(COND_FALSE_HALT)] 126 | public static void AssertArgument([AC(ACT.IS_TRUE)] [DNRI(false)] bool condition, 127 | string? name = null) 128 | { 129 | Assert(condition, name); 130 | } 131 | 132 | [DH] 133 | [AM] 134 | [CA(VALUE_NULL_HALT)] 135 | public static void AssertArgumentNotNull([NN] [AC(ACT.IS_NOT_NULL)] object? value, 136 | string? name = null) 137 | { 138 | Assert(value != null, name); 139 | } 140 | 141 | 142 | [DH] 143 | [AM] 144 | [CA(VALUE_NULL_HALT)] 145 | public static void AssertNotNull([NN] [AC(ACT.IS_NOT_NULL)] object? value, string? name = null) 146 | { 147 | Assert(value != null, name); 148 | } 149 | 150 | [DH] 151 | [AM] 152 | public static void AssertEqual(object a, object b) 153 | { 154 | Assert(a.Equals(b)); 155 | } 156 | 157 | 158 | [DH] 159 | [AM] 160 | public static void AssertEqual(T a, T b) where T : IEquatable 161 | { 162 | Assert(a.Equals(b)); 163 | } 164 | 165 | 166 | [DH] 167 | [AM] 168 | public static void AssertContains(IEnumerable enumerable, T name) 169 | { 170 | Assert(enumerable.Contains(name)); 171 | } 172 | 173 | [DH] 174 | [AM] 175 | public static void AssertPositive([NNV] long value, string? name = null) 176 | { 177 | Assert(value > 0, name); 178 | } 179 | 180 | [DH] 181 | [AM] 182 | public static void AssertThrows(Action f) where T : Exception 183 | { 184 | bool throws = false; 185 | 186 | try { 187 | f(); 188 | } 189 | catch (T) { 190 | throws = true; 191 | } 192 | 193 | if (!throws) { 194 | Fail(); 195 | } 196 | } 197 | 198 | [DH] 199 | [AM] 200 | public static void AssertAll([DNRI(false)] [AC(ACT.IS_TRUE)] params bool[] conditions) 201 | { 202 | foreach (bool condition in conditions) { 203 | Assert(condition); 204 | } 205 | } 206 | } 207 | 208 | public sealed class GuardException : Exception 209 | { 210 | public GuardException() { } 211 | 212 | public GuardException([CanBeNull] string? message) : base(message) { } 213 | } 214 | } -------------------------------------------------------------------------------- /Test/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Drawing; 6 | using System.Globalization; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Net; 10 | using System.Net.NetworkInformation; 11 | using System.Runtime.InteropServices; 12 | using System.Text; 13 | using System.Text.RegularExpressions; 14 | using System.Text.Unicode; 15 | using System.Threading; 16 | using System.Threading.Tasks; 17 | using AngleSharp.Common; 18 | using AngleSharp.Html.Dom; 19 | using AngleSharp.Html.Parser; 20 | using BenchmarkDotNet.Attributes; 21 | using BenchmarkDotNet.Mathematics; 22 | using BenchmarkDotNet.Running; 23 | using Newtonsoft.Json.Linq; 24 | using SimpleCore.Cli; 25 | using SimpleCore.Diagnostics; 26 | using SimpleCore.Model; 27 | using SimpleCore.Net; 28 | using SimpleCore.Numeric; 29 | using SimpleCore.Utilities; 30 | using SimpleCore.Utilities.Configuration; 31 | using Console = System.Console; 32 | using MathHelper = SimpleCore.Numeric.MathHelper; 33 | using Timer = System.Timers.Timer; 34 | 35 | #pragma warning disable IDE0060 36 | 37 | namespace Test 38 | { 39 | // nuget pack -Prop Configuration=Release 40 | 41 | // C:\Library\Nuget 42 | // dotnet pack -c Release -o %cd% 43 | // dotnet nuget push "*.nupkg" 44 | // del *.nupkg & dotnet pack -c Release -o %cd% & dotnet nuget push "*.nupkg" 45 | 46 | /* 47 | * Novus https://github.com/Decimation/Novus 48 | * NeoCore https://github.com/Decimation/NeoCore 49 | * RazorSharp https://github.com/Decimation/RazorSharp 50 | * 51 | * SimpleCore https://github.com/Decimation/SimpleCore 52 | * SimpleSharp https://github.com/Decimation/SimpleSharp 53 | * 54 | * Memkit https://github.com/Decimation/Memkit 55 | * 56 | */ 57 | 58 | public static class Program 59 | { 60 | public static void Main(string[] args) 61 | { 62 | /*var i = new List() { 1, 2, 3 }; 63 | var o = NConsoleOption.FromList(i); 64 | 65 | o[0].ShiftFunction = () => 66 | { 67 | Debug.WriteLine("shift"); 68 | return null; 69 | }; 70 | o[0].ComboFunction = () => 71 | { 72 | Debug.WriteLine("combo"); 73 | return null; 74 | }; 75 | o[0].CtrlFunction = () => 76 | { 77 | Debug.WriteLine("ctrl"); 78 | return null; 79 | }; 80 | o[0].AltFunction = () => 81 | { 82 | Debug.WriteLine("alt"); 83 | return null; 84 | }; 85 | // o[0].Function = () => 86 | // { 87 | // Debug.WriteLine("main"); 88 | // return null; 89 | // }; 90 | var d = new NConsoleDialog() { Options = o, SelectMultiple = true }; 91 | NConsole.Init(); 92 | new Thread(() => 93 | { 94 | Thread.Sleep(5000); 95 | d.Options.Add(new NConsoleOption() { Name = "4", Function = () => { return 4; } }); 96 | }).Start(); 97 | var x = NConsole.ReadOptions(d); 98 | Console.WriteLine(x);*/ 99 | 100 | //var i = new List() { 1, 2, 3 }; 101 | //var o = NConsoleOption.FromList(i); 102 | 103 | //Console.WriteLine(o[^1].GetHashCode()); 104 | //new Thread(() => 105 | //{ 106 | // Thread.Sleep(2000); 107 | // //o.Add(new NConsoleOption() { Name = "3", Function = () => { return 3; } }); 108 | // o[^1].Function = () => { return 10; }; 109 | // o[^1].Name = "10"; 110 | // Console.WriteLine(o[^1].GetHashCode()); 111 | 112 | //}).Start(); 113 | 114 | 115 | //NConsole.ReadOptions(new NConsoleDialog() {Options = o}); 116 | 117 | //var s = "http://tidder.xyz/?imagelink=https://i.imgur.com/QtCausw.png"; 118 | 119 | //var hostUri = Network.GetHostUri(new Uri(s)); 120 | //Console.WriteLine(hostUri); 121 | //Console.WriteLine(Network.IsUriAlive2(new Uri(s))); 122 | //var sw2 = Stopwatch.StartNew(); 123 | //Console.WriteLine(Network.IsUriAlive(hostUri)); 124 | //sw2.Stop(); 125 | //Console.WriteLine(sw2.Elapsed.TotalSeconds); 126 | //var component = Network.GetHostComponent(new Uri(s)); 127 | //var address = Dns.GetHostAddresses(component)[0]; 128 | //Console.WriteLine(address); 129 | 130 | //var sw = Stopwatch.StartNew(); 131 | //var p2 = new Ping(); 132 | //var t2 =p2.SendPingAsync(address, (int)TimeSpan.FromSeconds(3).TotalMilliseconds); 133 | //await t2; 134 | //sw.Stop(); 135 | //Console.WriteLine(sw.Elapsed.TotalSeconds); 136 | 137 | //var x = Network.Identify(address); 138 | //Console.WriteLine(x); 139 | 140 | //var p = new Ping(); 141 | //var component = Network.GetHostComponent(new Uri(s)); 142 | //var address = Dns.GetHostAddresses(component.ToString())[0]; 143 | //Console.WriteLine(address); 144 | //var x =p.SendPingAsync(address); 145 | //x.Wait(); 146 | //Console.WriteLine(x.Result.Status); 147 | //Console.WriteLine(Network.IsUriAlive2((component))); 148 | //Encoding.Convert(Encoding.GetEncoding(437), Encoding.UTF8, new byte[] { 1 }); 149 | 150 | 151 | /* 152 | * int wchars_num = MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, NULL , 0 ); 153 | wchar_t* wstr = new wchar_t[wchars_num]; 154 | MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, wstr , wchars_num ); 155 | */ 156 | 157 | //SetConsoleOutputCP(65001); 158 | //string s; 159 | //Console.WriteLine(StringConstants.CHECK_MARK); 160 | 161 | //var p = BitConverter.GetBytes(StringConstants.CHECK_MARK); 162 | //Console.WriteLine(p.Length); 163 | //var c =MultiByteToWideChar(65001,0, p, -1, null, 0); 164 | //char[] rg = new char[c]; 165 | //MultiByteToWideChar(65001, 0, p, -1, rg, rg.Length); 166 | 167 | 168 | //Console.WriteLine(c); 169 | //Console.WriteLine(new string(rg)); 170 | //Console.WriteLine(StringConstants.CHECK_MARK); 171 | 172 | //foreach (char c1 in rg) { 173 | // Console.WriteLine($"{c1} {(int)c1}"); 174 | //} 175 | 176 | 177 | Console.WriteLine(StringConstants.CHECK_MARK); 178 | 179 | var s = "https://image4.uhdpaper.com/wallpaper/azur-lane-atago-anime-girl-uhdpaper.com-4K-4.1734.jpg"; 180 | var s2 = "https://i.imgur.com/QtCausw.png"; 181 | 182 | 183 | var i=Test(s2); 184 | 185 | i.Dispose(); 186 | 187 | } 188 | 189 | private static Image Test(string s) 190 | { 191 | 192 | 193 | 194 | using var wc = new WebClient(); 195 | 196 | 197 | using var read = wc.OpenRead(s); 198 | 199 | return Image.FromStream(read); 200 | 201 | 202 | } 203 | } 204 | } -------------------------------------------------------------------------------- /SimpleCore.Selenium/Highlight.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | // ReSharper disable UnusedMember.Global 3 | 4 | namespace SimpleCore.Selenium 5 | { 6 | public class Highlight 7 | { 8 | // assuming JS is enabled 9 | private readonly IJavaScriptExecutor m_driver; 10 | private IWebElement m_lastElem = null; 11 | private string m_lastBorder = null; 12 | 13 | private const string SCRIPT_GET_ELEMENT_BORDER = "/*\n" + 14 | " * Returns all border properties of the specified element as String,\n" + 15 | " * in order of \"width style color\" delimited by ';' (semicolon) in the form of:\n" + 16 | " * \n" + 17 | " * \"2px inset #000000;2px inset #000000;2px inset #000000;2px inset #000000\"\n" + 18 | " * \"medium none #ccc;medium none #ccc;1px solid #e5e5e5;medium none #ccc\"\n" + 19 | " * etc.\n" + 20 | " */\n" + 21 | "var elem = arguments[0]; \n" + 22 | "if (elem.currentStyle) {\n" + 23 | " // Branch for IE 6,7,8. No idea how this works on IE9, but the script\n" + 24 | " // should take care of it.\n" + 25 | " var style = elem.currentStyle;\n" + 26 | " var border = style['borderTopWidth']\n" + 27 | " + ' ' + style['borderTopStyle']\n" + 28 | " + ' ' + style['borderTopColor']\n" + 29 | " + ';' + style['borderRightWidth']\n" + 30 | " + ' ' + style['borderRightStyle']\n" + 31 | " + ' ' + style['borderRightColor']\n" + 32 | " + ';' + style['borderBottomWidth']\n" + 33 | " + ' ' + style['borderBottomStyle']\n" + 34 | " + ' ' + style['borderBottomColor']\n" + 35 | " + ';' + style['borderLeftWidth']\n" + 36 | " + ' ' + style['borderLeftStyle']\n" + 37 | " + ' ' + style['borderLeftColor'];\n" + 38 | "} else if (window.getComputedStyle) {\n" + 39 | " // Branch for FF, Chrome, Opera\n" + 40 | " var style = document.defaultView.getComputedStyle(elem);\n" + 41 | " var border = style.getPropertyValue('border-top-width')\n" + 42 | " + ' ' + style.getPropertyValue('border-top-style')\n" + 43 | " + ' ' + style.getPropertyValue('border-top-color')\n" + 44 | " + ';' + style.getPropertyValue('border-right-width')\n" + 45 | " + ' ' + style.getPropertyValue('border-right-style')\n" + 46 | " + ' ' + style.getPropertyValue('border-right-color')\n" + 47 | " + ';' + style.getPropertyValue('border-bottom-width')\n" + 48 | " + ' ' + style.getPropertyValue('border-bottom-style')\n" + 49 | " + ' ' + style.getPropertyValue('border-bottom-color')\n" + 50 | " + ';' + style.getPropertyValue('border-left-width')\n" + 51 | " + ' ' + style.getPropertyValue('border-left-style')\n" + 52 | " + ' ' + style.getPropertyValue('border-left-color');\n" + 53 | "}\n" + 54 | "// highlight the element\n" + 55 | "elem.style.border = '2px solid red';\n" + 56 | "return border;"; 57 | 58 | private const string SCRIPT_UNHIGHLIGHT_ELEMENT = "var elem = arguments[0];\n" + 59 | "var borders = arguments[1].split(';');\n" + 60 | "elem.style.borderTop = borders[0];\n" + 61 | "elem.style.borderRight = borders[1];\n" + 62 | "elem.style.borderBottom = borders[2];\n" + 63 | "elem.style.borderLeft = borders[3];"; 64 | 65 | public Highlight(IWebDriver driver) 66 | { 67 | m_driver = (IJavaScriptExecutor) driver; 68 | } 69 | 70 | public void HighlightElement(IWebElement elem) 71 | { 72 | ClearHighlight(); 73 | 74 | // remember the new element 75 | m_lastElem = elem; 76 | m_lastBorder = (string) (m_driver.ExecuteScript(SCRIPT_GET_ELEMENT_BORDER, elem)); 77 | } 78 | 79 | /// 80 | /// Removes previously highlighted element. 81 | /// 82 | public void ClearHighlight() 83 | { 84 | if (m_lastElem != null) { 85 | try { 86 | // if there already is a highlighted element, unhighlight it 87 | m_driver.ExecuteScript(SCRIPT_UNHIGHLIGHT_ELEMENT, m_lastElem, m_lastBorder); 88 | } 89 | catch (StaleElementReferenceException) { 90 | // the page got reloaded, the element isn't there 91 | } 92 | finally { 93 | // element either restored or wasn't valid, nullify in both cases 94 | m_lastElem = null; 95 | } 96 | } 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /SimpleCore.Net/MediaTypes.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using RestSharp; 3 | using SimpleCore.Diagnostics; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Net; 9 | using System.Runtime.InteropServices; 10 | 11 | // ReSharper disable InconsistentNaming 12 | 13 | // ReSharper disable IdentifierTypo 14 | 15 | #pragma warning disable 8602 16 | #pragma warning disable 8604 17 | #pragma warning disable 8625 18 | #pragma warning disable 8618 19 | #pragma warning disable IDE0059 20 | 21 | // ReSharper disable UnusedMember.Global 22 | #nullable enable 23 | 24 | namespace SimpleCore.Net 25 | { 26 | /// 27 | /// Media types, MIME types, etc. 28 | /// 29 | public static class MediaTypes 30 | { 31 | /* 32 | * type/subtype 33 | * type/subtype;parameter=value 34 | */ 35 | 36 | //todo 37 | 38 | 39 | /// 40 | /// Identifies the MIME type of 41 | /// 42 | public static string? Identify(string url) 43 | { 44 | var res = Network.GetQueryResponse(url); 45 | 46 | return res?.ContentType; 47 | } 48 | 49 | /// 50 | /// Whether the MIME is of type 51 | /// 52 | public static bool IsType(string mime, MimeType type) => 53 | GetTypeComponent(mime) == Enum.GetName(type)!.ToLower(); 54 | 55 | public static bool IsDirect(string url, MimeType m) 56 | { 57 | //var isUri = Network.IsUri(value, out _); 58 | 59 | string? mediaType = Identify(url); 60 | 61 | if (mediaType == null) { 62 | return false; 63 | } 64 | 65 | bool b = IsType(mediaType, m); 66 | 67 | return b; 68 | } 69 | 70 | /* 71 | * https://github.com/khellang/MimeTypes/blob/master/src/MimeTypes/MimeTypeFunctions.ttinclude 72 | */ 73 | 74 | [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)] 75 | private static extern int FindMimeFromData(IntPtr pBC, 76 | [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl, 77 | [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, 78 | SizeParamIndex = 3)] 79 | byte[] pBuffer, 80 | int cbSize, 81 | [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed, 82 | int dwMimeFlags, 83 | out IntPtr ppwzMimeOut, 84 | int dwReserved); 85 | 86 | public static string ResolveFromData(string url) => ResolveFromData(WebUtilities.GetStream(url)); 87 | 88 | public static string ResolveFromData(Stream s) 89 | { 90 | var ms = s as MemoryStream; 91 | 92 | const int BLOCK_SIZE = 256; 93 | 94 | byte[] rg = new byte[BLOCK_SIZE]; 95 | 96 | int c = ms.Read(rg, 0, BLOCK_SIZE); 97 | 98 | string m = ResolveFromData(rg); 99 | 100 | return m; 101 | } 102 | 103 | public static string ResolveFromData(byte[] dataBytes, string? mimeProposed = null) 104 | { 105 | //https://stackoverflow.com/questions/2826808/how-to-identify-the-extension-type-of-the-file-using-c/2826884#2826884 106 | //https://stackoverflow.com/questions/18358548/urlmon-dll-findmimefromdata-works-perfectly-on-64bit-desktop-console-but-gener 107 | //https://stackoverflow.com/questions/11547654/determine-the-file-type-using-c-sharp 108 | //https://github.com/GetoXs/MimeDetect/blob/master/src/Winista.MimeDetect/URLMONMimeDetect/urlmonMimeDetect.cs 109 | 110 | Guard.AssertArgumentNotNull(dataBytes, nameof(dataBytes)); 111 | 112 | string mimeRet = String.Empty; 113 | 114 | if (!String.IsNullOrEmpty(mimeProposed)) { 115 | //suggestPtr = Marshal.StringToCoTaskMemUni(mimeProposed); // for your experiments ;-) 116 | mimeRet = mimeProposed; 117 | } 118 | 119 | int ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, 120 | mimeProposed, 0, out var outPtr, 0); 121 | 122 | if (ret == 0 && outPtr != IntPtr.Zero) { 123 | string str = Marshal.PtrToStringUni(outPtr)!; 124 | 125 | Marshal.FreeHGlobal(outPtr); 126 | 127 | return str; 128 | } 129 | 130 | return mimeRet; 131 | } 132 | 133 | /*private static IEnumerable<(string Extension, string Type)> GetMediaTypes( 134 | IEnumerable> mimeTypes) 135 | => mimeTypes.Where(x => x.Value.Extensions.Any()) 136 | .SelectMany(x => x.Value.Extensions.Select(e => (e, x.Key))) 137 | .Where(x => x.Item1.Length <= 8 && x.Item1.All(char.IsLetterOrDigit)) 138 | .GroupBy(x => x.Item1) 139 | .Select(x => x.First()) 140 | .OrderBy(x => x.Item1, StringComparer.InvariantCulture); 141 | 142 | public static IList<(string Extension, string Type)> GetMediaTypeList() 143 | { 144 | return GetMediaTypes(GetMediaTypes()).ToList(); 145 | }*/ 146 | 147 | private const char DELIM = '/'; 148 | 149 | private const int TYPE_I = 0; 150 | 151 | private const int SUBTYPE_I = 1; 152 | 153 | public static string GetTypeComponent(string mime) => mime.Split(DELIM)[TYPE_I]; 154 | 155 | public static string GetSubTypeComponent(string mime) 156 | { 157 | // NOTE: doesn't handle parameters 158 | return mime.Split(DELIM)[SUBTYPE_I]; 159 | } 160 | 161 | 162 | private const string DB_JSON_URL = "https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json"; 163 | 164 | private static Dictionary GetDatabase() 165 | { 166 | using var client = new WebClient(); 167 | 168 | string json = client.DownloadString(new Uri(DB_JSON_URL)); 169 | 170 | var mimeTypes = JsonConvert.DeserializeObject>(json)!; 171 | 172 | return mimeTypes; 173 | } 174 | 175 | public static IEnumerable GetExtensions(string mime) 176 | { 177 | mime = mime.ToLower(); 178 | 179 | return Database.Value.Where(kp => kp.Key == mime).SelectMany(kp => kp.Value.Extensions); 180 | } 181 | 182 | private static Lazy> Database { get; } = new(GetDatabase); 183 | 184 | 185 | static MediaTypes() { } 186 | } 187 | 188 | public enum MimeType 189 | { 190 | Image, 191 | Video, 192 | Audio 193 | } 194 | 195 | public class MimeTypeInfo 196 | { 197 | public MimeTypeInfo() 198 | { 199 | Extensions = new List(); 200 | } 201 | 202 | public string Source { get; set; } 203 | 204 | public List Extensions { get; } 205 | 206 | public bool Compressible { get; set; } 207 | 208 | public string Charset { get; set; } 209 | } 210 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Collections.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using SimpleCore.Diagnostics; 8 | using static SimpleCore.Internal.Common; 9 | using Map= System.Collections.Generic.Dictionary; 10 | // ReSharper disable AssignNullToNotNullAttribute 11 | 12 | // ReSharper disable PossibleMultipleEnumeration 13 | 14 | // ReSharper disable UnusedMember.Global 15 | 16 | namespace SimpleCore.Utilities 17 | { 18 | /// 19 | /// Utilities for collections () and associated types. 20 | /// 21 | public static class Collections 22 | { 23 | /// 24 | /// Determines whether ends with . 25 | /// 26 | /// type 27 | /// Larger 28 | /// Smaller 29 | /// true if ends with ; false otherwise 30 | public static bool EndsWith(this IList list, IList sequence) => 31 | list.TakeLast(sequence.Count).SequenceEqual(sequence); 32 | 33 | /// 34 | /// Determines whether starts with . 35 | /// 36 | /// type 37 | /// Larger 38 | /// Smaller 39 | /// true if starts with ; false otherwise 40 | public static bool StartsWith(this IList list, IList sequence) => 41 | list.Take(sequence.Count).SequenceEqual(sequence); 42 | 43 | /// 44 | /// Retrieves a random element from . 45 | /// 46 | /// type 47 | /// from which to retrieve a random element 48 | /// A random element 49 | public static T GetRandomElement(this IList list) 50 | { 51 | var i = RandomInstance.Next(list.Count); 52 | 53 | return list[i]; 54 | } 55 | 56 | public static object[] CastObjectArray(this Array r) 57 | { 58 | var rg = new object[r.Length]; 59 | 60 | for (int i = 0; i < r.Length; i++) { 61 | rg[i] = r.GetValue(i); 62 | } 63 | 64 | return rg; 65 | } 66 | 67 | public static IEnumerable AllIndexesOf(this List list, T search) 68 | { 69 | int minIndex = list.IndexOf(search); 70 | 71 | while (minIndex != -1) { 72 | yield return minIndex; 73 | minIndex = list.IndexOf(search, minIndex + 1); 74 | } 75 | } 76 | 77 | /// 78 | /// Replaces all occurrences of sequence within with . 79 | /// 80 | /// Original 81 | /// Sequence to search for 82 | /// Replacement sequence 83 | public static IList ReplaceAllSequences(this List rg, IList sequence, IList replace) 84 | { 85 | int i = 0; 86 | 87 | do { 88 | //i = rg.IndexOf(sequence[0], i); 89 | 90 | var b = rg.GetRange(i, sequence.Count).SequenceEqual(sequence); 91 | 92 | if (b) { 93 | rg.RemoveRange(i, sequence.Count); 94 | rg.InsertRange(i, replace); 95 | i += sequence.Count; 96 | } 97 | 98 | 99 | 100 | } while (!(++i >= rg.Count)); 101 | 102 | return rg; 103 | } 104 | 105 | /*public static bool IndexOutOfBounds(this IList rg, int idx) 106 | { 107 | //idx < io.Length && idx >= 0 108 | //(idx < rg.Count && idx >= 0) 109 | //!(idx > rg.Count || idx < 0) 110 | 111 | return idx < rg.Count && idx >= 0; 112 | }*/ 113 | 114 | public static IEnumerable Difference(this IEnumerable a, IEnumerable b) 115 | { 116 | return b.Where(c => !a.Contains(c)); 117 | } 118 | 119 | 120 | /// 121 | /// Break a list of items into chunks of a specific size 122 | /// 123 | public static IEnumerable> Chunk(this IEnumerable source, int size) 124 | { 125 | while (source.Any()) { 126 | yield return source.Take(size); 127 | source = source.Skip(size); 128 | } 129 | } 130 | 131 | public static void Replace(this List list, Predicate oldItemSelector, T newItem) 132 | { 133 | //check for different situations here and throw exception 134 | //if list contains multiple items that match the predicate 135 | //or check for nullability of list and etc ... 136 | int oldItemIndex = list.FindIndex(oldItemSelector); 137 | list[oldItemIndex] = newItem; 138 | } 139 | 140 | #region Dictionary 141 | 142 | #region Serialize 143 | 144 | /// 145 | /// Writes a to file . 146 | /// 147 | public static void WriteDictionary(IDictionary dictionary, string filename) 148 | { 149 | string[] lines = dictionary.Select(kvp => kvp.Key + DICT_DELIM + kvp.Value).ToArray(); 150 | File.WriteAllLines(filename, lines); 151 | } 152 | 153 | /// 154 | /// Reads a written by to . 155 | /// 156 | public static IDictionary ReadDictionary(string filename) 157 | { 158 | string[] lines = File.ReadAllLines(filename); 159 | 160 | var dict = lines.Select(l => l.Split(DICT_DELIM)) 161 | .ToDictionary(a => a[0], a => a[1]); 162 | 163 | return dict; 164 | } 165 | 166 | private const string DICT_DELIM = "="; 167 | 168 | #endregion 169 | 170 | public static TValue GetValueOrDefault(this IDictionary dic, 171 | TKey k, TValue d = default) 172 | { 173 | if (!dic.ContainsKey(k)) { 174 | dic.Add(k, d); 175 | 176 | // for performance 177 | return d; 178 | } 179 | 180 | return dic[k]; 181 | } 182 | 183 | public static bool TryCastDictionary(object obj, out Map buf) 184 | { 185 | bool condition = obj.GetType().GetInterface(nameof(IDictionary)) != null; 186 | 187 | if (!condition) { 188 | buf = null; 189 | return false; 190 | } 191 | 192 | var ex = ((IDictionary) obj).GetEnumerator(); 193 | 194 | buf = new Map(); 195 | 196 | while (ex.MoveNext()) { 197 | buf.Add(ex.Key, ex.Value); 198 | 199 | } 200 | 201 | return true; 202 | } 203 | 204 | #endregion 205 | } 206 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Configuration/ConfigHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | // ReSharper disable UnusedMember.Global 9 | 10 | namespace SimpleCore.Utilities.Configuration 11 | { 12 | public static class ConfigHandler 13 | { 14 | /* 15 | * Handles config components (properties or fields). 16 | * 17 | * 18 | * A config component is a setting/option (i.e. field, parameter, etc). 19 | * - Its value can be stored and later retrieved from a config file. 20 | * - Its value can also be specified through the command line. 21 | * 22 | * 23 | * mname - Member name 24 | * id - Map name (Id) 25 | */ 26 | 27 | 28 | 29 | public static void ReadFromFile(IConfig obj) 30 | { 31 | 32 | // create cfg with default options if it doesn't exist 33 | if (!File.Exists(obj.ConfigFile)) { 34 | 35 | var f = File.Create(obj.ConfigFile); 36 | f.Close(); 37 | } 38 | 39 | var cfg = Collections.ReadDictionary(obj.ConfigFile); 40 | 41 | var tuples = obj.GetType().GetAnnotated(); 42 | 43 | foreach (var (_, member) in tuples) { 44 | string memberName = member.Name; 45 | 46 | var (attr, field) = GetField(obj, memberName); 47 | 48 | var defaultValue = (object) attr.DefaultValue; 49 | bool setDefaultIfNull = attr.SetDefaultIfNull; 50 | string name = attr.Id; 51 | 52 | 53 | var v = ReadMapValue(cfg, name, setDefaultIfNull, defaultValue); 54 | //Debug.WriteLine($"{v} -> {name} {field.Name}"); 55 | string? valStr = v.ToString(); 56 | 57 | var fi = member.GetBackingField(); 58 | 59 | var val = ParseValue(valStr, fi.FieldType); 60 | 61 | fi.SetValue(obj, val); 62 | } 63 | 64 | 65 | Collections.WriteDictionary(ConvertToMap(obj), obj.ConfigFile); 66 | 67 | } 68 | 69 | /// 70 | /// Read config from command line arguments 71 | /// 72 | public static void ReadFromArguments(IConfig cfg, string[] args) 73 | { 74 | //string[] args = cfg.CliArguments; 75 | 76 | if (!args.Any()) { 77 | return; 78 | } 79 | 80 | var argQueue = new Queue(args); 81 | 82 | using var argEnumerator = argQueue.GetEnumerator(); 83 | 84 | while (argEnumerator.MoveNext()) { 85 | string parameterName = argEnumerator.Current; 86 | 87 | var parameterName1 = argEnumerator.Current; 88 | 89 | var members = GetMembers(cfg); 90 | 91 | // Corresponding component 92 | var component = members.FirstOrDefault(y => y.Attribute.ParameterName == parameterName1); 93 | 94 | if (component == default) 95 | { } 96 | else { 97 | argEnumerator.MoveNext(); 98 | 99 | string argValueRaw = argEnumerator.Current; 100 | 101 | var field = component.Member.GetBackingField(); 102 | 103 | var value = ParseValue(argValueRaw, field.FieldType); 104 | Debug.WriteLine($"{field.Name} -> {value}"); 105 | field.SetValue(cfg, value); 106 | } 107 | 108 | } 109 | } 110 | 111 | public static void Reset(IConfig obj) 112 | { 113 | var tuples = GetFields(obj); 114 | 115 | foreach (var (attr, field) in tuples) { 116 | var dv = attr.DefaultValue; 117 | field.SetValue(obj, dv); 118 | 119 | //Debug.WriteLine($"Reset {dv} -> {field.Name}"); 120 | } 121 | } 122 | 123 | 124 | public static IDictionary ConvertToMap(IConfig obj) 125 | { 126 | var cfgFields = GetFields(obj); 127 | 128 | var keyValuePairs = cfgFields.Select(f => 129 | new KeyValuePair( 130 | f.Attribute.Id, f.Field.GetValue(obj).ToString())); 131 | 132 | return new Dictionary(keyValuePairs); 133 | } 134 | 135 | 136 | private static T ReadMapValue(IDictionary cfg, string id, 137 | bool setDefaultIfNull = false, 138 | T defaultValue = default) 139 | { 140 | 141 | if (!cfg.ContainsKey(id)) { 142 | cfg.Add(id, String.Empty); 143 | } 144 | 145 | string rawValue = cfg[id]; 146 | 147 | if (setDefaultIfNull && String.IsNullOrWhiteSpace(rawValue)) { 148 | string valStr = defaultValue.ToString(); 149 | 150 | if (!cfg.ContainsKey(id)) { 151 | cfg.Add(id, valStr); 152 | } 153 | else { 154 | cfg[id] = valStr; 155 | } 156 | 157 | rawValue = ReadMapValue(cfg, id); 158 | } 159 | 160 | var parse = (T) ParseValue(rawValue, typeof(T)); 161 | return parse; 162 | } 163 | 164 | #region 165 | 166 | private static object ParseValue(string rawValue, Type t) 167 | { 168 | if (t.IsEnum) { 169 | Enum.TryParse(t, rawValue, out var e); 170 | return e; 171 | } 172 | 173 | if (t == typeof(bool)) { 174 | Boolean.TryParse(rawValue, out bool b); 175 | return b; 176 | } 177 | 178 | if (t == typeof(int)) { 179 | int.TryParse(rawValue, out int b); 180 | return b; 181 | } 182 | 183 | return rawValue; 184 | } 185 | 186 | public static FieldInfo GetResolvedField(this Type t, string fname) 187 | { 188 | var member = t.GetMember(fname, ALL_FLAGS).First(); 189 | 190 | 191 | var field = member.MemberType == MemberTypes.Property 192 | ? t.GetResolvedField(fname) 193 | : member as FieldInfo; 194 | 195 | return field; 196 | } 197 | 198 | public static FieldInfo GetBackingField(this MemberInfo m) 199 | { 200 | var fv = m.DeclaringType.GetResolvedField(m.Name); 201 | 202 | return fv; 203 | } 204 | 205 | /// 206 | /// and 207 | /// 208 | public const BindingFlags ALL_FLAGS = ALL_INSTANCE_FLAGS | BindingFlags.Static; 209 | 210 | /// 211 | /// , , 212 | /// and 213 | /// 214 | public const BindingFlags ALL_INSTANCE_FLAGS = 215 | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; 216 | 217 | public static (TAttribute Attribute, MemberInfo Member)[] GetAnnotated(this Type t) 218 | where TAttribute : Attribute 219 | { 220 | return (from member in t.GetMembers(ALL_FLAGS) 221 | where Attribute.IsDefined(member, typeof(TAttribute)) 222 | select (member.GetCustomAttribute(), member)).ToArray(); 223 | } 224 | 225 | /// 226 | /// Get all members annotated with in . 227 | /// 228 | public static (TAttribute Attribute, MemberInfo Member)[] GetMembers(object obj) 229 | where TAttribute : Attribute 230 | { 231 | var tuples = obj.GetType().GetAnnotated(); 232 | 233 | return tuples.Select(y => (y.Attribute, y.Member)).ToArray(); 234 | } 235 | 236 | /// 237 | /// Get all fields annotated with in . 238 | /// 239 | public static (TAttribute Attribute, FieldInfo Field)[] GetFields(object obj) 240 | where TAttribute : Attribute 241 | { 242 | var tuples = GetMembers(obj); 243 | 244 | return tuples.Select(y => (y.Attribute, y.Member.GetBackingField())).ToArray(); 245 | } 246 | 247 | /// 248 | /// Get field of name annotated with in 249 | /// . 250 | /// 251 | public static (T Attribute, FieldInfo Field) GetField(object obj, string mname) where T : Attribute 252 | { 253 | var t = obj.GetType(); 254 | var field = t.GetResolvedField(mname); 255 | 256 | var attr = field.GetCustomAttribute(); 257 | 258 | return (attr, field); 259 | } 260 | 261 | #endregion 262 | } 263 | } -------------------------------------------------------------------------------- /SimpleCore.Cli/NConsoleProgress.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | // ReSharper disable UnusedMember.Global 6 | #pragma warning disable CA1416, CA2211 7 | namespace SimpleCore.Cli 8 | { 9 | public static class NConsoleProgress 10 | { 11 | /* 12 | * https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json 13 | * 14 | * https://jsbin.com/tofehujixe/1/edit?js,output 15 | * https://www.npmjs.com/package/cli-spinners 16 | * https://www.fileformat.info/info/unicode/block/braille_patterns/images.htm 17 | */ 18 | 19 | #region Spinners 20 | 21 | public static string[] Dots = 22 | { 23 | "⠋", 24 | "⠙", 25 | "⠹", 26 | "⠸", 27 | "⠼", 28 | "⠴", 29 | "⠦", 30 | "⠧", 31 | "⠇", 32 | "⠏" 33 | }; 34 | 35 | public static string[] Dots2 = 36 | { 37 | "⣾", 38 | "⣽", 39 | "⣻", 40 | "⢿", 41 | "⡿", 42 | "⣟", 43 | "⣯", 44 | "⣷" 45 | }; 46 | 47 | public static string[] Dots3 = 48 | { 49 | "⠋", 50 | "⠙", 51 | "⠚", 52 | "⠞", 53 | "⠖", 54 | "⠦", 55 | "⠴", 56 | "⠲", 57 | "⠳", 58 | "⠓" 59 | }; 60 | 61 | public static string[] Dots4 = 62 | { 63 | "⠄", 64 | "⠆", 65 | "⠇", 66 | "⠋", 67 | "⠙", 68 | "⠸", 69 | "⠰", 70 | "⠠", 71 | "⠰", 72 | "⠸", 73 | "⠙", 74 | "⠋", 75 | "⠇", 76 | "⠆" 77 | }; 78 | 79 | public static string[] Dots5 = 80 | { 81 | "⠋", 82 | "⠙", 83 | "⠚", 84 | "⠒", 85 | "⠂", 86 | "⠂", 87 | "⠒", 88 | "⠲", 89 | "⠴", 90 | "⠦", 91 | "⠖", 92 | "⠒", 93 | "⠐", 94 | "⠐", 95 | "⠒", 96 | "⠓", 97 | "⠋" 98 | }; 99 | 100 | public static string[] Dots8Bit = 101 | { 102 | "⠀", 103 | "⠁", 104 | "⠂", 105 | "⠃", 106 | "⠄", 107 | "⠅", 108 | "⠆", 109 | "⠇", 110 | "⡀", 111 | "⡁", 112 | "⡂", 113 | "⡃", 114 | "⡄", 115 | "⡅", 116 | "⡆", 117 | "⡇", 118 | "⠈", 119 | "⠉", 120 | "⠊", 121 | "⠋", 122 | "⠌", 123 | "⠍", 124 | "⠎", 125 | "⠏", 126 | "⡈", 127 | "⡉", 128 | "⡊", 129 | "⡋", 130 | "⡌", 131 | "⡍", 132 | "⡎", 133 | "⡏", 134 | "⠐", 135 | "⠑", 136 | "⠒", 137 | "⠓", 138 | "⠔", 139 | "⠕", 140 | "⠖", 141 | "⠗", 142 | "⡐", 143 | "⡑", 144 | "⡒", 145 | "⡓", 146 | "⡔", 147 | "⡕", 148 | "⡖", 149 | "⡗", 150 | "⠘", 151 | "⠙", 152 | "⠚", 153 | "⠛", 154 | "⠜", 155 | "⠝", 156 | "⠞", 157 | "⠟", 158 | "⡘", 159 | "⡙", 160 | "⡚", 161 | "⡛", 162 | "⡜", 163 | "⡝", 164 | "⡞", 165 | "⡟", 166 | "⠠", 167 | "⠡", 168 | "⠢", 169 | "⠣", 170 | "⠤", 171 | "⠥", 172 | "⠦", 173 | "⠧", 174 | "⡠", 175 | "⡡", 176 | "⡢", 177 | "⡣", 178 | "⡤", 179 | "⡥", 180 | "⡦", 181 | "⡧", 182 | "⠨", 183 | "⠩", 184 | "⠪", 185 | "⠫", 186 | "⠬", 187 | "⠭", 188 | "⠮", 189 | "⠯", 190 | "⡨", 191 | "⡩", 192 | "⡪", 193 | "⡫", 194 | "⡬", 195 | "⡭", 196 | "⡮", 197 | "⡯", 198 | "⠰", 199 | "⠱", 200 | "⠲", 201 | "⠳", 202 | "⠴", 203 | "⠵", 204 | "⠶", 205 | "⠷", 206 | "⡰", 207 | "⡱", 208 | "⡲", 209 | "⡳", 210 | "⡴", 211 | "⡵", 212 | "⡶", 213 | "⡷", 214 | "⠸", 215 | "⠹", 216 | "⠺", 217 | "⠻", 218 | "⠼", 219 | "⠽", 220 | "⠾", 221 | "⠿", 222 | "⡸", 223 | "⡹", 224 | "⡺", 225 | "⡻", 226 | "⡼", 227 | "⡽", 228 | "⡾", 229 | "⡿", 230 | "⢀", 231 | "⢁", 232 | "⢂", 233 | "⢃", 234 | "⢄", 235 | "⢅", 236 | "⢆", 237 | "⢇", 238 | "⣀", 239 | "⣁", 240 | "⣂", 241 | "⣃", 242 | "⣄", 243 | "⣅", 244 | "⣆", 245 | "⣇", 246 | "⢈", 247 | "⢉", 248 | "⢊", 249 | "⢋", 250 | "⢌", 251 | "⢍", 252 | "⢎", 253 | "⢏", 254 | "⣈", 255 | "⣉", 256 | "⣊", 257 | "⣋", 258 | "⣌", 259 | "⣍", 260 | "⣎", 261 | "⣏", 262 | "⢐", 263 | "⢑", 264 | "⢒", 265 | "⢓", 266 | "⢔", 267 | "⢕", 268 | "⢖", 269 | "⢗", 270 | "⣐", 271 | "⣑", 272 | "⣒", 273 | "⣓", 274 | "⣔", 275 | "⣕", 276 | "⣖", 277 | "⣗", 278 | "⢘", 279 | "⢙", 280 | "⢚", 281 | "⢛", 282 | "⢜", 283 | "⢝", 284 | "⢞", 285 | "⢟", 286 | "⣘", 287 | "⣙", 288 | "⣚", 289 | "⣛", 290 | "⣜", 291 | "⣝", 292 | "⣞", 293 | "⣟", 294 | "⢠", 295 | "⢡", 296 | "⢢", 297 | "⢣", 298 | "⢤", 299 | "⢥", 300 | "⢦", 301 | "⢧", 302 | "⣠", 303 | "⣡", 304 | "⣢", 305 | "⣣", 306 | "⣤", 307 | "⣥", 308 | "⣦", 309 | "⣧", 310 | "⢨", 311 | "⢩", 312 | "⢪", 313 | "⢫", 314 | "⢬", 315 | "⢭", 316 | "⢮", 317 | "⢯", 318 | "⣨", 319 | "⣩", 320 | "⣪", 321 | "⣫", 322 | "⣬", 323 | "⣭", 324 | "⣮", 325 | "⣯", 326 | "⢰", 327 | "⢱", 328 | "⢲", 329 | "⢳", 330 | "⢴", 331 | "⢵", 332 | "⢶", 333 | "⢷", 334 | "⣰", 335 | "⣱", 336 | "⣲", 337 | "⣳", 338 | "⣴", 339 | "⣵", 340 | "⣶", 341 | "⣷", 342 | "⢸", 343 | "⢹", 344 | "⢺", 345 | "⢻", 346 | "⢼", 347 | "⢽", 348 | "⢾", 349 | "⢿", 350 | "⣸", 351 | "⣹", 352 | "⣺", 353 | "⣻", 354 | "⣼", 355 | "⣽", 356 | "⣾", 357 | "⣿" 358 | }; 359 | 360 | public static string[] Dots9 = 361 | { 362 | "⢹", 363 | "⢺", 364 | "⢼", 365 | "⣸", 366 | "⣇", 367 | "⡧", 368 | "⡗", 369 | "⡏" 370 | }; 371 | 372 | public static string[] Dots10 = 373 | { 374 | "⢄", 375 | "⢂", 376 | "⢁", 377 | "⡁", 378 | "⡈", 379 | "⡐", 380 | "⡠" 381 | }; 382 | 383 | public static string[] Dots11 = 384 | { 385 | "⠁", 386 | "⠂", 387 | "⠄", 388 | "⡀", 389 | "⢀", 390 | "⠠", 391 | "⠐", 392 | "⠈" 393 | }; 394 | 395 | public static string[] Dots12 = 396 | { 397 | "⢀⠀", 398 | "⡀⠀", 399 | "⠄⠀", 400 | "⢂⠀", 401 | "⡂⠀", 402 | "⠅⠀", 403 | "⢃⠀", 404 | "⡃⠀", 405 | "⠍⠀", 406 | "⢋⠀", 407 | "⡋⠀", 408 | "⠍⠁", 409 | "⢋⠁", 410 | "⡋⠁", 411 | "⠍⠉", 412 | "⠋⠉", 413 | "⠋⠉", 414 | "⠉⠙", 415 | "⠉⠙", 416 | "⠉⠩", 417 | "⠈⢙", 418 | "⠈⡙", 419 | "⢈⠩", 420 | "⡀⢙", 421 | "⠄⡙", 422 | "⢂⠩", 423 | "⡂⢘", 424 | "⠅⡘", 425 | "⢃⠨", 426 | "⡃⢐", 427 | "⠍⡐", 428 | "⢋⠠", 429 | "⡋⢀", 430 | "⠍⡁", 431 | "⢋⠁", 432 | "⡋⠁", 433 | "⠍⠉", 434 | "⠋⠉", 435 | "⠋⠉", 436 | "⠉⠙", 437 | "⠉⠙", 438 | "⠉⠩", 439 | "⠈⢙", 440 | "⠈⡙", 441 | "⠈⠩", 442 | "⠀⢙", 443 | "⠀⡙", 444 | "⠀⠩", 445 | "⠀⢘", 446 | "⠀⡘", 447 | "⠀⠨", 448 | "⠀⢐", 449 | "⠀⡐", 450 | "⠀⠠", 451 | "⠀⢀", 452 | "⠀⡀" 453 | }; 454 | 455 | public static string[] Progress7 = 456 | { 457 | "▰▱▱▱▱▱▱", 458 | "▰▰▱▱▱▱▱", 459 | "▰▰▰▱▱▱▱", 460 | "▰▰▰▰▱▱▱", 461 | "▰▰▰▰▰▱▱", 462 | "▰▰▰▰▰▰▱", 463 | "▰▰▰▰▰▰▰", 464 | "▰▱▱▱▱▱▱" 465 | }; 466 | 467 | public static string[] Progress10 = 468 | { 469 | "▰▱▱▱▱▱▱▱▱▱", 470 | "▰▰▱▱▱▱▱▱▱▱", 471 | "▰▰▰▱▱▱▱▱▱▱", 472 | "▰▰▰▰▱▱▱▱▱▱", 473 | "▰▰▰▰▰▱▱▱▱▱", 474 | "▰▰▰▰▰▰▱▱▱▱", 475 | "▰▰▰▰▰▰▰▱▱▱", 476 | "▰▰▰▰▰▰▰▰▱▱", 477 | "▰▰▰▰▰▰▰▰▰▱", 478 | "▰▰▰▰▰▰▰▰▰▰", 479 | "▰▱▱▱▱▱▱▱▱▱" 480 | }; 481 | 482 | public static string[] Line = 483 | { 484 | "-", 485 | "\\", 486 | "|", 487 | "/" 488 | }; 489 | 490 | #endregion 491 | 492 | 493 | public static string[] Current { get; set; } = Dots2; 494 | 495 | public static TimeSpan Duration { get; set; } = TimeSpan.FromMilliseconds(80); 496 | 497 | public static void ForTask(Task t) 498 | { 499 | var cts = new CancellationTokenSource(); 500 | Queue(cts); 501 | // ReSharper disable once MethodSupportsCancellation 502 | t.Wait(); 503 | cts.Cancel(); 504 | cts.Dispose(); 505 | } 506 | 507 | public static void Queue(CancellationTokenSource cts) 508 | { 509 | // Pass the token to the cancelable operation. 510 | ThreadPool.QueueUserWorkItem(Show, cts.Token); 511 | } 512 | 513 | public static void Show(object obj) 514 | { 515 | var token = (CancellationToken) obj; 516 | 517 | var oldTitle = Console.Title; 518 | 519 | while (!token.IsCancellationRequested) { 520 | foreach (string t in Current) { 521 | Console.Title = $"{oldTitle} \r{t}"; 522 | 523 | if (token.IsCancellationRequested) { 524 | break; 525 | } 526 | 527 | Thread.Sleep(Duration); 528 | } 529 | 530 | } 531 | 532 | Console.Title = oldTitle; 533 | } 534 | } 535 | } -------------------------------------------------------------------------------- /SimpleCore.Net/Network.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Net; 4 | using System.Net.NetworkInformation; 5 | using RestSharp; 6 | using SimpleCore.Model; 7 | 8 | #pragma warning disable 8600 9 | #pragma warning disable 8604 10 | 11 | // ReSharper disable CognitiveComplexity 12 | 13 | // ReSharper disable InconsistentNaming 14 | #pragma warning disable 8618 15 | 16 | // ReSharper disable SwitchStatementHandlesSomeKnownEnumValuesWithDefault 17 | 18 | // ReSharper disable UnusedMember.Global 19 | #nullable enable 20 | 21 | namespace SimpleCore.Net 22 | { 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | /// 29 | public static class Network 30 | { 31 | private const long TimeoutMS = 3000; 32 | 33 | public static Uri GetHostUri(Uri u) 34 | { 35 | return new UriBuilder(u.Host).Uri; 36 | } 37 | 38 | public static string GetHostComponent(Uri u) 39 | { 40 | return u.GetComponents(UriComponents.NormalizedHost, UriFormat.Unescaped); 41 | } 42 | 43 | public static string StripScheme(Uri uri) 44 | { 45 | return uri.Host + uri.PathAndQuery + uri.Fragment; 46 | } 47 | 48 | public static bool IsUri(string uriName, out Uri? uriResult) 49 | { 50 | bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 51 | && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); 52 | 53 | 54 | // if (!result) { 55 | // var b = new UriBuilder(StripScheme(new Uri(uriName))) 56 | // { 57 | // Scheme = Uri.UriSchemeHttps, 58 | // Port = -1 59 | // }; 60 | // uriResult = b.Uri; 61 | // 62 | // //uriResult = new Uri(uriResult.ToString().Replace("file:", "http:")); 63 | // } 64 | 65 | 66 | return result; 67 | } 68 | 69 | public static IPGeolocation Identify(IPAddress ip) => Identify(ip.ToString()); 70 | 71 | public static IPGeolocation Identify(string hostOrIP) 72 | { 73 | var rc = new RestClient("https://freegeoip.app/{format}/{host}"); 74 | var r = new RestRequest(); 75 | 76 | r.AddUrlSegment("format", "json"); 77 | r.AddUrlSegment("host", hostOrIP); 78 | 79 | var res = rc.Execute(r, Method.GET); 80 | 81 | return res.Data; 82 | } 83 | 84 | public static IPAddress GetHostAddress(string hostOrIP) => Dns.GetHostAddresses(hostOrIP)[0]; 85 | 86 | public static string GetAddress(string u) 87 | { 88 | string s = null; 89 | 90 | if (IPAddress.TryParse(u, out var ip)) { 91 | s = ip.ToString(); 92 | } 93 | 94 | if (IsUri(u, out var ux)) { 95 | s = GetHostComponent(ux); 96 | } 97 | 98 | return GetHostAddress(s).ToString(); 99 | } 100 | 101 | 102 | public static bool IsAlive(Uri u, long ms = TimeoutMS) => 103 | IsAlive(GetAddress(u.ToString()), ms); 104 | 105 | public static bool IsAlive(string hostOrIP, long ms = TimeoutMS) 106 | { 107 | /* 108 | * This approach is about .7 sec faster than using a web request 109 | */ 110 | 111 | PingReply r = Ping(hostOrIP, ms); 112 | 113 | //return !(r.Status != IPStatus.Success || r.Status == IPStatus.TimedOut); 114 | 115 | return r.Status == IPStatus.Success; 116 | } 117 | 118 | public static PingReply Ping(Uri u, long ms = TimeoutMS) => 119 | Ping(GetAddress(u.ToString()), ms); 120 | 121 | 122 | public static PingReply Ping(string hostOrIP, long ms = TimeoutMS) 123 | { 124 | var ping = new Ping(); 125 | 126 | var task = ping.SendPingAsync(hostOrIP, (int) ms); 127 | task.Wait(); 128 | 129 | PingReply r = task.Result; 130 | 131 | return r; 132 | } 133 | 134 | /*public static bool IsAlive2(Uri u) => IsAlive2(u, Timeout); 135 | 136 | public static bool IsAlive2(Uri u, TimeSpan span) 137 | { 138 | try { 139 | var request = (HttpWebRequest) WebRequest.Create(u); 140 | 141 | request.Timeout = (int) span.TotalMilliseconds; 142 | request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector 143 | request.Method = "HEAD"; 144 | 145 | using var response = (HttpWebResponse) request.GetResponse(); 146 | return true; 147 | } 148 | catch (WebException) { 149 | return false; 150 | } 151 | }*/ 152 | 153 | public static string? GetFinalRedirect(string url) 154 | { 155 | // https://stackoverflow.com/questions/704956/getting-the-redirected-url-from-the-original-url 156 | 157 | if (String.IsNullOrWhiteSpace(url)) 158 | return url; 159 | 160 | const int MAX_REDIR = 8; 161 | 162 | int maxRedirCount = MAX_REDIR; // prevent infinite loops 163 | 164 | string? newUrl = url; 165 | 166 | do { 167 | HttpWebResponse? resp = null; 168 | 169 | try { 170 | var req = (HttpWebRequest) WebRequest.Create(url); 171 | req.Method = "HEAD"; 172 | req.AllowAutoRedirect = false; 173 | resp = (HttpWebResponse) req.GetResponse(); 174 | 175 | switch (resp.StatusCode) { 176 | case HttpStatusCode.OK: 177 | return newUrl; 178 | 179 | case HttpStatusCode.Redirect: 180 | case HttpStatusCode.MovedPermanently: 181 | case HttpStatusCode.RedirectKeepVerb: 182 | case HttpStatusCode.RedirectMethod: 183 | newUrl = resp.Headers["Location"]; 184 | 185 | if (newUrl == null) 186 | return url; 187 | 188 | if (newUrl.Contains("://", StringComparison.Ordinal)) { 189 | // Doesn't have a URL Schema, meaning it's a relative or absolute URL 190 | Uri u = new(new Uri(url), newUrl); 191 | newUrl = u.ToString(); 192 | } 193 | 194 | break; 195 | 196 | default: 197 | return newUrl; 198 | } 199 | 200 | url = newUrl; 201 | } 202 | catch (WebException) { 203 | // Return the last known good URL 204 | return newUrl; 205 | } 206 | catch (Exception) { 207 | return null; 208 | } 209 | finally { 210 | resp?.Close(); 211 | } 212 | } while (maxRedirCount-- > 0); 213 | 214 | return newUrl; 215 | } 216 | 217 | public static IRestResponse GetResponse(string url) 218 | { 219 | var client = new RestClient(); 220 | var restReq = new RestRequest(url); 221 | var restRes = client.Execute(restReq); 222 | 223 | return restRes; 224 | } 225 | 226 | public static IRestResponse? GetQueryResponse(string s) 227 | { 228 | var req = new RestRequest(s, Method.HEAD); 229 | var client = new RestClient(); 230 | 231 | //client.FollowRedirects = true; 232 | 233 | var res = client.Execute(req); 234 | 235 | if (res.StatusCode == HttpStatusCode.NotFound) { 236 | return null; 237 | } 238 | 239 | return res; 240 | } 241 | 242 | public static void DumpResponse(IRestResponse response) 243 | { 244 | var ct = new ConsoleTable("-", "Value"); 245 | 246 | ct.AddRow("Uri", response.ResponseUri); 247 | ct.AddRow("Successful", response.IsSuccessful); 248 | ct.AddRow("Status code", response.StatusCode); 249 | ct.AddRow("Error message", response.ErrorMessage); 250 | 251 | var str = ct.ToString(); 252 | 253 | Trace.WriteLine(str); 254 | } 255 | } 256 | 257 | public sealed class IPGeolocation 258 | { 259 | public string IP { get; internal set; } 260 | 261 | public string CountryCode { get; internal set; } 262 | 263 | public string CountryName { get; internal set; } 264 | 265 | public string RegionCode { get; internal set; } 266 | 267 | public string RegionName { get; internal set; } 268 | 269 | public string City { get; internal set; } 270 | 271 | public string ZipCode { get; internal set; } 272 | 273 | public string TimeZone { get; internal set; } 274 | 275 | public double Latitude { get; internal set; } 276 | 277 | public double Longitude { get; internal set; } 278 | 279 | public int MetroCode { get; internal set; } 280 | 281 | public override string ToString() 282 | { 283 | return $"{nameof(IP)}: {IP}\n" + 284 | $"{nameof(CountryCode)}: {CountryCode}\n" + 285 | $"{nameof(CountryName)}: {CountryName}\n" + 286 | $"{nameof(RegionCode)}: {RegionCode}\n" + 287 | $"{nameof(RegionName)}: {RegionName}\n" + 288 | $"{nameof(City)}: {City}\n" + 289 | $"{nameof(ZipCode)}: {ZipCode}\n" + 290 | $"{nameof(TimeZone)}: {TimeZone}\n" + 291 | $"{nameof(Latitude)}: {Latitude}\n" + 292 | $"{nameof(Longitude)}: {Longitude}\n" + 293 | $"{nameof(MetroCode)}: {MetroCode}"; 294 | } 295 | } 296 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.vspscc 94 | *.vssscc 95 | .builds 96 | *.pidb 97 | *.svclog 98 | *.scc 99 | 100 | # Chutzpah Test files 101 | _Chutzpah* 102 | 103 | # Visual C++ cache files 104 | ipch/ 105 | *.aps 106 | *.ncb 107 | *.opendb 108 | *.opensdf 109 | *.sdf 110 | *.cachefile 111 | *.VC.db 112 | *.VC.VC.opendb 113 | 114 | # Visual Studio profiler 115 | *.psess 116 | *.vsp 117 | *.vspx 118 | *.sap 119 | 120 | # Visual Studio Trace Files 121 | *.e2e 122 | 123 | # TFS 2012 Local Workspace 124 | $tf/ 125 | 126 | # Guidance Automation Toolkit 127 | *.gpState 128 | 129 | # ReSharper is a .NET coding add-in 130 | _ReSharper*/ 131 | *.[Rr]e[Ss]harper 132 | *.DotSettings.user 133 | 134 | # TeamCity is a build add-in 135 | _TeamCity* 136 | 137 | # DotCover is a Code Coverage Tool 138 | *.dotCover 139 | 140 | # AxoCover is a Code Coverage Tool 141 | .axoCover/* 142 | !.axoCover/settings.json 143 | 144 | # Coverlet is a free, cross platform Code Coverage Tool 145 | coverage*.json 146 | coverage*.xml 147 | coverage*.info 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # Fody - auto-generated XML schema 362 | FodyWeavers.xsd 363 | 364 | 365 | # Entire IDEA dir 366 | .idea/ 367 | 368 | 369 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 370 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 371 | 372 | # User-specific stuff 373 | .idea/**/workspace.xml 374 | .idea/**/tasks.xml 375 | .idea/**/usage.statistics.xml 376 | .idea/**/dictionaries 377 | .idea/**/shelf 378 | 379 | # Generated files 380 | .idea/**/contentModel.xml 381 | 382 | # Sensitive or high-churn files 383 | .idea/**/dataSources/ 384 | .idea/**/dataSources.ids 385 | .idea/**/dataSources.local.xml 386 | .idea/**/sqlDataSources.xml 387 | .idea/**/dynamic.xml 388 | .idea/**/uiDesigner.xml 389 | .idea/**/dbnavigator.xml 390 | 391 | # Gradle 392 | .idea/**/gradle.xml 393 | .idea/**/libraries 394 | 395 | # Gradle and Maven with auto-import 396 | # When using Gradle or Maven with auto-import, you should exclude module files, 397 | # since they will be recreated, and may cause churn. Uncomment if using 398 | # auto-import. 399 | # .idea/artifacts 400 | # .idea/compiler.xml 401 | # .idea/jarRepositories.xml 402 | # .idea/modules.xml 403 | # .idea/*.iml 404 | # .idea/modules 405 | # *.iml 406 | # *.ipr 407 | 408 | # CMake 409 | cmake-build-*/ 410 | 411 | # Mongo Explorer plugin 412 | .idea/**/mongoSettings.xml 413 | 414 | # File-based project format 415 | *.iws 416 | 417 | # IntelliJ 418 | out/ 419 | 420 | # mpeltonen/sbt-idea plugin 421 | .idea_modules/ 422 | 423 | # JIRA plugin 424 | atlassian-ide-plugin.xml 425 | 426 | # Cursive Clojure plugin 427 | .idea/replstate.xml 428 | 429 | # Crashlytics plugin (for Android Studio and IntelliJ) 430 | com_crashlytics_export_strings.xml 431 | crashlytics.properties 432 | crashlytics-build.properties 433 | fabric.properties 434 | 435 | # Editor-based Rest Client 436 | .idea/httpRequests 437 | 438 | # Android studio 3.1+ serialized cache file 439 | .idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /SimpleCore/Utilities/Pastel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.ObjectModel; 5 | using System.Drawing; 6 | using System.Globalization; 7 | using System.Linq; 8 | using System.Runtime.InteropServices; 9 | using System.Text; 10 | using System.Text.RegularExpressions; 11 | 12 | // ReSharper disable InconsistentNaming 13 | 14 | #nullable enable 15 | // ReSharper disable UnusedMember.Global 16 | // ReSharper disable ParameterTypeCanBeEnumerable.Global 17 | // ReSharper disable StringCompareToIsCultureSpecific 18 | 19 | namespace SimpleCore.Utilities 20 | { 21 | public static class Pastel 22 | { 23 | //https://github.com/silkfire/Pastel/blob/master/src/ConsoleExtensions.cs 24 | 25 | private const int STD_OUTPUT_HANDLE = -11; 26 | 27 | private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; 28 | 29 | private const string K32 = "kernel32.dll"; 30 | 31 | private const string FORMAT_STRING_START = "\u001b[{0};2;"; 32 | private const string FORMAT_STRING_COLOR = "{1};{2};{3}m"; 33 | private const string FORMAT_STRING_CONTENT = "{4}"; 34 | private const string FORMAT_STRING_END = "\u001b[0m"; 35 | 36 | 37 | private static bool _enabled; 38 | 39 | private static readonly string FormatStringFull = 40 | $"{FORMAT_STRING_START}{FORMAT_STRING_COLOR}{FORMAT_STRING_CONTENT}{FORMAT_STRING_END}"; 41 | 42 | 43 | private static readonly ReadOnlyDictionary PlaneFormatModifiers = 44 | new(new Dictionary 45 | { 46 | [ColorPlane.Foreground] = "38", 47 | [ColorPlane.Background] = "48" 48 | }); 49 | 50 | 51 | private static readonly Regex CloseNestedPastelStringRegex1 = 52 | new($"({FORMAT_STRING_END.Replace("[", @"\[")})+", RegexOptions.Compiled); 53 | 54 | private static readonly Regex CloseNestedPastelStringRegex2 = new( 55 | $"(?().ToArray())})(?:{String.Format(FORMAT_STRING_START.Replace("[", @"\["), $"(?:{PlaneFormatModifiers[ColorPlane.Foreground]}|{PlaneFormatModifiers[ColorPlane.Background]})")})" 56 | , 57 | RegexOptions.Compiled); 58 | 59 | private static readonly ReadOnlyDictionary CloseNestedPastelStringRegex3 = 60 | new(new Dictionary 61 | { 62 | [ColorPlane.Foreground] = 63 | new( 64 | $"(?:{FORMAT_STRING_END.Replace("[", @"\[")})(?!{String.Format(FORMAT_STRING_START.Replace("[", @"\["), PlaneFormatModifiers[ColorPlane.Foreground])})(?!$)" 65 | , 66 | RegexOptions.Compiled), 67 | [ColorPlane.Background] = 68 | new( 69 | $"(?:{FORMAT_STRING_END.Replace("[", @"\[")})(?!{String.Format(FORMAT_STRING_START.Replace("[", @"\["), PlaneFormatModifiers[ColorPlane.Background])})(?!$)" 70 | , 71 | RegexOptions.Compiled) 72 | }); 73 | 74 | 75 | private static readonly Func ParseHexColor = 76 | hc => Int32.Parse(hc.Replace("#", ""), NumberStyles.HexNumber); 77 | 78 | private static readonly Func ColorFormat = (i, c, p) => 79 | String.Format(FormatStringFull, PlaneFormatModifiers[p], c.R, c.G, c.B, CloseNestedPastelStrings(i, c, p)); 80 | 81 | private static readonly Func ColorHexFormat = 82 | (i, c, p) => ColorFormat(i, Color.FromArgb(ParseHexColor(c)), p); 83 | 84 | private static readonly ColorFormatFunction NoColorOutputFormat = (i, _) => i; 85 | 86 | private static readonly HexColorFormatFunction NoHexColorOutputFormat = (i, _) => i; 87 | 88 | private static readonly ColorFormatFunction 89 | ForegroundColorFormat = (i, c) => ColorFormat(i, c, ColorPlane.Foreground); 90 | 91 | private static readonly HexColorFormatFunction ForegroundHexColorFormat = 92 | (i, c) => ColorHexFormat(i, c, ColorPlane.Foreground); 93 | 94 | private static readonly ColorFormatFunction 95 | BackgroundColorFormat = (i, c) => ColorFormat(i, c, ColorPlane.Background); 96 | 97 | private static readonly HexColorFormatFunction BackgroundHexColorFormat = 98 | (i, c) => ColorHexFormat(i, c, ColorPlane.Background); 99 | 100 | 101 | private static readonly ReadOnlyDictionary> 102 | ColorFormatFunctions 103 | = new( 104 | new Dictionary> 105 | { 106 | [false] = new( 107 | new Dictionary 108 | { 109 | [ColorPlane.Foreground] = NoColorOutputFormat, 110 | [ColorPlane.Background] = NoColorOutputFormat 111 | }), 112 | [true] = new( 113 | new Dictionary 114 | { 115 | [ColorPlane.Foreground] = ForegroundColorFormat, 116 | [ColorPlane.Background] = BackgroundColorFormat 117 | }) 118 | }); 119 | 120 | private static readonly ReadOnlyDictionary> 121 | HexColorFormatFunctions = new( 122 | new Dictionary> 123 | { 124 | [false] = new( 125 | new Dictionary 126 | { 127 | [ColorPlane.Foreground] = NoHexColorOutputFormat, 128 | [ColorPlane.Background] = NoHexColorOutputFormat 129 | }), 130 | [true] = new( 131 | new Dictionary 132 | { 133 | [ColorPlane.Foreground] = ForegroundHexColorFormat, 134 | [ColorPlane.Background] = BackgroundHexColorFormat 135 | }) 136 | }); 137 | 138 | 139 | static Pastel() 140 | { 141 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { 142 | var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE); 143 | 144 | bool enable = GetConsoleMode(iStdOut, out uint outConsoleMode) 145 | && SetConsoleMode(iStdOut, outConsoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); 146 | } 147 | 148 | 149 | if (Environment.GetEnvironmentVariable("NO_COLOR") == null) { 150 | Enable(); 151 | } 152 | else { 153 | Disable(); 154 | } 155 | } 156 | 157 | 158 | [DllImport(K32)] 159 | private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); 160 | 161 | [DllImport(K32)] 162 | private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); 163 | 164 | [DllImport(K32, SetLastError = true)] 165 | private static extern IntPtr GetStdHandle(int nStdHandle); 166 | 167 | 168 | /// 169 | /// Enables any future console color output produced by Pastel. 170 | /// 171 | public static void Enable() 172 | { 173 | _enabled = true; 174 | } 175 | 176 | /// 177 | /// Disables any future console color output produced by Pastel. 178 | /// 179 | public static void Disable() 180 | { 181 | _enabled = false; 182 | } 183 | 184 | 185 | private static string CloseNestedPastelStrings(string input, Color color, ColorPlane colorPlane) 186 | { 187 | string closedString = CloseNestedPastelStringRegex1.Replace(input, FORMAT_STRING_END); 188 | 189 | closedString = CloseNestedPastelStringRegex2.Replace(closedString, $"{FORMAT_STRING_END}$0"); 190 | 191 | closedString = CloseNestedPastelStringRegex3[colorPlane].Replace(closedString, 192 | $"$0{String.Format($"{FORMAT_STRING_START}{FORMAT_STRING_COLOR}", PlaneFormatModifiers[colorPlane], color.R, color.G, color.B)}"); 193 | 194 | return closedString; 195 | } 196 | 197 | private delegate string ColorFormatFunction(string input, Color color); 198 | 199 | private delegate string HexColorFormatFunction(string input, string hexColor); 200 | 201 | private enum ColorPlane : byte 202 | { 203 | Foreground, 204 | Background 205 | } 206 | 207 | /// 208 | /// Returns a string wrapped in an ANSI foreground color code using the specified color. 209 | /// 210 | /// The string to color. 211 | /// The color to use on the specified string. 212 | public static string AddColor(this string input, Color color) 213 | { 214 | return ColorFormatFunctions[_enabled][ColorPlane.Foreground](input, color); 215 | } 216 | 217 | /// 218 | /// Returns a string wrapped in an ANSI foreground color code using the specified color. 219 | /// 220 | /// The string to color. 221 | /// The color to use on the specified string. 222 | /// Supported format: [#]RRGGBB. 223 | /// 224 | public static string AddColor(this string input, string hexColor) 225 | { 226 | return HexColorFormatFunctions[_enabled][ColorPlane.Foreground](input, hexColor); 227 | } 228 | 229 | 230 | /// 231 | /// Returns a string wrapped in an ANSI background color code using the specified color. 232 | /// 233 | /// The string to color. 234 | /// The color to use on the specified string. 235 | public static string AddColorBG(this string input, Color color) 236 | { 237 | return ColorFormatFunctions[_enabled][ColorPlane.Background](input, color); 238 | } 239 | 240 | /// 241 | /// Returns a string wrapped in an ANSI background color code using the specified color. 242 | /// 243 | /// The string to color. 244 | /// The color to use on the specified string. 245 | /// Supported format: [#]RRGGBB. 246 | /// 247 | public static string AddColorBG(this string input, string hexColor) 248 | { 249 | return HexColorFormatFunctions[_enabled][ColorPlane.Background](input, hexColor); 250 | } 251 | 252 | 253 | public static string AddUnderline(this string s) 254 | { 255 | //\x1b[36mTEST\x1b[0m 256 | 257 | s = $"\x1b[4m{s}{ANSI_RESET}"; 258 | return s; 259 | } 260 | 261 | private const string ANSI_RESET = "\u001b[0m"; 262 | } 263 | } -------------------------------------------------------------------------------- /SimpleCore/Model/ConsoleTable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.RegularExpressions; 7 | 8 | // ReSharper disable UnusedMember.Global 9 | 10 | namespace SimpleCore.Model 11 | { 12 | // https://github.com/khalidabuhakmeh/ConsoleTables 13 | 14 | /// 15 | /// From ConsoleTable repo 16 | /// 17 | public class ConsoleTable 18 | { 19 | public IList Columns { get; set; } 20 | public IList Rows { get; protected set; } 21 | 22 | public ConsoleTableOptions Options { get; protected set; } 23 | public Type[] ColumnTypes { get; private set; } 24 | 25 | public static HashSet NumericTypes = new() 26 | { 27 | typeof(int), typeof(double), typeof(decimal), 28 | typeof(long), typeof(short), typeof(sbyte), 29 | typeof(byte), typeof(ulong), typeof(ushort), 30 | typeof(uint), typeof(float) 31 | }; 32 | 33 | public ConsoleTable(params string[] columns) 34 | : this(new ConsoleTableOptions {Columns = new List(columns)}) { } 35 | 36 | public ConsoleTable(ConsoleTableOptions options) 37 | { 38 | Options = options ?? throw new ArgumentNullException("options"); 39 | Rows = new List(); 40 | Columns = new List(options.Columns); 41 | } 42 | 43 | public ConsoleTable AddColumn(IEnumerable names) 44 | { 45 | foreach (var name in names) 46 | Columns.Add(name); 47 | return this; 48 | } 49 | 50 | public ConsoleTable AddRow(params object[] values) 51 | { 52 | if (values == null) 53 | throw new ArgumentNullException(nameof(values)); 54 | 55 | if (!Columns.Any()) 56 | throw new Exception("Please set the columns first"); 57 | 58 | if (Columns.Count != values.Length) 59 | throw new Exception( 60 | $"The number columns in the row ({Columns.Count}) does not match the values ({values.Length})"); 61 | 62 | Rows.Add(values); 63 | return this; 64 | } 65 | 66 | public ConsoleTable Configure(Action action) 67 | { 68 | action(Options); 69 | return this; 70 | } 71 | 72 | public static ConsoleTable From(IEnumerable values) 73 | { 74 | var table = new ConsoleTable 75 | { 76 | ColumnTypes = GetColumnsType().ToArray() 77 | }; 78 | 79 | var columns = GetColumns(); 80 | 81 | table.AddColumn(columns); 82 | 83 | foreach ( 84 | var propertyValues 85 | in values.Select(value => columns.Select(column => GetColumnValue(value, column))) 86 | ) table.AddRow(propertyValues.ToArray()); 87 | 88 | return table; 89 | } 90 | 91 | public override string ToString() => ToMarkDownString(); 92 | 93 | public string ToDefaultString() 94 | { 95 | var builder = new StringBuilder(); 96 | 97 | // find the longest column by searching each row 98 | var columnLengths = ColumnLengths(); 99 | 100 | // set right alinment if is a number 101 | var columnAlignment = Enumerable.Range(0, Columns.Count) 102 | .Select(GetNumberAlignment) 103 | .ToList(); 104 | 105 | // create the string format with padding 106 | var format = Enumerable.Range(0, Columns.Count) 107 | .Select(i => " | {" + i + "," + columnAlignment[i] + columnLengths[i] + "}") 108 | .Aggregate((s, a) => s + a) + " |"; 109 | 110 | // find the longest formatted line 111 | var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0); 112 | var columnHeaders = string.Format(format, Columns.ToArray()); 113 | 114 | // longest line is greater of formatted columnHeader and longest row 115 | var longestLine = Math.Max(maxRowLength, columnHeaders.Length); 116 | 117 | // add each row 118 | var results = Rows.Select(row => string.Format(format, row)).ToList(); 119 | 120 | // create the divider 121 | var divider = " " + string.Join("", Enumerable.Repeat("-", longestLine - 1)) + " "; 122 | 123 | builder.AppendLine(divider); 124 | builder.AppendLine(columnHeaders); 125 | 126 | foreach (var row in results) { 127 | builder.AppendLine(divider); 128 | builder.AppendLine(row); 129 | } 130 | 131 | builder.AppendLine(divider); 132 | 133 | if (Options.EnableCount) { 134 | builder.AppendLine(""); 135 | builder.AppendFormat(" Count: {0}", Rows.Count); 136 | } 137 | 138 | return builder.ToString(); 139 | } 140 | 141 | public string ToMarkDownString() 142 | { 143 | return ToMarkDownString('|'); 144 | } 145 | 146 | private string ToMarkDownString(char delimiter) 147 | { 148 | var builder = new StringBuilder(); 149 | 150 | // find the longest column by searching each row 151 | var columnLengths = ColumnLengths(); 152 | 153 | // create the string format with padding 154 | var format = Format(columnLengths, delimiter); 155 | 156 | // find the longest formatted line 157 | var columnHeaders = string.Format(format, Columns.ToArray()); 158 | 159 | // add each row 160 | var results = Rows.Select(row => string.Format(format, row)).ToList(); 161 | 162 | // create the divider 163 | var divider = Regex.Replace(columnHeaders, @"[^|]", "-"); 164 | 165 | builder.AppendLine(columnHeaders); 166 | builder.AppendLine(divider); 167 | results.ForEach(row => builder.AppendLine(row)); 168 | 169 | return builder.ToString(); 170 | } 171 | 172 | public string ToMinimalString() 173 | { 174 | return ToMarkDownString(char.MinValue); 175 | } 176 | 177 | public string ToStringAlternative() 178 | { 179 | var builder = new StringBuilder(); 180 | 181 | // find the longest column by searching each row 182 | var columnLengths = ColumnLengths(); 183 | 184 | // create the string format with padding 185 | var format = Format(columnLengths); 186 | 187 | // find the longest formatted line 188 | var columnHeaders = string.Format(format, Columns.ToArray()); 189 | 190 | // add each row 191 | var results = Rows.Select(row => string.Format(format, row)).ToList(); 192 | 193 | // create the divider 194 | var divider = Regex.Replace(columnHeaders, @"[^|]", "-"); 195 | var dividerPlus = divider.Replace("|", "+"); 196 | 197 | builder.AppendLine(dividerPlus); 198 | builder.AppendLine(columnHeaders); 199 | 200 | foreach (var row in results) { 201 | builder.AppendLine(dividerPlus); 202 | builder.AppendLine(row); 203 | } 204 | 205 | builder.AppendLine(dividerPlus); 206 | 207 | return builder.ToString(); 208 | } 209 | 210 | private string Format(List columnLengths, char delimiter = '|') 211 | { 212 | // set right alinment if is a number 213 | var columnAlignment = Enumerable.Range(0, Columns.Count) 214 | .Select(GetNumberAlignment) 215 | .ToList(); 216 | 217 | var delimiterStr = delimiter == char.MinValue ? string.Empty : delimiter.ToString(); 218 | 219 | var format = (Enumerable.Range(0, Columns.Count) 220 | .Select(i => " " + delimiterStr + " {" + i + "," + columnAlignment[i] + 221 | columnLengths[i] + "}") 222 | .Aggregate((s, a) => s + a) + " " + delimiterStr).Trim(); 223 | return format; 224 | } 225 | 226 | private string GetNumberAlignment(int i) 227 | { 228 | return Options.NumberAlignment == ConsoleTableAlignment.Right 229 | && ColumnTypes != null 230 | && NumericTypes.Contains(ColumnTypes[i]) 231 | ? "" 232 | : "-"; 233 | } 234 | 235 | private List ColumnLengths() 236 | { 237 | var columnLengths = Columns 238 | .Select((t, i) => Rows.Select(x => x[i]) 239 | .Union(new[] {Columns[i]}) 240 | .Where(x => x != null) 241 | .Select(x => x.ToString().Length).Max()) 242 | .ToList(); 243 | return columnLengths; 244 | } 245 | 246 | /* 247 | * NOTE: Markdown string is default 248 | */ 249 | 250 | public void Write(ConsoleTableFormat consoleTableFormat = ConsoleTableFormat.MarkDown) 251 | { 252 | switch (consoleTableFormat) { 253 | case ConsoleTableFormat.Default: 254 | Options.OutputTo.WriteLine(ToString()); 255 | break; 256 | case ConsoleTableFormat.MarkDown: 257 | Options.OutputTo.WriteLine(ToMarkDownString()); 258 | break; 259 | case ConsoleTableFormat.Alternative: 260 | Options.OutputTo.WriteLine(ToStringAlternative()); 261 | break; 262 | case ConsoleTableFormat.Minimal: 263 | Options.OutputTo.WriteLine(ToMinimalString()); 264 | break; 265 | default: 266 | throw new ArgumentOutOfRangeException(nameof(consoleTableFormat), consoleTableFormat, null); 267 | } 268 | } 269 | 270 | private static IEnumerable GetColumns() 271 | { 272 | return typeof(T).GetProperties().Select(x => x.Name).ToArray(); 273 | } 274 | 275 | private static object GetColumnValue(object target, string column) 276 | { 277 | return typeof(T).GetProperty(column).GetValue(target, null); 278 | } 279 | 280 | private static IEnumerable GetColumnsType() 281 | { 282 | return typeof(T).GetProperties().Select(x => x.PropertyType).ToArray(); 283 | } 284 | } 285 | 286 | public class ConsoleTableOptions 287 | { 288 | public IEnumerable Columns { get; set; } = new List(); 289 | public bool EnableCount { get; set; } = true; 290 | 291 | /// 292 | /// Enable only from a list of objects 293 | /// 294 | public ConsoleTableAlignment NumberAlignment { get; set; } = ConsoleTableAlignment.Left; 295 | 296 | /// 297 | /// The to write to. Defaults to . 298 | /// 299 | public TextWriter OutputTo { get; set; } = Console.Out; 300 | } 301 | 302 | public enum ConsoleTableFormat 303 | { 304 | Default = 0, 305 | MarkDown = 1, 306 | Alternative = 2, 307 | Minimal = 3 308 | } 309 | 310 | public enum ConsoleTableAlignment 311 | { 312 | Left, 313 | Right 314 | } 315 | } -------------------------------------------------------------------------------- /SimpleCore/Utilities/Strings.cs: -------------------------------------------------------------------------------- 1 | #nullable disable 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Drawing; 5 | using System.Globalization; 6 | using System.Linq; 7 | using System.Runtime.CompilerServices; 8 | using System.Text; 9 | using System.Text.RegularExpressions; 10 | using System.Text.Unicode; 11 | using JetBrains.Annotations; 12 | using SimpleCore.Model; 13 | using static SimpleCore.Internal.Common; 14 | using static SimpleCore.Utilities.StringConstants; 15 | 16 | // ReSharper disable UnusedMember.Local 17 | 18 | // ReSharper disable StringIndexOfIsCultureSpecific.1 19 | 20 | // ReSharper disable UnusedMember.Global 21 | 22 | 23 | namespace SimpleCore.Utilities 24 | { 25 | /// 26 | /// Utilities for strings (). 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | /// 33 | public static class Strings 34 | { 35 | public static string SelectOnlyDigits(this string s) 36 | { 37 | return s.SelectOnly(Char.IsDigit); 38 | } 39 | 40 | public static string SelectOnly(this string s, Func fn) 41 | { 42 | return s.Where(fn).Aggregate(String.Empty, (current, t) => current + t); 43 | } 44 | 45 | 46 | public static string CleanString(this string s) 47 | { 48 | //return s.Replace("\"", String.Empty); 49 | 50 | return s.Trim('\"'); 51 | } 52 | 53 | public static string Truncate(this string value) 54 | { 55 | //return value.Truncate(Console.WindowWidth - 5); 56 | return value.Truncate(100); 57 | } 58 | 59 | public static string Truncate(this string value, int maxLength) 60 | { 61 | if (String.IsNullOrEmpty(value)) 62 | { 63 | return value; 64 | } 65 | 66 | return value.Length <= maxLength ? value : value[..maxLength]; 67 | } 68 | 69 | [CanBeNull] 70 | public static string NullIfNullOrWhiteSpace([CanBeNull] string str) 71 | { 72 | return String.IsNullOrWhiteSpace(str) ? null : str; 73 | 74 | } 75 | 76 | public static bool StringWraps(string s) 77 | { 78 | /* 79 | * Assuming buffer width equals window width 80 | * 81 | * If 'Wrap text output on resize' is ticked, this is true 82 | */ 83 | 84 | return s.Length >= Console.WindowWidth; 85 | } 86 | 87 | /// Convert a word that is formatted in pascal case to have splits (by space) at each upper case letter. 88 | public static string SplitPascalCase(string convert) 89 | { 90 | return Regex.Replace(Regex.Replace(convert, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), 91 | @"(\p{Ll})(\P{Ll})", "$1 $2"); 92 | } 93 | 94 | public static string CreateRandom(int length) 95 | { 96 | return new(Enumerable.Repeat(Alphanumeric, length) 97 | .Select(s => s[RandomInstance.Next(s.Length)]) 98 | .ToArray()); 99 | } 100 | 101 | public static IEnumerable AllIndexesOf(this string str, string search) 102 | { 103 | int minIndex = str.IndexOf(search); 104 | 105 | while (minIndex != -1) 106 | { 107 | yield return minIndex; 108 | minIndex = str.IndexOf(search, minIndex + search.Length, StringComparison.Ordinal); 109 | } 110 | } 111 | 112 | public static string RemoveLastOccurrence(this string s, string s2) 113 | { 114 | return s.Remove(s.LastIndexOf(s2, StringComparison.Ordinal)); 115 | } 116 | 117 | /// 118 | /// Compute the Levenshtein distance (approximate string matching) between and 119 | /// 120 | public static int Compute(string s, string t) 121 | { 122 | int n = s.Length; 123 | int m = t.Length; 124 | int[,] d = new int[n + 1, m + 1]; 125 | 126 | // Step 1 127 | if (n == 0) 128 | return m; 129 | 130 | if (m == 0) 131 | return n; 132 | 133 | // Step 2 134 | for (int i = 0; i <= n; d[i, 0] = i++) { } 135 | 136 | for (int j = 0; j <= m; d[0, j] = j++) { } 137 | 138 | // Step 3 139 | for (int i = 1; i <= n; i++) //Step 4 140 | for (int j = 1; j <= m; j++) 141 | { 142 | // Step 5 143 | int cost = t[j - 1] == s[i - 1] ? 0 : 1; 144 | 145 | // Step 6 146 | d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); 147 | } 148 | 149 | // Step 7 150 | return d[n, m]; 151 | } 152 | 153 | #region Substring 154 | 155 | /// 156 | /// Simulates Java substring function 157 | /// 158 | public static string JSubstring(this string s, int beginIndex) 159 | { 160 | return s[beginIndex..]; 161 | } 162 | 163 | /// 164 | /// Simulates Java substring function 165 | /// 166 | public static string JSubstring(this string s, int beginIndex, int endIndex) 167 | { 168 | return s.Substring(beginIndex, endIndex - beginIndex + 1); 169 | } 170 | 171 | /// 172 | /// Simulates Java substring function 173 | /// 174 | public static string JSubstring(this string s, Range r) 175 | { 176 | return s.JSubstring(r.Start.Value, r.End.Value); 177 | } 178 | 179 | /// 180 | /// Simulates Java substring function 181 | /// 182 | public static string JSubstring(this string s, Index i) 183 | { 184 | return s.JSubstring(i.Value); 185 | } 186 | 187 | 188 | /// 189 | /// String value after [last] 190 | /// 191 | public static string SubstringAfter(this string value, string a) 192 | { 193 | int posA = value.LastIndexOf(a, StringComparison.Ordinal); 194 | 195 | if (posA == INVALID) 196 | { 197 | return String.Empty; 198 | } 199 | 200 | int adjustedPosA = posA + a.Length; 201 | return adjustedPosA >= value.Length ? String.Empty : value[adjustedPosA..]; 202 | } 203 | 204 | /// 205 | /// String value after [first] 206 | /// 207 | public static string SubstringBefore(this string value, string a) 208 | { 209 | int posA = value.IndexOf(a, StringComparison.Ordinal); 210 | return posA == INVALID ? String.Empty : value[..posA]; 211 | } 212 | 213 | /// 214 | /// String value between [first] and [last] 215 | /// 216 | public static string SubstringBetween(this string value, string a, string b) 217 | { 218 | int posA = value.IndexOf(a, StringComparison.Ordinal); 219 | int posB = value.LastIndexOf(b, StringComparison.Ordinal); 220 | 221 | if (posA == INVALID || posB == INVALID) 222 | { 223 | return String.Empty; 224 | } 225 | 226 | int adjustedPosA = posA + a.Length; 227 | return adjustedPosA >= posB ? String.Empty : value.Substring(adjustedPosA, posB - adjustedPosA); 228 | } 229 | 230 | #endregion 231 | 232 | 233 | #region View 234 | 235 | public static string Separator { get; set; } = new('-', 20); 236 | 237 | public static string Indentation { get; set; } = new(' ', 5); 238 | 239 | public static string Indent(string s) 240 | { 241 | return Indent(s, Indentation); 242 | } 243 | 244 | public static string Indent(string s, string indent) 245 | { 246 | //return s.Replace("\n", "\n" + Indent); 247 | 248 | string[] split = s.Split('\n'); 249 | 250 | string j = String.Join($"\n{indent}", split); 251 | 252 | return indent + j; 253 | } 254 | 255 | 256 | public static string ViewString(IViewable view) 257 | { 258 | var esb = new ExtendedStringBuilder(); 259 | 260 | 261 | foreach (var (key, value) in view.View) 262 | { 263 | switch (value) 264 | { 265 | case null: 266 | continue; 267 | case IViewable view2: 268 | esb.Append(ViewString(view2)); 269 | break; 270 | default: 271 | esb.Append(key, value); 272 | break; 273 | } 274 | 275 | } 276 | 277 | return esb.ToString(); 278 | } 279 | 280 | #endregion 281 | 282 | 283 | #region Hex 284 | 285 | private static HexFormatter Hex { get; } = new(); 286 | 287 | public sealed class HexFormatter : ICustomFormatter 288 | { 289 | public string Format(string fmt, object arg, IFormatProvider formatProvider) 290 | { 291 | fmt ??= FMT_P; 292 | 293 | 294 | fmt = fmt.ToUpper(CultureInfo.InvariantCulture); 295 | string hexStr; 296 | 297 | if (arg is IFormattable f) 298 | { 299 | hexStr = f.ToString(HEX_FORMAT_SPECIFIER, null); 300 | } 301 | else 302 | { 303 | throw new NotImplementedException(); 304 | } 305 | 306 | var sb = new StringBuilder(); 307 | 308 | 309 | switch (fmt) 310 | { 311 | case FMT_P: 312 | sb.Append(HEX_PREFIX); 313 | goto case FMT_X; 314 | case FMT_X: 315 | sb.Append(hexStr); 316 | break; 317 | default: 318 | return arg.ToString(); 319 | } 320 | 321 | return sb.ToString(); 322 | 323 | } 324 | 325 | public const string HEX_FORMAT_SPECIFIER = "X"; 326 | 327 | public const string HEX_PREFIX = "0x"; 328 | 329 | public const string FMT_X = "X"; 330 | public const string FMT_P = "P"; 331 | } 332 | 333 | public static string ToHexString(T t, string s = HexFormatter.FMT_P) => 334 | Hex.Format(s, t, CultureInfo.CurrentCulture); 335 | 336 | #endregion 337 | 338 | #region Join 339 | 340 | public static string FormatJoin(this IEnumerable values, string format, IFormatProvider provider = null, 341 | string delim = JOIN_COMMA) where T : IFormattable 342 | { 343 | return values.Select(v => v.ToString(format, provider)).QuickJoin(delim); 344 | } 345 | 346 | /// 347 | /// Concatenates the strings returned by 348 | /// using the specified separator between each element or member. 349 | /// 350 | /// Collection of values 351 | /// 352 | /// Function which returns a given a member of 353 | /// 354 | /// Delimiter 355 | /// Element type 356 | public static string FuncJoin(this IEnumerable values, Func toString, 357 | string delim = JOIN_COMMA) 358 | { 359 | return values.Select(toString).QuickJoin(delim); 360 | } 361 | 362 | 363 | public static string QuickJoin(this IEnumerable enumerable, string delim = JOIN_COMMA) 364 | { 365 | return String.Join(delim, enumerable); 366 | } 367 | 368 | #endregion 369 | 370 | public static string EncodingConvert(Encoding src, Encoding dest, string a) 371 | { 372 | return dest.GetString(Encoding.Convert(src, dest, src.GetBytes(a))); 373 | } 374 | public static bool IsCharInRange(short c, UnicodeRange r) => IsCharInRange((char) c, r); 375 | 376 | public static bool IsCharInRange(char c, UnicodeRange r) => c < (r.FirstCodePoint + r.Length) && c >= r.FirstCodePoint; 377 | 378 | } 379 | } -------------------------------------------------------------------------------- /SimpleCore.Cli/NConsole.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Runtime.CompilerServices; 8 | using System.Text; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using JetBrains.Annotations; 12 | using SimpleCore.Numeric; 13 | using SimpleCore.Utilities; 14 | using static SimpleCore.Internal.Common; 15 | 16 | // ReSharper disable CognitiveComplexity 17 | 18 | // ReSharper disable SwitchStatementMissingSomeEnumCasesNoDefault 19 | 20 | // ReSharper disable InvocationIsSkipped 21 | // ReSharper disable UnusedMember.Local 22 | // ReSharper disable InconsistentNaming 23 | // ReSharper disable UnusedMember.Global 24 | // ReSharper disable ParameterTypeCanBeEnumerable.Local 25 | // ReSharper disable UnusedVariable 26 | // ReSharper disable ParameterTypeCanBeEnumerable.Global 27 | 28 | #pragma warning disable 8602, CA1416, CS8604, IDE0059 29 | #nullable enable 30 | 31 | namespace SimpleCore.Cli 32 | { 33 | /// 34 | /// Extended console. 35 | /// 36 | /// 37 | /// 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | /// 45 | /// 46 | /// 47 | /// 48 | /// 49 | /// 50 | /// 51 | /// 52 | /// 53 | /// 54 | /// 55 | /// 56 | /// 57 | /// 58 | public static class NConsole 59 | { 60 | /* 61 | * https://github.com/Decimation/SimpleCore/blob/2d6009cfc498de07d5f507192c3cbe1983ff1a11/SimpleCore.Cli/NConsole.cs 62 | * https://gist.github.com/ZacharyPatten/798ed612d692a560bdd529367b6a7dbd 63 | * https://github.com/ZacharyPatten/Towel 64 | */ 65 | 66 | public static void Init() 67 | { 68 | //Console.OutputEncoding = Encoding.Unicode; 69 | //ListenThread.Start(); 70 | 71 | //ThreadPool.QueueUserWorkItem(KeyWatch); 72 | } 73 | 74 | /// 75 | /// Attempts to resize the console window 76 | /// 77 | /// true if the operation succeeded 78 | public static bool Resize(int cww, int cwh) 79 | { 80 | bool canResize = Console.LargestWindowWidth >= cww && 81 | Console.LargestWindowHeight >= cwh; 82 | 83 | if (canResize) { 84 | Console.SetWindowSize(cww, cwh); 85 | } 86 | 87 | return canResize; 88 | } 89 | 90 | public static int BufferLimit { get; set; } = Console.BufferWidth - 10; 91 | 92 | private static readonly Color ColorHeader = Color.Red; 93 | private static readonly Color ColorOptions = Color.Aquamarine; 94 | private static readonly Color ColorError = Color.Red; 95 | 96 | 97 | #region Write 98 | 99 | #region QWrite 100 | 101 | public delegate void WriteFunction(object o); 102 | 103 | public static void QWrite(object obj) => QWrite(obj, Console.WriteLine); 104 | 105 | public static void QWrite(object obj, WriteFunction c) 106 | { 107 | string? s = obj switch 108 | { 109 | object[] rg => rg.QuickJoin(), 110 | Array r => r.CastObjectArray().QuickJoin(), 111 | 112 | _ => obj.ToString() 113 | }; 114 | 115 | if (obj.GetType().IsPointer || obj is IntPtr) { 116 | s = Strings.ToHexString(obj); 117 | } 118 | 119 | 120 | else if (Collections.TryCastDictionary(obj, out var kv)) { 121 | s = kv.Select(x => $"{x.Key} = {x.Value}") 122 | .QuickJoin("\n"); 123 | } 124 | 125 | 126 | c(s); 127 | 128 | } 129 | 130 | #endregion 131 | 132 | 133 | /// 134 | /// Root write method. 135 | /// 136 | [StringFormatMethod(STRING_FORMAT_ARG)] 137 | public static void Write(bool newLine, string msg, params object[] args) 138 | { 139 | string fmt = String.Format(msg, args); 140 | 141 | if (newLine) { 142 | Console.WriteLine(fmt); 143 | } 144 | else { 145 | Console.Write(fmt); 146 | } 147 | } 148 | 149 | [StringFormatMethod(STRING_FORMAT_ARG)] 150 | public static void Write(string msg, params object[] args) => Write(true, msg, args); 151 | 152 | [StringFormatMethod(STRING_FORMAT_ARG)] 153 | public static void WriteOnCurrentLine(string msg, params object[] args) 154 | { 155 | msg = String.Format(msg, args); 156 | 157 | string clear = new('\b', msg.Length); 158 | Console.Write(clear); 159 | Write(msg); 160 | } 161 | 162 | public static void ClearCurrentConsoleLine() 163 | { 164 | int currentLineCursor = Console.CursorTop; 165 | Console.SetCursorPosition(0, Console.CursorTop); 166 | Console.Write(new string(' ', Console.WindowWidth)); 167 | Console.SetCursorPosition(0, currentLineCursor); 168 | } 169 | 170 | public static void ClearLastLine() 171 | { 172 | Console.SetCursorPosition(0, Console.CursorTop - 1); 173 | Console.Write(new string(' ', Console.BufferWidth)); 174 | Console.SetCursorPosition(0, Console.CursorTop - 1); 175 | } 176 | 177 | #endregion 178 | 179 | #region IO 180 | 181 | #region Keys 182 | 183 | /// 184 | /// Exits 185 | /// 186 | public const ConsoleKey NC_GLOBAL_EXIT_KEY = ConsoleKey.Escape; 187 | 188 | 189 | /// 190 | /// 191 | /// 192 | public const ConsoleKey NC_GLOBAL_REFRESH_KEY = ConsoleKey.F5; 193 | 194 | /// 195 | /// Return 196 | /// 197 | public const ConsoleKey NC_GLOBAL_RETURN_KEY = ConsoleKey.F1; 198 | 199 | /// 200 | /// 201 | /// 202 | public const ConsoleModifiers NC_ALT_FUNC_MODIFIER = ConsoleModifiers.Alt; 203 | 204 | /// 205 | /// 206 | /// 207 | public const ConsoleModifiers NC_CTRL_FUNC_MODIFIER = ConsoleModifiers.Control; 208 | 209 | /// 210 | /// 211 | /// 212 | public const ConsoleModifiers NC_SHIFT_FUNC_MODIFIER = ConsoleModifiers.Shift; 213 | 214 | /// 215 | /// 216 | /// 217 | public const ConsoleModifiers NC_COMBO_FUNC_MODIFIER = NC_ALT_FUNC_MODIFIER | NC_CTRL_FUNC_MODIFIER; 218 | 219 | #endregion Keys 220 | 221 | /*static void listen(Action x, Action ck) 222 | { 223 | ConsoleKeyInfo cki; 224 | 225 | do { 226 | //io 227 | Console.Clear(); 228 | x(); 229 | 230 | // Block until input is entered. 231 | while (!Console.KeyAvailable) { 232 | // HACK: hacky 233 | } 234 | 235 | // Key was read 236 | 237 | cki = Console.ReadKey(true); 238 | 239 | // Handle special keys 240 | 241 | ck(cki); 242 | } while (cki.Key != ConsoleKey.Escape); 243 | }*/ 244 | 245 | 246 | #region Display/formatting 247 | 248 | /// 249 | /// Root formatting function. 250 | /// 251 | [StringFormatMethod(STRING_FORMAT_ARG)] 252 | public static string FormatString(string delim, string s) 253 | { 254 | string[] split = s.Split(StringConstants.NativeNewLine); 255 | 256 | for (int i = 0; i < split.Length; i++) { 257 | string a = StringConstants.SPACE + split[i]; 258 | 259 | string b; 260 | 261 | if (String.IsNullOrWhiteSpace(a)) { 262 | b = String.Empty; 263 | } 264 | else { 265 | b = delim + a; 266 | } 267 | 268 | string c = b.Truncate(BufferLimit); 269 | 270 | if (c.Length < b.Length) { 271 | c += StringConstants.ELLIPSES; 272 | } 273 | 274 | split[i] = c; 275 | } 276 | 277 | return String.Join(StringConstants.NativeNewLine, split); 278 | } 279 | 280 | private static string FormatOption(NConsoleOption option, int i) 281 | { 282 | var sb = new StringBuilder(); 283 | char c = GetDisplayOptionFromIndex(i); 284 | 285 | string? name = option.Name; 286 | 287 | if (option.Color.HasValue) { 288 | name = name.AddColor(option.Color.Value); 289 | } 290 | 291 | sb.Append($"[{c}]: "); 292 | 293 | if (name != null) { 294 | sb.Append($"{name} "); 295 | } 296 | 297 | if (option.Data != null) { 298 | 299 | sb.AppendLine(); 300 | 301 | sb.Append($"{Strings.Indent(Strings.ViewString(option.Data))}"); 302 | } 303 | 304 | if (!sb.ToString().EndsWith(StringConstants.NativeNewLine)) { 305 | sb.AppendLine(); 306 | } 307 | 308 | var f = FormatString(StringConstants.ASTERISK.ToString(), sb.ToString()); 309 | 310 | //if (f.EndsWith('\n')) { 311 | // f += '\n'; 312 | //} 313 | 314 | return f; 315 | } 316 | 317 | private static char GetDisplayOptionFromIndex(int i) 318 | { 319 | if (i < MAX_OPTION_N) { 320 | return Char.Parse(i.ToString()); 321 | } 322 | 323 | int d = OPTION_LETTER_START + (i - MAX_OPTION_N); 324 | 325 | return (char) d; 326 | } 327 | 328 | private static int GetIndexFromDisplayOption(char c) 329 | { 330 | if (Char.IsNumber(c)) { 331 | return (int) Char.GetNumericValue(c); 332 | } 333 | 334 | if (Char.IsLetter(c)) { 335 | c = Char.ToUpper(c); 336 | return MAX_OPTION_N + (c - OPTION_LETTER_START); 337 | } 338 | 339 | return INVALID; 340 | } 341 | 342 | /// 343 | /// Display dialog 344 | /// 345 | private static void DisplayDialog(NConsoleDialog dialog, HashSet selectedOptions) 346 | { 347 | Console.Clear(); 348 | 349 | if (dialog.Header is { }) { 350 | Write(false, dialog.Header.AddColor(ColorHeader)); 351 | } 352 | 353 | int clamp = Math.Clamp(dialog.Options.Count, 0, MAX_DISPLAY_OPTIONS); 354 | 355 | for (int i = 0; i < clamp; i++) { 356 | var option = dialog.Options[i]; 357 | 358 | string s = FormatOption(option, i); 359 | 360 | Write(false, s); 361 | } 362 | 363 | Console.WriteLine(); 364 | 365 | if (dialog.Status != null) { 366 | Write(dialog.Status); 367 | } 368 | 369 | if (dialog.Description != null) { 370 | Console.WriteLine(); 371 | 372 | Write(dialog.Description); 373 | } 374 | 375 | // Show options 376 | if (dialog.SelectMultiple) { 377 | Console.WriteLine(); 378 | 379 | string optionsStr = $">> {selectedOptions.QuickJoin()}".AddColor(ColorOptions); 380 | 381 | Write(true, optionsStr); 382 | } 383 | 384 | if (dialog.SelectMultiple) { 385 | Console.WriteLine(); 386 | Write($"Press {NC_GLOBAL_EXIT_KEY.ToString().AddUnderline()} to save selected values."); 387 | } 388 | } 389 | 390 | #endregion 391 | 392 | 393 | /// 394 | /// Handles user input and options 395 | /// 396 | /// Returns when returns a non-null value 397 | public static HashSet ReadOptions(NConsoleDialog dialog) 398 | { 399 | var selectedOptions = new HashSet(); 400 | 401 | /* 402 | * Handle input 403 | */ 404 | 405 | ConsoleKeyInfo cki; 406 | 407 | // int prevHash = 0; 408 | // int prevCount = 0; 409 | 410 | do { 411 | DisplayDialog(dialog, selectedOptions); 412 | 413 | //Debug.WriteLine($"{hashCode}|{dialog.Options.GetHashCode()}"); 414 | 415 | // Block until input is entered. 416 | 417 | while (!Console.KeyAvailable) { 418 | 419 | // Handle signals from other threads 420 | 421 | /*int hashCode = dialog.GetHashCode(); 422 | int selectCount = selectedOptions.Count; 423 | 424 | var b1 = prevHash != hashCode || prevCount != selectCount; 425 | 426 | var b2 = Atomic.Exchange(ref Status, ConsoleStatus.Ok) == ConsoleStatus.Refresh; 427 | 428 | if (b1 || b2) { 429 | Debug.WriteLine($"Refreshing {hashCode}"); 430 | DisplayDialog(dialog, selectedOptions); 431 | prevHash = hashCode; 432 | prevCount = selectCount; 433 | }*/ 434 | 435 | if (Atomic.Exchange(ref Status, ConsoleStatus.Ok) == ConsoleStatus.Refresh) { 436 | DisplayDialog(dialog, selectedOptions); 437 | } 438 | } 439 | 440 | 441 | // Key was read 442 | 443 | cki = Console.ReadKey(true); 444 | 445 | 446 | // Handle special keys 447 | 448 | switch (cki.Key) { 449 | case NC_GLOBAL_REFRESH_KEY: 450 | Refresh(); 451 | break; 452 | 453 | case NC_GLOBAL_RETURN_KEY: 454 | //todo 455 | return new HashSet {true}; 456 | } 457 | 458 | 459 | // KeyChar can't be used as modifiers are not applicable 460 | char keyChar = (char) (int) cki.Key; 461 | 462 | Debug.WriteLine($"{cki.Key} ({keyChar}) | {cki.KeyChar}"); 463 | 464 | if (!Char.IsLetterOrDigit(keyChar)) { 465 | continue; 466 | } 467 | 468 | var modifiers = cki.Modifiers; 469 | 470 | bool altModifier = modifiers.HasFlag(NC_ALT_FUNC_MODIFIER); 471 | bool ctrlModifier = modifiers.HasFlag(NC_CTRL_FUNC_MODIFIER); 472 | bool shiftModifier = modifiers.HasFlag(NC_SHIFT_FUNC_MODIFIER); 473 | 474 | // Handle option 475 | 476 | int idx = GetIndexFromDisplayOption(keyChar); 477 | 478 | if (idx < dialog.Options.Count && idx >= 0) { 479 | var option = dialog.Options[idx]; 480 | 481 | bool useAltFunc = altModifier && option.AltFunction != null; 482 | bool useCtrlFunc = ctrlModifier && option.CtrlFunction != null; 483 | bool useShiftFunc = shiftModifier && option.ShiftFunction != null; 484 | 485 | bool useComboFunc = altModifier && ctrlModifier && option.ComboFunction != null; 486 | 487 | if (useComboFunc) { 488 | object? comboFunc = option.ComboFunction(); 489 | 490 | // 491 | } 492 | else if (useCtrlFunc) { 493 | object? ctrlFunc = option.CtrlFunction(); 494 | 495 | // 496 | } 497 | else if (useAltFunc) { 498 | object? altFunc = option.AltFunction(); 499 | 500 | // 501 | } 502 | else if (useShiftFunc) { 503 | object? shiftFunc = option.ShiftFunction(); 504 | 505 | // 506 | } 507 | else { 508 | object? funcResult = option.Function(); 509 | 510 | if (funcResult != null) { 511 | // 512 | if (dialog.SelectMultiple) { 513 | selectedOptions.Add(funcResult); 514 | } 515 | else { 516 | return new HashSet {funcResult}; 517 | } 518 | } 519 | } 520 | } 521 | } while (cki.Key != NC_GLOBAL_EXIT_KEY); 522 | 523 | return selectedOptions; 524 | } 525 | 526 | 527 | public static string ReadInput(string? prompt = null, Predicate? invalid = null, 528 | string? errPrompt = null) 529 | { 530 | invalid ??= String.IsNullOrWhiteSpace; 531 | 532 | string? input; 533 | bool isInvalid; 534 | 535 | 536 | do { 537 | //https://stackoverflow.com/questions/8946808/can-console-clear-be-used-to-only-clear-a-line-instead-of-whole-console 538 | 539 | Console.Write("\r" + new string(' ', Console.WindowWidth - 1) + "\r"); 540 | 541 | if (prompt != null) { 542 | string str = $">> {prompt}: ".AddColor(ColorOptions); 543 | 544 | Console.Write(str); 545 | } 546 | 547 | input = Console.ReadLine(); 548 | isInvalid = invalid(input); 549 | 550 | if (isInvalid) { 551 | errPrompt ??= "Invalid input"; 552 | Console.WriteLine(errPrompt.AddColor(ColorError)); 553 | Thread.Sleep(TimeSpan.FromSeconds(1)); 554 | //Console.Write(new string('\r',7)); 555 | ClearLastLine(); 556 | //Console.CursorTop--; 557 | 558 | } 559 | 560 | } while (isInvalid); 561 | 562 | 563 | return input; 564 | } 565 | 566 | 567 | [StringFormatMethod(STRING_FORMAT_ARG)] 568 | public static bool ReadConfirmation(string msg, params object[] args) 569 | { 570 | Write($"{StringConstants.ASTERISK} {String.Format(msg, args)} ({OPTION_Y}/{OPTION_N}): "); 571 | 572 | char key = Char.ToUpper(Console.ReadKey().KeyChar); 573 | 574 | Console.WriteLine(); 575 | 576 | return key switch 577 | { 578 | OPTION_N => false, 579 | OPTION_Y => true, 580 | _ => ReadConfirmation(msg, args) 581 | }; 582 | } 583 | 584 | public static void Refresh() => Atomic.Exchange(ref Status, ConsoleStatus.Refresh); 585 | 586 | public static void WaitForInput() 587 | { 588 | Console.WriteLine(); 589 | Console.WriteLine("Press any key to continue..."); 590 | Console.ReadKey(); 591 | } 592 | 593 | public static void WaitForTimeSpan(TimeSpan span) => Thread.Sleep(span); 594 | 595 | public static void WaitForSecond() => WaitForTimeSpan(TimeSpan.FromSeconds(1)); 596 | 597 | #region Status 598 | 599 | /// 600 | /// Interface status 601 | /// 602 | private static ConsoleStatus Status; 603 | 604 | private enum ConsoleStatus 605 | { 606 | /// 607 | /// Signals to reload interface 608 | /// 609 | Refresh, 610 | 611 | /// 612 | /// Signals to continue displaying current interface 613 | /// 614 | Ok 615 | } 616 | 617 | #endregion 618 | 619 | #region Options 620 | 621 | public const char OPTION_N = 'N'; 622 | 623 | public const char OPTION_Y = 'Y'; 624 | 625 | private const int MAX_OPTION_N = 10; 626 | 627 | private const char OPTION_LETTER_START = 'A'; 628 | 629 | public const int MAX_DISPLAY_OPTIONS = 36; 630 | 631 | #endregion Options 632 | 633 | #endregion IO 634 | 635 | 636 | /* 637 | * https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json 638 | * https://github.com/sindresorhus/cli-spinners 639 | * https://www.npmjs.com/package/cli-spinners 640 | */ 641 | } 642 | } -------------------------------------------------------------------------------- /SimpleCore/Numeric/Fraction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | // ReSharper disable InconsistentNaming 3 | 4 | // ReSharper disable UnusedMember.Global 5 | 6 | // ReSharper disable IdentifierTypo 7 | 8 | namespace SimpleCore.Numeric 9 | { 10 | /* Adapted from https://stackoverflow.com/questions/7564906/convert-double-to-fraction-as-string-in-c-sharp 11 | * Classes Contained: 12 | * Fraction 13 | * FractionException 14 | * 15 | * 16 | * 17 | * 18 | * Class name: Fraction 19 | * Developed by: Syed Mehroz Alam 20 | * Email: smehrozalam@yahoo.com 21 | * URL: Programming Home "http://www.geocities.com/smehrozalam/" 22 | * Version: 2.0 23 | * 24 | * What's new in version 2.0: 25 | * * Changed Numerator and Denominator from Int32(integer) to Int64(long) for increased range 26 | * * renamed ConvertToString() to (overloaded) ToString() 27 | * * added the capability of detecting/raising overflow exceptions 28 | * * Fixed the bug that very small numbers e.g. 0.00000001 could not be converted to fraction 29 | * * Other minor bugs fixed 30 | * 31 | * What's new in version 2.1 32 | * * overloaded user-defined conversions to/from Fractions 33 | * 34 | * 35 | * Properties: 36 | * Numerator: Set/Get value for Numerator 37 | * Denominator: Set/Get value for Numerator 38 | * Value: Set an integer value for the fraction 39 | * 40 | * Constructors: 41 | * no arguments: initializes fraction as 0/1 42 | * (Numerator, Denominator): initializes fraction with the given numerator and denominator values 43 | * (integer): initializes fraction with the given integer value 44 | * (long): initializes fraction with the given long value 45 | * (double): initializes fraction with the given double value 46 | * (string): initializes fraction with the given string value 47 | * the string can be an in the form of and integer, double or fraction. 48 | * e.g it can be like "123" or "123.321" or "123/456" 49 | * 50 | * Public Methods (Description is given with respective methods' definitions) 51 | * (override) string ToString(Fraction) 52 | * Fraction ToFraction(string) 53 | * Fraction ToFraction(double) 54 | * double ToDouble(Fraction) 55 | * Fraction Duplicate() 56 | * Fraction Inverse(integer) 57 | * Fraction Inverse(Fraction) 58 | * ReduceFraction(Fraction) 59 | * Equals(object) 60 | * GetHashCode() 61 | * 62 | * Private Methods (Description is given with respective methods' definitions) 63 | * Initialize(Numerator, Denominator) 64 | * Fraction Negate(Fraction) 65 | * Fraction Add(Fraction1, Fraction2) 66 | * 67 | * Overloaded Operators (overloaded for Fractions, Integers and Doubles) 68 | * Unary: - 69 | * Binary: +,-,*,/ 70 | * Relational and Logical Operators: ==,!=,<,>,<=,>= 71 | * 72 | * Overloaded user-defined conversions 73 | * Implicit: From double/long/string to Fraction 74 | * Explicit: From Fraction to double/string 75 | */ 76 | 77 | public class Fraction 78 | { 79 | /// 80 | /// Class attributes/members 81 | /// 82 | private long m_iNumerator; 83 | 84 | private long m_iDenominator; 85 | 86 | /// 87 | /// Constructors 88 | /// 89 | public Fraction() 90 | { 91 | Initialize(0, 1); 92 | } 93 | 94 | public Fraction(long iWholeNumber) 95 | { 96 | Initialize(iWholeNumber, 1); 97 | } 98 | 99 | public Fraction(double dDecimalValue) 100 | { 101 | var temp = ToFraction(dDecimalValue); 102 | Initialize(temp.Numerator, temp.Denominator); 103 | } 104 | 105 | public Fraction(string strValue) 106 | { 107 | var temp = ToFraction(strValue); 108 | Initialize(temp.Numerator, temp.Denominator); 109 | } 110 | 111 | public Fraction(long iNumerator, long iDenominator) 112 | { 113 | Initialize(iNumerator, iDenominator); 114 | } 115 | 116 | /// 117 | /// Internal function for constructors 118 | /// 119 | private void Initialize(long iNumerator, long iDenominator) 120 | { 121 | Numerator = iNumerator; 122 | Denominator = iDenominator; 123 | ReduceFraction(this); 124 | } 125 | 126 | /// 127 | /// Properties 128 | /// 129 | public long Denominator 130 | { 131 | get => m_iDenominator; 132 | set 133 | { 134 | if (value != 0) 135 | m_iDenominator = value; 136 | else 137 | throw new FractionException("Denominator cannot be assigned a ZERO Value"); 138 | } 139 | } 140 | 141 | public long Numerator 142 | { 143 | get => m_iNumerator; 144 | set => m_iNumerator = value; 145 | } 146 | 147 | public long Value 148 | { 149 | set 150 | { 151 | m_iNumerator = value; 152 | m_iDenominator = 1; 153 | } 154 | } 155 | 156 | /// 157 | /// The function returns the current Fraction object as double 158 | /// 159 | public double ToDouble() 160 | { 161 | return (double) Numerator / Denominator; 162 | } 163 | 164 | /// 165 | /// The function returns the current Fraction object as a string 166 | /// 167 | public override string ToString() 168 | { 169 | string str; 170 | 171 | if (Denominator == 1) 172 | str = Numerator.ToString(); 173 | else 174 | str = Numerator + "/" + Denominator; 175 | return str; 176 | } 177 | 178 | /// 179 | /// The function takes an string as an argument and returns its corresponding reduced fraction 180 | /// the string can be an in the form of and integer, double or fraction. 181 | /// e.g it can be like "123" or "123.321" or "123/456" 182 | /// 183 | public static Fraction ToFraction(string strValue) 184 | { 185 | int i; 186 | 187 | for (i = 0; i < strValue.Length; i++) 188 | if (strValue[i] == '/') 189 | break; 190 | 191 | if (i == strValue.Length) // if string is not in the form of a fraction 192 | // then it is double or integer 193 | return Convert.ToDouble(strValue); 194 | //return ( ToFraction( Convert.ToDouble(strValue) ) ); 195 | 196 | // else string is in the form of Numerator/Denominator 197 | long iNumerator = Convert.ToInt64(strValue[..i]); 198 | long iDenominator = Convert.ToInt64(strValue[(i + 1)..]); 199 | return new Fraction(iNumerator, iDenominator); 200 | } 201 | 202 | 203 | /// 204 | /// The function takes a floating point number as an argument 205 | /// and returns its corresponding reduced fraction 206 | /// 207 | public static Fraction ToFraction(double dValue) 208 | { 209 | try { 210 | checked { 211 | Fraction frac; 212 | 213 | if (dValue % 1 == 0) // if whole number 214 | { 215 | frac = new Fraction((long) dValue); 216 | } 217 | else { 218 | double dTemp = dValue; 219 | long iMultiple = 1; 220 | string strTemp = dValue.ToString(); 221 | 222 | while (strTemp.IndexOf("E", StringComparison.Ordinal) > 0) // if in the form like 12E-9 223 | { 224 | dTemp *= 10; 225 | iMultiple *= 10; 226 | strTemp = dTemp.ToString(); 227 | } 228 | 229 | int i = 0; 230 | 231 | while (strTemp[i] != '.') 232 | i++; 233 | int iDigitsAfterDecimal = strTemp.Length - i - 1; 234 | 235 | while (iDigitsAfterDecimal > 0) { 236 | dTemp *= 10; 237 | iMultiple *= 10; 238 | iDigitsAfterDecimal--; 239 | } 240 | 241 | frac = new Fraction((int) Math.Round(dTemp), iMultiple); 242 | } 243 | 244 | return frac; 245 | } 246 | } 247 | catch (OverflowException) { 248 | throw new FractionException("Conversion not possible due to overflow"); 249 | } 250 | catch (Exception) { 251 | throw new FractionException("Conversion not possible"); 252 | } 253 | } 254 | 255 | /// 256 | /// The function replicates current Fraction object 257 | /// 258 | public Fraction Duplicate() 259 | { 260 | var frac = new Fraction(); 261 | frac.Numerator = Numerator; 262 | frac.Denominator = Denominator; 263 | return frac; 264 | } 265 | 266 | /// 267 | /// The function returns the inverse of a Fraction object 268 | /// 269 | public static Fraction Inverse(Fraction frac1) 270 | { 271 | if (frac1.Numerator == 0) 272 | throw new FractionException("Operation not possible (Denominator cannot be assigned a ZERO Value)"); 273 | 274 | long iNumerator = frac1.Denominator; 275 | long iDenominator = frac1.Numerator; 276 | return new Fraction(iNumerator, iDenominator); 277 | } 278 | 279 | 280 | #region Operators 281 | 282 | /// 283 | /// Operators for the Fraction object 284 | /// includes -(unary), and binary operators such as +,-,*,/ 285 | /// also includes relational and logical operators such as ==,!=,<,>,<=,>= 286 | /// 287 | public static Fraction operator -(Fraction frac1) => Negate(frac1); 288 | 289 | public static Fraction operator +(Fraction frac1, Fraction frac2) => Add(frac1, frac2); 290 | 291 | public static Fraction operator +(int iNo, Fraction frac1) => Add(frac1, new Fraction(iNo)); 292 | 293 | public static Fraction operator +(Fraction frac1, int iNo) => Add(frac1, new Fraction(iNo)); 294 | 295 | public static Fraction operator +(double dbl, Fraction frac1) => Add(frac1, ToFraction(dbl)); 296 | 297 | public static Fraction operator +(Fraction frac1, double dbl) => Add(frac1, ToFraction(dbl)); 298 | 299 | public static Fraction operator -(Fraction frac1, Fraction frac2) => Add(frac1, -frac2); 300 | 301 | public static Fraction operator -(int iNo, Fraction frac1) => Add(-frac1, new Fraction(iNo)); 302 | 303 | public static Fraction operator -(Fraction frac1, int iNo) 304 | { 305 | return Add(frac1, -new Fraction(iNo)); 306 | } 307 | 308 | public static Fraction operator -(double dbl, Fraction frac1) 309 | { 310 | return Add(-frac1, ToFraction(dbl)); 311 | } 312 | 313 | public static Fraction operator -(Fraction frac1, double dbl) 314 | { 315 | return Add(frac1, -ToFraction(dbl)); 316 | } 317 | 318 | public static Fraction operator *(Fraction frac1, Fraction frac2) 319 | { 320 | return Multiply(frac1, frac2); 321 | } 322 | 323 | public static Fraction operator *(int iNo, Fraction frac1) 324 | { 325 | return Multiply(frac1, new Fraction(iNo)); 326 | } 327 | 328 | public static Fraction operator *(Fraction frac1, int iNo) 329 | { 330 | return Multiply(frac1, new Fraction(iNo)); 331 | } 332 | 333 | public static Fraction operator *(double dbl, Fraction frac1) 334 | { 335 | return Multiply(frac1, ToFraction(dbl)); 336 | } 337 | 338 | public static Fraction operator *(Fraction frac1, double dbl) 339 | { 340 | return Multiply(frac1, ToFraction(dbl)); 341 | } 342 | 343 | public static Fraction operator /(Fraction frac1, Fraction frac2) 344 | { 345 | return Multiply(frac1, Inverse(frac2)); 346 | } 347 | 348 | public static Fraction operator /(int iNo, Fraction frac1) 349 | { 350 | return Multiply(Inverse(frac1), new Fraction(iNo)); 351 | } 352 | 353 | public static Fraction operator /(Fraction frac1, int iNo) 354 | { 355 | return Multiply(frac1, Inverse(new Fraction(iNo))); 356 | } 357 | 358 | public static Fraction operator /(double dbl, Fraction frac1) 359 | { 360 | return Multiply(Inverse(frac1), ToFraction(dbl)); 361 | } 362 | 363 | public static Fraction operator /(Fraction frac1, double dbl) 364 | { 365 | return Multiply(frac1, Inverse(ToFraction(dbl))); 366 | } 367 | 368 | public static bool operator ==(Fraction frac1, Fraction frac2) 369 | { 370 | return frac1.Equals(frac2); 371 | } 372 | 373 | public static bool operator !=(Fraction frac1, Fraction frac2) 374 | { 375 | return !frac1.Equals(frac2); 376 | } 377 | 378 | public static bool operator ==(Fraction frac1, int iNo) 379 | { 380 | return frac1.Equals(new Fraction(iNo)); 381 | } 382 | 383 | public static bool operator !=(Fraction frac1, int iNo) 384 | { 385 | return !frac1.Equals(new Fraction(iNo)); 386 | } 387 | 388 | public static bool operator ==(Fraction frac1, double dbl) 389 | { 390 | return frac1.Equals(new Fraction(dbl)); 391 | } 392 | 393 | public static bool operator !=(Fraction frac1, double dbl) 394 | { 395 | return !frac1.Equals(new Fraction(dbl)); 396 | } 397 | 398 | public static bool operator <(Fraction frac1, Fraction frac2) 399 | { 400 | return frac1.Numerator * frac2.Denominator < frac2.Numerator * frac1.Denominator; 401 | } 402 | 403 | public static bool operator >(Fraction frac1, Fraction frac2) 404 | { 405 | return frac1.Numerator * frac2.Denominator > frac2.Numerator * frac1.Denominator; 406 | } 407 | 408 | public static bool operator <=(Fraction frac1, Fraction frac2) 409 | { 410 | return frac1.Numerator * frac2.Denominator <= frac2.Numerator * frac1.Denominator; 411 | } 412 | 413 | public static bool operator >=(Fraction frac1, Fraction frac2) 414 | { 415 | return frac1.Numerator * frac2.Denominator >= frac2.Numerator * frac1.Denominator; 416 | } 417 | 418 | #endregion 419 | 420 | 421 | /// 422 | /// Overloaded user defined conversions: from numeric data types to Fractions 423 | /// 424 | public static implicit operator Fraction(long lNo) 425 | { 426 | return new(lNo); 427 | } 428 | 429 | public static implicit operator Fraction(double dNo) 430 | { 431 | return new(dNo); 432 | } 433 | 434 | public static implicit operator Fraction(string strNo) 435 | { 436 | return new(strNo); 437 | } 438 | 439 | /// 440 | /// Overloaded user defined conversions: from fractions to double and string 441 | /// 442 | public static explicit operator double(Fraction frac) 443 | { 444 | return frac.ToDouble(); 445 | } 446 | 447 | public static implicit operator string(Fraction frac) 448 | { 449 | return frac.ToString(); 450 | } 451 | 452 | /// 453 | /// checks whether two fractions are equal 454 | /// 455 | public override bool Equals(object obj) 456 | { 457 | var frac = (Fraction) obj; 458 | return Numerator == frac.Numerator && Denominator == frac.Denominator; 459 | } 460 | 461 | /// 462 | /// returns a hash code for this fraction 463 | /// 464 | public override int GetHashCode() 465 | { 466 | return Convert.ToInt32((Numerator ^ Denominator) & 0xFFFFFFFF); 467 | } 468 | 469 | /// 470 | /// internal function for negation 471 | /// 472 | private static Fraction Negate(Fraction frac1) 473 | { 474 | long iNumerator = -frac1.Numerator; 475 | long iDenominator = frac1.Denominator; 476 | return new Fraction(iNumerator, iDenominator); 477 | 478 | } 479 | 480 | /// 481 | /// internal functions for binary operations 482 | /// 483 | private static Fraction Add(Fraction frac1, Fraction frac2) 484 | { 485 | try { 486 | checked { 487 | long iNumerator = frac1.Numerator * frac2.Denominator + frac2.Numerator * frac1.Denominator; 488 | long iDenominator = frac1.Denominator * frac2.Denominator; 489 | return new Fraction(iNumerator, iDenominator); 490 | } 491 | } 492 | catch (OverflowException) { 493 | throw new FractionException("Overflow occurred while performing arithmetic operation"); 494 | } 495 | catch (Exception) { 496 | throw new FractionException("An error occurred while performing arithmetic operation"); 497 | } 498 | } 499 | 500 | private static Fraction Multiply(Fraction frac1, Fraction frac2) 501 | { 502 | try { 503 | checked { 504 | long iNumerator = frac1.Numerator * frac2.Numerator; 505 | long iDenominator = frac1.Denominator * frac2.Denominator; 506 | return new Fraction(iNumerator, iDenominator); 507 | } 508 | } 509 | catch (OverflowException) { 510 | throw new FractionException("Overflow occurred while performing arithmetic operation"); 511 | } 512 | catch (Exception) { 513 | throw new FractionException("An error occurred while performing arithmetic operation"); 514 | } 515 | } 516 | 517 | /// 518 | /// The function returns GCD of two numbers (used for reducing a Fraction) 519 | /// 520 | private static long GCD(long iNo1, long iNo2) 521 | { 522 | // take absolute values 523 | if (iNo1 < 0) iNo1 = -iNo1; 524 | if (iNo2 < 0) iNo2 = -iNo2; 525 | 526 | do { 527 | if (iNo1 < iNo2) { 528 | long tmp = iNo1; // swap the two operands 529 | iNo1 = iNo2; 530 | iNo2 = tmp; 531 | } 532 | 533 | iNo1 = iNo1 % iNo2; 534 | } while (iNo1 != 0); 535 | 536 | return iNo2; 537 | } 538 | 539 | /// 540 | /// The function reduces(simplifies) a Fraction object by dividing both its numerator 541 | /// and denominator by their GCD 542 | /// 543 | public static void ReduceFraction(Fraction frac) 544 | { 545 | try { 546 | if (frac.Numerator == 0) { 547 | frac.Denominator = 1; 548 | return; 549 | } 550 | 551 | long iGCD = GCD(frac.Numerator, frac.Denominator); 552 | frac.Numerator /= iGCD; 553 | frac.Denominator /= iGCD; 554 | 555 | if (frac.Denominator < 0) // if -ve sign in denominator 556 | { 557 | //pass -ve sign to numerator 558 | frac.Numerator *= -1; 559 | frac.Denominator *= -1; 560 | } 561 | } // end try 562 | catch (Exception exp) { 563 | throw new FractionException("Cannot reduce Fraction: " + exp.Message); 564 | } 565 | } 566 | } 567 | 568 | 569 | /// 570 | /// Exception class for Fraction, derived from System.Exception 571 | /// 572 | public class FractionException : Exception 573 | { 574 | public FractionException() : base() { } 575 | 576 | public FractionException(string message) : base(message) { } 577 | 578 | public FractionException(string message, Exception innerException) : base(message, innerException) { } 579 | } 580 | } --------------------------------------------------------------------------------