System.Console.ResetColor()

Here are the examples of the csharp api System.Console.ResetColor() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1082 Examples 7

19 Source : Log.cs
with MIT License
from 13xforever

private static void LogInternal(Exception e, string message, LogLevel level, ConsoleColor foregroundColor, ConsoleColor? backgroundColor = null)
        {
            try
            {
#if DEBUG
                const LogLevel minLevel = LogLevel.TRACE;
#else
                const LogLevel minLevel = LogLevel.DEBUG;
#endif
                if (level >= minLevel && message != null)
                {
                    Console.ForegroundColor = foregroundColor;
                    if (backgroundColor is ConsoleColor bg)
                        Console.BackgroundColor = bg;
                    Console.WriteLine(DateTime.Now.ToString("hh:mm:ss ") + message);
                    Console.ResetColor();
                }
                if (FileLog != null)
                {
                    if (message != null)
                        FileLog.WriteLine($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}\t{(long)Timer.Elapsed.TotalMilliseconds}\t{level}\t{message}");
                    if (e != null)
                        FileLog.WriteLine(e.ToString());
                    FileLog.Flush();
                }
            }
            catch { }
        }

19 Source : Program.cs
with MIT License
from 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : PkgChecker.cs
with MIT License
from 13xforever

private static void Write(string str, ConsoleColor? color = null)
        {
            Sync.Wait();
            try
            {
                if (color is ConsoleColor c)
                    Console.ForegroundColor = c;
                Console.Write(str);
                if (color.HasValue)
                    Console.ResetColor();
            }
            finally
            {
                Sync.Release();
            }
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

static void Main(string[] args)
        {
            try
            {
                RunAsync().GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());

                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static void PrintSuccess(string success)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(success);
            Console.ResetColor();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static void PrintInfo(string info)
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine(info);
            Console.ResetColor();
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;

                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<JObject> CallPatchWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                var body = new StringContent(data, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await HttpClient.PatchAsync(webApiUrl, body);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;
                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<JObject> CallDeleteWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            JObject result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.DeleteAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadreplacedtringAsync();
                    result = JsonConvert.DeserializeObject(json) as JObject;
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
                    Console.WriteLine($"Content: {content}");
                    result = content;

                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static void PrintError(string error)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(error);
            Console.ResetColor();
        }

19 Source : ProtectedApiCallHelper.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public async Task<string> CallGetHTMLWebApiAndProcessResultASync(string webApiUrl, string accessToken)
        {
            string result = null;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadreplacedtringAsync();
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    result = await response.Content.ReadreplacedtringAsync();
                    Console.WriteLine($"Content: {result}");
                }
                Console.ResetColor();
            }
            return result;
        }

19 Source : ToolsMain.cs
with Apache License 2.0
from 91270

static void Main(string[] args)
        {
            do
            {
                try
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("=============================================================================");
                    Console.WriteLine("*            1      -      生成模型");
                    Console.WriteLine("=============================================================================");
                    Console.Write("请选择要执行的程序 : ");
                    Console.ResetColor();

                    switch (Int32.Parse(Console.ReadLine()))
                    {
                        case 1:

                            #region  生成模型
                            Task001.Execute();
                            #endregion

                            Console.ReadKey();

                            break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadKey();
                }
            } while (true);
        }

19 Source : Program.cs
with Apache License 2.0
from aaaddress1

static void log(string str2log, ConsoleColor wordColor = ConsoleColor.White, params object[] args)
        {
            Console.ForegroundColor = wordColor;
            Console.Write(str2log, args);
            Console.ResetColor();
        }

19 Source : Program.cs
with Apache License 2.0
from aaaddress1

static void printMenu(bool showMenu = false, string loadXlsPath = "")
        {
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Cyan; ;
            Console.WriteLine(xlsKami.Properties.Resources.banner);
            Console.WriteLine("   xlsKami [v1.]");
            Console.WriteLine("   Out-of-the-Box Tool to Obfuscate Excel 97-2003 XLS");
            Console.ResetColor();
            Console.WriteLine(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            if (showMenu)
            {
                log("[v] Selected File: {0}\n", ConsoleColor.Magenta, loadXlsPath);
                log("[+] Menu \n", ConsoleColor.Cyan);
                log("\t[1] Masquerade Cell Labels\n", ConsoleColor.Cyan);
                log("\t[2] Masquerade Workbook Sheets\n", ConsoleColor.Cyan);
                log("\t[3] Save & Exit\n", ConsoleColor.Cyan);
                log("\t[4] Exit\n", ConsoleColor.Cyan);
                foreach (var szLog in historyList) log(szLog, ConsoleColor.Green);
                Console.WriteLine(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

                log("[?] choose action (index): ", ConsoleColor.Cyan);
            }

        }

19 Source : Program.cs
with MIT License
from abock

static int Main(string[] args)
    {
        var decode = false;
        var wrap = 76;
        var showHelp = false;
        var showVersion = false;

        var options = new OptionSet
        {
            { "usage: ecoji [OPTIONS]... [FILE]" },
            { "" },
            { "Encode or decode data as Unicode emojis. 😻🍹" },
            { "" },
            { "Options:" },
            {
                "d|decode",
                "Decode data.",
                v => decode = v != null
            },
            {
                "w|wrap=",
                "Wrap encoded lines after {COLS} characters (default 76). " +
                    "Use 0 to disable line wrapping.",
                (int v) => wrap = v
            },
            {
                "h|help",
                "Print this message.",
                v => showHelp = v != null
            },
            {
                "v|version",
                "Print version information.",
                v => showVersion = v != null
            }
        };

        void ShowHelp()
            => options.WriteOptionDescriptions(Console.Out);

        void ShowVersion()
        {
            Console.WriteLine($"Ecoji (.NET Core) version {version}");
            Console.WriteLine($"  Copyright   : {copyright}");
            Console.WriteLine($"  License     : MIT");
            Console.WriteLine($"  Source code : https://github.com/abock/dotnet-ecoji");
            Console.WriteLine();
            Console.WriteLine($"Based on Ecoji by Keith Turner:");
            Console.WriteLine($"  https://github.com/keith-turner/ecoji");
        }

        try
        {
            var positional = options.Parse(args);

            if (showHelp)
            {
                ShowHelp();
                return ExitShowHelp;
            }

            if (showVersion)
            {
                ShowVersion();
                return ExitShowVersion;
            }

            Stream inputStream;

            if (positional is null ||
                positional.Count == 0 ||
                positional[0] == "-")
                inputStream = Console.OpenStandardInput();
            else if (positional.Count == 1)
                inputStream = new FileStream(
                    positional[0],
                    FileMode.Open,
                    FileAccess.Read);
            else
                throw new Exception("more than one file was provided");

            try
            {
                using(inputStream)
                {
                    if (decode)
                    {
                        using var stdout = Console.OpenStandardOutput();
                        Ecoji.Decode(inputStream, stdout);
                    }
                    else
                    {
                        Ecoji.Encode(inputStream, Console.Out, wrap);
                    }
                }
            }
            catch (Exception e)
            {
                WriteError($"pipe or encoding/decoding error: {e}");
                return ExitDataError;
            }

            return ExitSuccess;
        }
        catch (Exception e)
        {
            WriteError(e.Message);
            ShowHelp();
            return ExitArgumentsError;
        }
        
        static void WriteError(string error)
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Error.WriteLine($"error: {error}");
            Console.Error.WriteLine();
            Console.ResetColor();
        }
    }

19 Source : Program.cs
with MIT License
from abock

static void Error(string message)
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine($"Error: {message}");
            Console.ResetColor();
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task LogAsync(LogMessage message)
        {
            while (IsLoggerLocked)
            {
                await Task.Delay(1).ConfigureAwait(false);
            }
            IsLoggerLocked = true;
            switch (message.Severity)
            {
                case LogSeverity.Critical:
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    break;
                case LogSeverity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                case LogSeverity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case LogSeverity.Info:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                case LogSeverity.Verbose:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;
                case LogSeverity.Debug:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
            }
            await Console.Out.WriteLineAsync($"[{message.Source}]{message.Message}").ConfigureAwait(false);
            Console.ResetColor();
            IsLoggerLocked = false;
        }

19 Source : Program.cs
with MIT License
from action-bi-toolkit

static int Main(string[] args)
        {
            // When invoked w/o args, print usage and exit immediately (do not trigger ArgException)
            if ((args ?? new string[0]).Length == 0)
            {
                ArgUsage.GenerateUsageFromTemplate<CmdLineActions>().WriteLine();
                return (int)ExitCode.NoArgsProvided;
            }

            var result = default(ExitCode);
            try
            {
                var action = Args.ParseAction<CmdLineActions>(args);
                
                action.Invoke(); // throws ArgException (DuplicateArg, MissingArg, UnexpectedArg, UnknownArg, ValidationArg)

                // in Debug compilation, propagates any exceptions thrown by executing action
                // in Release compilation, a user friendly error message is displayed, and exceptions thrown are available via the HandledException property

                /* This branch only applies in Release (StandardExceptionHandling enabled) mode, and only to __parser__ exceptions */
                if (action.HandledException != null)
                {
                    // Standard output has been generated by PowerArgs framework already
                    Console.WriteLine();
                    Log.Verbose(action.HandledException, "PowerArgs exception");
                }

                // TODO Define and handle specific exceptions to report back to user directly (No PBI install, etc...)

                result = action.HandledException == null ? ExitCode.Success : ExitCode.InvalidArgs;
            }
            catch (ArgException ex)
            {
                // In RELEASE mode, the PowerArgs error has already been emitted, and the usage docs have been printed to the console at this stage
                
                if (!Environment.UserInteractive)
                {
                    Log.Fatal(ex, "Bad user input.");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine(ex.Message);
                    Console.ResetColor();
#if DEBUG
                    ArgUsage.GenerateUsageFromTemplate(ex.Context.Definition).WriteLine();
#endif
                }
                result = ExitCode.InvalidArgs;
            }
            catch (PbiToolsCliException ex)
            {
                Log.Error(ex.Message);
                result = ex.ErrorCode;
            }
            catch (Exception ex) /* Any unhandled exception */
            {
                // TODO Explicitly log into crash file...
                // If CWD is not writable, put into user profile and show path...

                Log.Fatal(ex, "An unhandled exception occurred.");
                result = ExitCode.UnexpectedError;
            }

            // Prevent closing of window when debugging
            if (Debugger.IsAttached && Environment.UserInteractive)
            {
                Console.WriteLine();
                Console.Write("Press ENTER to exit...");
                Console.ReadLine();
            }

            // ExitCode:
            return (int)result;
        }

19 Source : Terminal.cs
with MIT License
from actions

public void Write(string message, ConsoleColor? colorCode = null)
        {
            Trace.Info($"WRITE: {message}");
            if (!Silent)
            {
                if (colorCode != null)
                {
                    Console.ForegroundColor = colorCode.Value;
                    Console.Write(message);
                    Console.ResetColor();
                }
                else
                {
                    Console.Write(message);
                }
            }
        }

19 Source : Terminal.cs
with MIT License
from actions

public void WriteLine(string line, ConsoleColor? colorCode = null)
        {
            Trace.Info($"WRITE LINE: {line}");
            if (!Silent)
            {
                if (colorCode != null)
                {
                    Console.ForegroundColor = colorCode.Value;
                    Console.WriteLine(line);
                    Console.ResetColor();
                }
                else
                {
                    Console.WriteLine(line);
                }
            }
        }

19 Source : Terminal.cs
with MIT License
from actions

public void WriteError(Exception ex)
        {
            Trace.Error("WRITE ERROR (exception):");
            Trace.Error(ex);
            if (!Silent)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Error.WriteLine(ex.Message);
                Console.ResetColor();
            }
        }

19 Source : Terminal.cs
with MIT License
from actions

public void WriteError(string line)
        {
            Trace.Error($"WRITE ERROR: {line}");
            if (!Silent)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Error.WriteLine(line);
                Console.ResetColor();
            }
        }

19 Source : Terminal.cs
with MIT License
from actions

public void WriteSection(string message)
        {
            if (!Silent)
            {
                Console.WriteLine();
                Console.ResetColor();
                Console.WriteLine($"# {message}");
                Console.WriteLine();
            }
        }

19 Source : Terminal.cs
with MIT License
from actions

public void WriteSuccessMessage(string message)
        {
            if (!Silent)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("√ ");
                Console.ResetColor();
                Console.WriteLine(message);
            }
        }

19 Source : SearchAutomation.cs
with MIT License
from ADeltaX

private static async Task SearchRun(string name, string ringName)
        {
            var res = await _edgeUpdate.GetLatestFiles(name);
            if (res.Success && !SharedDBcmd.UpdateExists(ringName, res.Value.Version))
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] !!! New update !!! {ringName} - Version: {res.Value.Version}");
                Console.ResetColor();

                var edgeFileFull = res.Value.EdgeFile.Where(file => file.EdgeFileUpdateType == EdgeFileUpdateType.Full).First();
                var SHA1Hex = BitConverter.ToString(edgeFileFull.Sha1).Replace("-", "");
                var SHA256Hex = BitConverter.ToString(edgeFileFull.Sha256).Replace("-", "");

                SharedDBcmd.AddNewUpdate(ring: ringName, version: res.Value.Version,
                                                filename: edgeFileFull.FileName, filesize: edgeFileFull.Size,
                                                sha256: SHA256Hex, url: edgeFileFull.Url);

                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] <<< Downloading from MSEdge fe3 server");
                Console.ResetColor();
                await Download(name, res.Value.Version, edgeFileFull);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] >>> Uploading to Telegram via TDLib");
                Console.ResetColor();
                await UploadAndSendMessage(edgeFileFull, string.Format(messageEdgeUpdate, ringName, res.Value.Version, SHA1Hex));

            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

void UpdateArchive(string path, bool verbose)
        {
            if (!verbose)
                Console.Write("Creating .tar archives ... ");

            foreach (var directory in DirectoriesDictionary(path + @"\customize", path))
            {
                if (verbose)
                    Console.Write("Creating " + directory.Value + ".tar archive ... ");

                ArchiveManager.CreateTarArchive(directory.Key, path + @"\themes\" + directory.Value + ".tar", verbose);
            }

            if (!verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

void UpdateIcons(string iconsPath, string customizePath, bool verbose)
        {
            if (!verbose)
                Console.Write("Copying icons ... ");

            foreach (var directory in DirectoriesArray(customizePath))
            {
                foreach (var icon in FilesArray(iconsPath))
                {
                    if (verbose)
                        Console.Write("Copying " + icon + " ... ");

                    File.Copy(iconsPath + @"\" + icon, directory + @"\icons\" + icon, true);

                    if (verbose)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("OK\n");
                        Console.ResetColor();
                    }
                }
            }

            if (!verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

void UpdateFonts(string fontsPath, string customizePath, bool verbose)
        {
            if (!verbose)
                Console.Write("Copying fonts ... ");

            foreach (var directory in DirectoriesArray(customizePath))
            {
                foreach (var font in FilesArray(fontsPath))
                {
                    if (verbose)
                        Console.Write("Copying " + font + " ... ");

                    File.Copy(fontsPath + @"\" + font, directory + @"\" + font, true);

                    if (verbose)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("OK\n");
                        Console.ResetColor();
                    }
                }
            }

            if (!verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

string CheckRepoPath(string path)
        {
            if (Directory.Exists(path) && path.Contains("distro-grub-themes"))
            {
                int index = path.IndexOf("distro-grub-themes") + 18;
                return path.Substring(0, index);
            }

            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("error: ");
                Console.ResetColor();
                Console.Write("could not find repository in this path");
                Environment.Exit(1);
                return null;
            }
        }

19 Source : ArchiveManager.cs
with GNU General Public License v3.0
from AdisonCavani

public static void CreateTarArchive(string sourceDirectory, string outputFile, bool verbose)
        {
            Chilkat.Tar tar = new Chilkat.Tar
            {
                WriteFormat = "gnu"
            };

            // Add a directory tree to be included in the output TAR archive:
            bool success = tar.AddDirRoot(sourceDirectory);
            if (success != true)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("ERROR\n\n");
                Console.Write("error: ");
                Console.ResetColor();
                Console.Write(tar.LastErrorText + "\n");
                return;
            }

            // Create the TAR archive.
            success = tar.WriteTar(outputFile);
            if (success != true)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("ERROR\n\n");
                Console.Write("error: ");
                Console.ResetColor();
                Console.Write(tar.LastErrorText + "\n");
                return;
            }

            if (verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with MIT License
from Aerion

private static async Task<T> RetryOnFailure<T>(Func<Task<T>> task)
        {
            try
            {
                return await task();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Error.WriteLine($"Caught exception - retrying once: {ex}");
                Console.ResetColor();
                return await task();
            }
        }

19 Source : Build.cs
with GNU General Public License v3.0
from Aetsu

public static string DownloadRepository(string toolName, string url)
        {
            string path = "GitTools";
            try
            {
                if (!Directory.Exists(path))
                {
                    DirectoryInfo di = Directory.CreateDirectory(path);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
            string toolPath = Path.Combine(new string[] { path, toolName });
            if (!Directory.Exists(toolPath))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Clonnig the repository: {0}", toolName);
                Console.ResetColor();
                Repository.Clone(url, toolPath);
                using (var repo = new Repository(toolPath))
                {
                    var commit = repo.Head.Tip;
                    Console.WriteLine(@"        Last commit: {0}", commit.Author.When.ToLocalTime());
                }
            }
            return toolPath;
        }

19 Source : Build.cs
with GNU General Public License v3.0
from Aetsu

public static string BuildTool(string solutionPath, string toolName)
        {
            string finalPath = string.Empty;
            string text = System.IO.File.ReadAllText(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "template_build.bat" }));
            string buildOptions = "/p:Platform=\"Any CPU\"";
            solutionPath = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "GitTools", solutionPath });
            string outputDir = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Output" });
            if (File.Exists(solutionPath))
            {

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Solving dependences with nuget...");
                Console.ResetColor();
                if (Helpers.ExecuteCommand(@"Resources\nuget.exe restore " + solutionPath) != 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("         Error -> nuget.exe: {0}", solutionPath);
                    Console.ResetColor();
                }
                finalPath = Path.Combine(new string[] { outputDir, toolName + "_" + Helpers.GetRandomString() });

                text = text.Replace("{{SOLUTION_PATH}}", solutionPath);
                text = text.Replace("{{BUILD_OPTIONS}}", buildOptions);
                text = text.Replace("{{OUTPUT_DIR}}", finalPath);
                string batPath = Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), "buildSolution.bat" });
                File.WriteAllText(batPath, text);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Building solution...");
                Console.ResetColor();
                if (Helpers.ExecuteCommand(batPath) != 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("         Error -> msbuild.exe: {0}", solutionPath);
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("         No errors!");
                    Console.ResetColor();
                }

                //Gets all references to the project to obfuscate it with confuser
                SolutionFile s = SolutionFile.Parse(solutionPath);
                foreach (ProjectInSolution p in s.ProjectsInOrder)
                {
                    if (File.Exists(p.AbsolutePath))
                    {
                        XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
                        XDoreplacedent projDefinition = XDoreplacedent.Load(p.AbsolutePath);
                        IEnumerable<string> references = projDefinition
                            .Element(msbuild + "Project")
                            .Elements(msbuild + "ItemGroup")
                            .Elements(msbuild + "Reference")
                            .Elements(msbuild + "HintPath")
                            .Select(refElem => refElem.Value);
                        foreach (string reference in references)
                        {
                            string referenceFile = reference.Replace(@"..\", "");
                            if (File.Exists(Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), referenceFile })))
                            {
                                File.Copy(
                                    Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), referenceFile }),
                                    Path.Combine(new string[] { finalPath, Path.GetFileName(referenceFile) }),
                                    true);
                            }
                        }
                    }

                }
            }
            return finalPath;
        }

19 Source : Build.cs
with GNU General Public License v3.0
from Aetsu

public static void Confuse(string folder)
        {
            string[] exeList = Directory.GetFiles(folder, "*.exe");
            foreach (string exe in exeList)
            {
                string text = File.ReadAllText(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "template_confuserEx.crproj" }));
                text = text.Replace("{{BASE_DIR}}", folder);
                text = text.Replace("{{OUTPUT_DIR}}", Path.Combine(new string[] { folder, "Confused" }));
                text = text.Replace("{{EXE_FILE}}", exe);
                string crprojPath = Path.Combine(new string[] { folder, exe + ".crproj" });
                System.IO.File.WriteAllText(crprojPath, text);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Confusing " + exe + "...");
                Console.ResetColor();
                if (Helpers.ExecuteCommand(
                    Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx", "Confuser.CLI.exe" }) + " " + crprojPath) != 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("         Error -> ConfuserEx: {0}", exe);
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("         No errors!");
                    Console.ResetColor();
                }
            }
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from Aetsu

public static void CalculateMD5Files(string folder)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("     Calculating md5...");
            Console.ResetColor();
            string[] fileList = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
            List<string> md5List = new List<string>();
            foreach (string filename in fileList)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(filename))
                    {
                        var hash = md5.ComputeHash(stream);
                        md5List.Add(filename + " - " + BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
                    }
                }
            }
            File.WriteAllLines(Path.Combine(new string[] { folder, "md5.txt" }), md5List);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Aetsu

static void replacedyzeTools()
        {
            string[] toolList = Directory.GetFiles("Tools", "*.yml");
            foreach (string tool in toolList)
            {
                string outputFolder = string.Empty;
                string toolPath = string.Empty;
                string text = File.ReadAllText(tool);
                var stringReader = new StringReader(text);
                var yaml = new YamlStream();
                yaml.Load(stringReader);
                var mapping = (YamlMappingNode)yaml.Doreplacedents[0].RootNode;

                foreach (var entry in mapping.Children)
                {
                    var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("tool")];
                    foreach (YamlMappingNode item in items)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("\n[+] Name: {0}", item.Children[new YamlScalarNode("name")]);
                        Console.ResetColor();
                        Console.WriteLine("     - Description: {0}\n     - Git link: {1}\n     - Solution file: {2}\n",
                            item.Children[new YamlScalarNode("description")],
                            item.Children[new YamlScalarNode("gitLink")],
                            item.Children[new YamlScalarNode("solutionPath")]);

                        try
                        {
                            toolPath = Build.DownloadRepository(item.Children[new YamlScalarNode("name")].ToString()
                            , item.Children[new YamlScalarNode("gitLink")].ToString());
                            outputFolder = Build.BuildTool(
                                item.Children[new YamlScalarNode("solutionPath")].ToString(),
                                item.Children[new YamlScalarNode("name")].ToString());
                            if (Helpers.ExecuteCommand("RMDIR \"" + toolPath + "\" /S /Q") != 0)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("         Error -> RMDIR: {0}", toolPath);
                                Helpers.LogToFile("replacedyzeTools", "ERROR", "RMDIR: <" + toolPath + ">");
                                Console.ResetColor();
                            }
                            Build.Confuse(outputFolder);
                            Helpers.CalculateMD5Files(outputFolder);
                            Console.ForegroundColor = ConsoleColor.Magenta;
                            Console.WriteLine("     Output folder: {0}", outputFolder);
                            Console.ResetColor();
                        } 
                        catch (Exception ex)
                        {
                            Console.WriteLine("         Error -> replacedyzing: <{0}> -> {1}", item.Children[new YamlScalarNode("name")], ex.ToString());
                            Helpers.LogToFile("replacedyzeTools", "ERROR", "replacedyzing: <" + item.Children[new YamlScalarNode("name")] + "> -> " + ex.ToString());
                        }
                    }
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Aetsu

static void replacedyzeTools(string toolName)
        {
            string outputFolder = string.Empty;
            string toolPath = string.Empty;
            if (!File.Exists(@"Tools\" + toolName + ".yml"))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("         Error -> {0} tool not supported", toolName);
                Helpers.LogToFile("replacedyzeTools", "ERROR", "<" + toolName + "> not supported");
                Console.ResetColor();
                return;
            }
            string text = File.ReadAllText(@"Tools\" + toolName + ".yml");
            var stringReader = new StringReader(text);
            var yaml = new YamlStream();
            yaml.Load(stringReader);
            var mapping = (YamlMappingNode)yaml.Doreplacedents[0].RootNode;

            foreach (var entry in mapping.Children)
            {
                var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("tool")];
                foreach (YamlMappingNode item in items)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("\n[+] Name: {0}", item.Children[new YamlScalarNode("name")]);
                    Console.ResetColor();
                    Console.WriteLine("     - Description: {0}\n     - Git link: {1}\n     - Solution file: {2}\n",
                        item.Children[new YamlScalarNode("description")],
                        item.Children[new YamlScalarNode("gitLink")],
                        item.Children[new YamlScalarNode("solutionPath")]);
                    try
                    {
                        toolPath = Build.DownloadRepository(item.Children[new YamlScalarNode("name")].ToString()
                            , item.Children[new YamlScalarNode("gitLink")].ToString());
                        outputFolder = Build.BuildTool(
                                item.Children[new YamlScalarNode("solutionPath")].ToString(),
                                item.Children[new YamlScalarNode("name")].ToString());
                        if (Helpers.ExecuteCommand("RMDIR \"" + toolPath + "\" /S /Q") != 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("         Error -> RMDIR: {0}", toolPath);
                            Helpers.LogToFile("replacedyzeTools", "ERROR", "RMDIR: <" + toolPath + ">");
                            Console.ResetColor();
                        }
                        Build.Confuse(outputFolder);
                        Helpers.CalculateMD5Files(outputFolder);
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        Console.WriteLine("     Output folder: {0}", outputFolder);
                        Console.ResetColor();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("         Error -> replacedyzing: <{0}> -> {1}", item.Children[new YamlScalarNode("name")], ex.ToString());
                        Helpers.LogToFile("replacedyzeTools", "ERROR", "replacedyzing: <" + item.Children[new YamlScalarNode("name")] + "> -> " + ex.ToString());
                    }
                }
            }

        }

19 Source : Program.cs
with GNU General Public License v3.0
from Aetsu

static void CheckStart()
        {
            int error = 0;
            if (!File.Exists(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "nuget.exe" })))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("   [*] Downloading nuget.exe...");
                Console.ResetColor();
                //Download nuget.exe
                error = Helpers.DownloadResources(@"https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", "nuget.exe", "Resources");
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
            }
            if (!Directory.Exists(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx" })))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("   [*] Downloading ConfuserEx...");
                Console.ResetColor();
                //Download ConfuserEx
                error = Helpers.DownloadResources(@"https://github.com/mkaring/ConfuserEx/releases/download/v1.4.1/ConfuserEx-CLI.zip", "ConfuserEx.zip", "Resources");
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
                error = Helpers.UnzipFile(
                    Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }),
                    Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx" }));
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
                try
                {
                    File.Delete(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("         Error ->  deleting <" + Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }) + "> - " + ex.ToString());
                    Helpers.LogToFile("CheckStart", "ERROR", "Deleting: <" + Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }) + "> - " + ex.ToString());
                }
            }
            string buildToolsPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\VsDevCmd.bat";
            if (!File.Exists(buildToolsPath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("         Error -> File not found: {0}", buildToolsPath);
                Console.WriteLine("             Install -> Build Tools for Visual Studio 2019");
                Helpers.LogToFile("CheckStart", "ERROR", "File not found: <" + buildToolsPath + ">");
                Console.ResetColor();
                System.Environment.Exit(1);
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Aetsu

static void ListTools()
        {
            string[] toolList = Directory.GetFiles("Tools", "*.yml");
            foreach (string tool in toolList)
            {
                string text = File.ReadAllText(tool);
                var stringReader = new StringReader(text);
                var yaml = new YamlStream();
                yaml.Load(stringReader);
                var mapping = (YamlMappingNode)yaml.Doreplacedents[0].RootNode;
                foreach (var entry in mapping.Children)
                {
                    var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("tool")];
                    foreach (YamlMappingNode item in items)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("\n   [+] Name: {0}", item.Children[new YamlScalarNode("name")]);
                        Console.ResetColor();
                        Console.WriteLine("     - Description: {0}\n     - Git: {1}",
                            item.Children[new YamlScalarNode("description")],
                            item.Children[new YamlScalarNode("gitLink")]);
                    }
                }
            }
            Console.WriteLine();
        }

19 Source : Tester.cs
with Mozilla Public License 2.0
from agebullhu

static void TestFrame(string replacedle, ZeroOperatorStateType state, params byte[][] frames)
        {
            Console.Error.Write(replacedle);
            Console.ForegroundColor = ConsoleColor.Red;
            TestFrameInner(replacedle, state, frames);
            Console.Error.WriteLine();
            Console.Error.WriteLine("**----**");
            Console.ResetColor();
        }

19 Source : AppConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void Write(string text, ConsoleColor color = ConsoleColor.White)
        {
            Console.ForegroundColor = color;
            Console.Write(text);
            Console.ResetColor();
        }

19 Source : AppConsole.cs
with GNU General Public License v3.0
from agolaszewski

public void WriteLine(string text = " ", ConsoleColor color = ConsoleColor.White)
        {
            Console.ForegroundColor = color;
            Console.WriteLine(text);
            Console.ResetColor();
        }

19 Source : SampleExecute.cs
with The Unlicense
from ahotko

private void PopColors()
        {
            Console.ResetColor();
        }

19 Source : DefaultLogger.cs
with MIT License
from Aiko-IT-Systems

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!this.IsEnabled(logLevel))
                return;

            lock (_lock)
            {
                var ename = eventId.Name;
                ename = ename?.Length > 12 ? ename?.Substring(0, 12) : ename;
                Console.Write($"[{DateTimeOffset.Now.ToString(this.TimestampFormat)}] [{eventId.Id,-4}/{ename,-12}] ");

                switch (logLevel)
                {
                    case LogLevel.Trace:
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;

                    case LogLevel.Debug:
                        Console.ForegroundColor = ConsoleColor.DarkMagenta;
                        break;

                    case LogLevel.Information:
                        Console.ForegroundColor = ConsoleColor.DarkCyan;
                        break;

                    case LogLevel.Warning:
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        break;

                    case LogLevel.Error:
                        Console.ForegroundColor = ConsoleColor.Red;
                        break;

                    case LogLevel.Critical:
                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.ForegroundColor = ConsoleColor.Black;
                        break;
                }
                Console.Write(logLevel switch
                {
                    LogLevel.Trace => "[Trace] ",
                    LogLevel.Debug => "[Debug] ",
                    LogLevel.Information => "[Info ] ",
                    LogLevel.Warning => "[Warn ] ",
                    LogLevel.Error => "[Error] ",
                    LogLevel.Critical => "[Crit ]",
                    LogLevel.None => "[None ] ",
                    _ => "[?????] "
                });
                Console.ResetColor();

                //The foreground color is off.
                if (logLevel == LogLevel.Critical)
                    Console.Write(" ");

                var message = formatter(state, exception);
                Console.WriteLine(message);
                if (exception != null)
                    Console.WriteLine(exception);
            }

19 Source : Util.cs
with GNU General Public License v3.0
from am0nsec

private static void LogMessage(string msg, string prefix, int indent, ConsoleColor color) {
            // Indent
            Console.Write(new String(' ', indent));
            Trace.Write(new String(' ', indent));

            // Color and prefix
            Trace.Write(prefix);
            Console.ForegroundColor = color;
            Console.Write(prefix);
            Console.ResetColor();

            // Message
            Console.WriteLine($" {msg}");
            Trace.WriteLine($" {msg}");
        }

19 Source : sqlite.cs
with MIT License
from Amine-Smahi

private static void Main(string[] args)
        {
            _dbPath = ReadVariable();
            switch (args.Length)
            {
                case 2:
                    switch (args[0])
                    {
                        case "-db":
                            SaveValue(args[1]);
                            _dbPath = args[1];
                            break;
                        case "-q" when _dbPath == "empty":
                            Console.Write("\n Please Specify the sqlite database path first by typing ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write(@"-db ""path""" + Environment.NewLine + Environment.NewLine);
                            Console.ResetColor();
                            break;
                        case "-q":
                            ExecuteQuery(args[1]);
                            break;
                        case "-r" when _dbPath == "empty":
                            Console.Write("\n Please Specify the sqlite database path first by typing ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write(@"-db ""path""" + Environment.NewLine + Environment.NewLine);
                            Console.ResetColor();
                            break;
                        case "-r":
                            ExecuteQueryWithResult(args[1], false);
                            break;
                        case "-s":
                        {
                            if (args[1] != null)
                            {
                                ExecuteQueryWithResult(args[1], true);
                            }
                            break;
                        }
                        default:
                            Console.Write("\n  Command not found check the option ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write(@"--h");
                            Console.ResetColor();
                            Console.Write(" for more information \n\n");
                            break;
                    }

                    break;
                case 1 when args[0] == "--h":
                    Console.WriteLine("\n => Welcome to sqlite .net core global tool version 1.0");
                    Console.WriteLine("\nOptions:");
                    Console.WriteLine(@"   -db ""Sqlite Database Path""");
                    Console.WriteLine(@"   -q  ""Query to execute""");
                    Console.WriteLine(@"   -r  ""Query to execute with result""");
                    Console.WriteLine(@"   -s  ""the table that you want to show, its data""");
                    Console.WriteLine();
                    break;
                case 1:
                    Console.WriteLine("\n   Need to insert a value for the option\n");
                    break;
                default:
                    Console.Write("\n   Check the help section by typing ");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("sqlite-tool --h \n");
                    Console.ResetColor();
                    break;
            }
        }

19 Source : sqlite.cs
with MIT License
from Amine-Smahi

private static void ExecuteQueryWithResult(string queryOrTable, bool isTable)
        {
            try
            {
                if (_dbPath == "empty")
                {
                    Console.WriteLine("\n => Welcome to sqlite .net core global tool version 1.1 <=");
                    Console.Write("       Check the help section by typing sqlite ");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("sqlite-tool --h \n");
                    Console.ResetColor();
                }
                else
                {
                    if (!TestConnectionDatabase()) return;
                    var connectionStringBuilder = new SqliteConnectionStringBuilder {DataSource = _dbPath};
                    using (var connection = new SqliteConnection(connectionStringBuilder.ConnectionString))
                    {
                        connection.Open();
                        var selectCmd = connection.CreateCommand();
                        if (!isTable)
                        {
                            selectCmd.CommandText = queryOrTable;
                        }
                        else
                        {
                            selectCmd.CommandText = "Select * from " + queryOrTable;
                        }

                        using (var reader = selectCmd.ExecuteReader())
                        {
                            var count = reader.FieldCount;
                            var numberRecord = 0;
                            while (reader.Read())
                            {
                                numberRecord++;
                            }

                            var arrValues = new string[numberRecord + 1, count];
                            for (var i = 0; i < count; i++)
                            {
                                arrValues[0, i] = " " + reader.GetName(i) + " ";
                                var j = 1;
                                while (reader.Read())
                                {
                                    arrValues[j, i] = " " + reader[reader.GetName(i)] + " ";
                                    j++;
                                }
                            }

                            Console.WriteLine();
                            ArrayPrinter.PrintToConsole(arrValues);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n There is an error in your sql syntax");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("  "+ex.Message + "\n");
                Console.ResetColor();
            }
        }

See More Examples