private void RunSingleTest(MethodInfo methodInfo, string inputFile, string outputFile) { Console.SetIn(File.OpenText(inputFile)); var actualOutput = new StringWriter(); var expectedOutputLines = FileWithoutLock.ReadAllLines(outputFile).Select(l => l.Replace("\r\n", string.Empty)).ToArray(); Console.SetOut(actualOutput); methodInfo.Invoke(null, null); Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); var actualOutputLines = new StringReader(actualOutput.ToString()).ReadAllLines() .Select(l => l.Replace("\r\n", string.Empty)).ToArray(); var success = CompareOutput(actualOutputLines, expectedOutputLines); var sucessLabel = success ? "OK" : "KO"; Console.WriteLineStyled($"[{Path.GetFileName(_sourceCodeFile)}] Running test : {Path.GetFileName(inputFile)} {sucessLabel}", _styleSheet); if (!success) { PrintDiff(expectedOutputLines, actualOutputLines); } }
public static string licenseInformation() { using (HttpRequest httpRequest = new HttpRequest()) { Console.WriteLineFormatted("\n{0}{1}{2} License:", Color.White, design.colors); Console.WriteFormatted(" {3} ", Color.White, design.colors); string license = Console.ReadLine(); try { string result = httpRequest.Get("https://developers.auth.gg/LICENSES/?type=fetch&authorization=" + Program.AuthorizationKey + "&license=" + license).ToString(); informationLicense infoLicense = JsonConvert.DeserializeObject <informationLicense>(result); Console.WriteLineFormatted("\n{0}{1}{2} Status: " + infoLicense.status, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} License: " + infoLicense.license, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} Rank: " + infoLicense.rank, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} Used: " + infoLicense.used, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} Used_by: " + infoLicense.used_by, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} Created: " + infoLicense.created, Color.White, design.colors); return("done"); } catch (Exception ex) { Console.WriteLine("\n " + ex.Message, Color.Red); Console.ReadLine(); Environment.Exit(0); return(null); } } }
private static async Task Main(string[] args) { Logger logger = LogManager.GetLogger("Launch"); var parser = new CommandLineBuilder(LaunchCommand.GetCommand()) .UseHost((args) => CreateHostBuilder(args)) .UseDefaults() .UseMiddleware(async(context, next) => { await next(context); }) .UseExceptionHandler((ex, context) => { var stackTrace = Configuration.GetValue <bool>("ShowStackTraceOnError") ? ex.StackTrace : "Error details hidden. Enable 'ShowStackTraceOnError' to see more..."; logger.Error(ex, $"The global exception handler caught an exception: {ex.Message}{Environment.NewLine}{stackTrace}"); logger.Info($"Press any key to close..."); Console.ReadKey(); }) .Build(); // display some startup info Console.WriteAscii("Launch", Color.FromArgb(204, 102, 0)); Console.Write($"Version: "); parser.Parse("--version").Invoke(); // parse the arguments await parser.InvokeAsync(args); }
public static string editPassword() { using (HttpRequest httpRequest = new HttpRequest()) { Console.WriteLineFormatted("\n{0}{1}{2} User:"******" {3} ", Color.White, design.colors); string userSearch = Console.ReadLine(); Console.WriteLineFormatted("\n{0}{1}{2} new Password:"******" {3} ", Color.White, design.colors); string newPassword = Console.ReadLine(); try { string result = httpRequest.Get("https://developers.auth.gg/USERS/?type=changepw&authorization=" + Program.AuthorizationKey + "&user="******"&password="******"\n{0}{1}{2} Status: " + user.status, Color.White, design.colors); Console.WriteLineFormatted("{0}{1}{2} Info: " + user.info, Color.White, design.colors); return("done"); } catch (Exception ex) { Console.WriteLine("\n " + ex.Message, Color.Red); Console.ReadLine(); Environment.Exit(0); return(null); } } }
public static void tryingAuthorizationKey() { try { using (HttpRequest httpRequest = new HttpRequest()) { string result = httpRequest.Get("https://developers.auth.gg/USERS/?type=count&authorization=" + Program.AuthorizationKey).ToString(); if (result.Contains("\"status\":\"failed\"")) { Console.WriteLine("\nSomething went wrong, please check your authorization key or renew it.", Color.Red); } else if (result.Contains("\"status\":\"success\"")) { Console.Clear(); Program.Menu(); } } } catch (Exception ex) { Console.WriteLine("\n " + ex.Message, Color.Red); Console.ReadLine(); Environment.Exit(0); } }
public void WriteHelpItem(ICommandRoot helpItem, int indent = 0) { ConsoleHelper.WriteWithIndent(helpItem.Name, indent * IndentAmount, ColorH1); Console.WriteLine(); ConsoleHelper.WriteWithIndent(new String(HeaderSeparatorChar, helpItem.Name.Length), indent * IndentAmount, Color.Gray); Console.WriteLine(); ConsoleHelper.WriteWithIndent(helpItem.Description, indent * IndentAmount); Console.WriteLine(); Console.WriteLine(); ConsoleHelper.WriteWithIndent("Usage:", indent * IndentAmount, ColorH1); Console.WriteLine(); string rootVerbs = string.Join(" ", helpItem.CommonTokens.Select(x => x.Name.Preferred)); foreach (ICommandUsage usage in helpItem.Usages) { if (usage.IsHelp) { continue; } WriteHelpItem(helpItem, usage, indent + 1); } }
/// <summary> Writes the given URL to give file </summary> static void writeListToFile(string path, List <string> content) { FileInfo f = new FileInfo(path); if (f == null) { Console.WriteFormatted("\n\t │ Cannot find {0} " + path, red); } bool isFirst = f.Length > 10 ? false : true; try { using (StreamWriter writer = new StreamWriter(path, append: true)) { //open the file that will be written as updated version of before foreach (string ss in content) { if (isFirst == true) { writer.Write(ss); isFirst = false; } else { writer.Write(Environment.NewLine + ss); } } } // using } catch (Exception e) { Console.WriteFormatted("\n\t │ Exception: " + e.Message, red); Console.WriteLineFormatted("\t │ Operation failed. Nothing changed.", red); new SoundPlayer(URLbliss.Properties.Resources.gurg).Play(); return; } }
protected override void WriteAppTitle() { // choose font on http://www.figlet.org/examples.html var font = FiggleFonts.Epic; Console.WriteLine(font.Render("Group App")); }
/// <summary> Searches(contains) given URL in txt </summary> static bool searchUrl(string URL) { bool found = false; string[] dots = { ".", "..", "..." }; try { using (StreamReader file = new StreamReader(urlblissFileName)) { if (file.ReadLine() == null) { Console.WriteLineFormatted("\n │ ! Failure when reading file.", red); } else { short counterLines = 0; string currLine; while ((currLine = file.ReadLine()) != null) { Helpers.NOP(200); // waits a little bit, the greater the longer Console.Write("\r\t│ [{0}] Looking {1} ", counterLines, dots[(counterLines / 600) % 3]); counterLines++; if (currLine.Contains(URL)) { Console.Write("\n\t│ Found at line [{0}] > {1}\n", counterLines, currLine); found = true; } } // loop } // if-else } // file read } // try catch (Exception e) { Console.WriteLineFormatted("\n!│ Reading exception: " + e.Message, red); new SoundPlayer(URLbliss.Properties.Resources.gurg).Play(); } return(found); }
static async Task SubmitScore(PlayerInfo player) { int retries = 0; while (retries < 3) { try { int Score = player.Zone.Score; await player.ReportScore(); Console.WriteLine($"{{{player.Token}}} Score {Score} Submitted", Color.Green); return; } catch (GameTimeNotSync TooEarly) { retries++; Console.WriteLine($"Score Submission Too Early [{TooEarly.EResult}] -> Wait 1 Second and Retry", Color.Red); await Task.Delay(1000); } catch (GameExpired) { Console.WriteLine($"{{{player.Token}}} Zone was Captured, Unable to Submit Score.", Color.Red); return; } catch (InvalidGameResponse IGR) { Console.WriteLine($"{{{player.Token}}} Bad Response {IGR.EResult} - {IGR.EReason}.", Color.Red); return; } } Console.WriteLine($"{{{player.Token}}} Score Submission Failure After 3 Retries", Color.Red); }
public static void LoadAssemblies(IConfiguration configuration, Action <Assembly> action) { ModulesOptions options = configuration.Get <ModulesOptions>(); var platform = configuration.GetValue <string>("platformModuleName"); var module = options.Modules.Find(x => x.Name == platform); // load platform emulator dynamically Console.WriteLine(); var platformDllPath = Path.Combine(options.ModuleBasePath, module.Path, $"{module.Type}.dll"); if (File.Exists(platformDllPath)) { Assembly library = AssemblyLoadContext.Default.LoadFromAssemblyPath(platformDllPath); action(library); Formatter[] settings = new Formatter[] { new Formatter(platform, Color.Yellow), new Formatter(platformDllPath, Color.Yellow) }; Console.WriteLineFormatted("Loaded {0} platform emulator from {1} assembly.", Color.White, settings); } else { Console.WriteLine($"Can't load {module.Type} assembly from {platformDllPath}."); } Console.WriteLine(); }
static void PrintPlayerInfo() { foreach (PlayerInfo player in Players.Values) { Console.WriteLineStyled($"{{{player.Token}}} Level {player.Level} [{player.Score} -> {player.NextLevelScore}] {Math.Round((float)player.Score / player.NextLevelScore * 100, 2)}%", NumberStyle); } }
static async Task PrintPlanetInfo() { await Planet.UpdateActive(); Console.WriteLineStyled($"Planets, {Planet.Active.Count()} Active / {Planet.Captured.Count()} Captured / {Planet.Locked.Count()} Locked / {Planet.All.Count()} Total", PrimaryStyle); Console.WriteLineStyled($"Total Zone Completion {Planet.All.CompletionPercent()}%, Active Zone Completion {Planet.Active.CompletionPercent()}%", NumberStyle); }
private void RunTests(MethodInfo methodInfo) { if (methodInfo == null) { return; } if (!_inputFiles.Any()) { Console.WriteLine($"WARN: no input files found in {Path.GetDirectoryName(_sourceCodeFile)}", Color.Yellow); } foreach (var inputFile in _inputFiles) { var outputFile = Path.Combine( Path.GetDirectoryName(inputFile), Path.GetFileName(inputFile.Replace("input", "output"))); if (File.Exists(outputFile)) { RunSingleTest(methodInfo, inputFile, outputFile); } else { Console.WriteLine($"WARN: {inputFile} ignore because no associated output was found", Color.Yellow); } } }
protected void ReadAndDispatchConsoleKeys() { if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.Enter: this.InputManager.SendInputBufferAsCommand(); break; case ConsoleKey.Backspace: this.InputManager.RemoveLastCharOfInputBuffer(); break; case ConsoleKey.Escape: L.Information("Stopping"); this.Destroy(); break; default: this.InputManager.AddCharToInputBuffer(key.KeyChar); break; } } }
/// <summary> Checks given IP for error/fouls in syntax </summary> static bool checkIP(string IP) { // check whether given url is valid or not IPAddress address; if (IPAddress.TryParse(IP, out address)) { switch (address.AddressFamily) { case System.Net.Sockets.AddressFamily.InterNetwork: Console.Write("\n │ " + IP + " is IPv4"); return(true); case System.Net.Sockets.AddressFamily.InterNetworkV6: Console.Write("\n │ " + IP + " is IPv6"); return(true); default: Console.WriteFormatted("\n ! " + IP + " is NOT valid", red); return(false); } } else { return(false); } }
public void WriteCommandList(CommandLibrary library) { List <ICommandRoot> commands = library.GetAllCommands().ToList(); if (!commands.Any()) { Console.WriteLine($"There are 0 available commands!"); return; } Console.WriteLine($"{Environment.NewLine}Available Commands:"); Console.WriteLine($"-------------------"); int padLen = commands.Max(x => x.Name.Length) + 1; //add 1 is an arbitrary number. //Just gives it some extra padding foreach (var command in commands) { Console.Write(command.Name.PadRight(padLen)); if (!string.IsNullOrWhiteSpace(command.Description)) { Console.WriteLine($": {command.Description}", Color.Gray); } else { Console.WriteLine(); } } Console.WriteLine(); }
private static void ShowStartMessages(string migrationGeneratedSqlFolder, string migrationGeneratedSqlFilename) { Formatter[] message; if (!Parameters.PreviewOnly) { message = new[] { new Formatter("UPDATE", Color.Red), new Formatter($"{migrationGeneratedSqlFolder}{migrationGeneratedSqlFilename}", Color.Green) }; } else { message = new[] { new Formatter("PREVIEW", Color.Green), new Formatter($"{migrationGeneratedSqlFolder}{migrationGeneratedSqlFilename}", Color.Green) }; } Console.WriteLineFormatted( "Starting migrations in {0} mode." + Environment.NewLine + "SQL will be written to {1}", Color.White, message); Console.WriteLine($"Tags passed: {string.Join(",", Parameters.Tags)}"); }
public static void DisplayAsciiArt(this CommandLineApplication target) { const string ascii = @" `.:::` ``` `` `:+ooooo. syo /yy` `-/ooooooooo. `` ydy +dd` ``` `:+oooooooooooo. -+syyso:ss: ydy `/so: +dd` -ss/ -+syyso:ss: `./oooooooooooooooo. `ohho:-:+ydd+ ydy`:yho- +dd`-shy: /hhs/-:/yhdy `:+ooooooooooooooooooo- /dd: .hd+ ydhshh: +ddohd+ .hdo `ydy ./oooooooooooss{0} /dd: .hd+ ydhsyhs. +ddyshy: .hdo `ydy `-+ooooooooos{1} `ohho:-:+hdds- ydy``/hh+` +dd. :yho ohho:-:+hdds- `/ooooooooos{2} -+syyso:/sys oso .os+ /ss` `+so `/syyys/-sys /oooooooos{3} ``` `` ``` `` -oooooo/{4} {5} `-::-` {6} "; var lightColor = Color.FromArgb(47, 171, 223); var darkColor = Color.FromArgb(25, 118, 186); var fruits = new[] { new Formatter("yhhhhddddh-", darkColor), new Formatter("yhhhdddddddddddh:", darkColor), new Formatter("yhhhdddddddddddddddh.", darkColor), new Formatter("yhhhddddddddhhdddddddh:", darkColor), new Formatter(":-.```", darkColor), new Formatter("``.-ddhdddh`", darkColor), new Formatter("`-::-`", darkColor) }; Console.WriteLineFormatted(ascii, lightColor, fruits); }
static void Main(string[] args) { Console.WriteLine(string.Empty); var desc = " Foreach"; var fontArr = System.Text.Encoding.Default.GetBytes(ContessaFont.CONTESSA); FigletFont font = FigletFont.Load(fontArr); Figlet figlet = new Figlet(font); Console.WriteLine(figlet.ToAscii(desc), Color.Blue); Console.WriteFormatted("Turn easy the execution of loops, for and batch command line programs using statments like ", Color.White); Console.WriteLineFormatted("foreach ", Color.Green); try { var multiplierIndex = args.ToList().IndexOf("*"); if (multiplierIndex == -1) { throw new DocoptNet.DocoptInputErrorException("You must to specify * multiplier character"); } var beforeArgs = SubArray <string>(args, 0, multiplierIndex); var afterArgs = SubArray <string>(args, multiplierIndex + 1, args.Length - multiplierIndex - 1); var arguments = new Docopt().Apply(Usage.SHORT_HELP, beforeArgs, version: "Foreach", exit: false); try { Run(afterArgs, arguments).Wait(); Environment.Exit(0); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(2); } } catch (Exception e) { Console.WriteLine(Usage.SHORT_HELP); Console.WriteLine(string.Empty); //Console.WriteLine($@" > To convert all wav files in currenty folder (and sub-directories recursivelly) and convert to mp3 format"); //Console.WriteLineFormatted($@" ffmpeg-batch -s /**/*.wav -o mp3", Color.Green); //Console.WriteLine(string.Empty); //Console.WriteLine($@" > To convert all wma files in c:\music and convert to mp3 format"); //Console.WriteLineFormatted($@" ffmpeg-batch -s c:\music\*.wma -o mp3", Color.Green); Console.WriteLine("Install/Uninstall tool:"); Console.WriteLine($@" > To install tool from system"); Console.WriteLineFormatted($@" dotnet tool install -g foreach", Color.Green); Console.WriteLine(string.Empty); Console.WriteLine($@" > To uninstall tool from system"); Console.WriteLineFormatted($@" dotnet tool uninstall -g foreach", Color.Green); Environment.Exit(1); } }
private static void Log(string p_message, DebugChannel p_channel, DebuggingLevel p_min_level, Indentation p_pre, Indentation p_post) { if (!enable_debugging && p_channel == DebugChannel.Debug) { return; } if (debugging_level < p_min_level) { return; } // If the pre-indentation style is not set to none, perform the necessary indentation/unindentation/reset task first if (p_pre > 0) { if (p_pre == Debugging.Indentation.Indent) { Indent(); } else if (p_pre == Debugging.Indentation.Unindent) { Unindent(); } else if (p_pre == Debugging.Indentation.Reset) { ResetIndentation(); } } // Re-format the message to include the channel tag, timestamp and indentation string message = $"{p_channel.Tag()} {Timestamp} > {Indentation}{p_message}"; // Print the message to the console using the correct colours if (p_channel != DebugChannel.Debug) { Console.WriteLine(message, p_channel.Colour()); } else { // If using the [debug] channel, use the debug stylesheet to allow syntax highlighting Console.WriteLineStyled(message, debug_style_sheet); } // If the post-indentation style is not set to none, perform the necessary indentation/unindentation/reset task if (p_post > 0) { if (p_post == Debugging.Indentation.Indent) { Indent(); } else if (p_post == Debugging.Indentation.Unindent) { Unindent(); } else if (p_post == Debugging.Indentation.Reset) { ResetIndentation(); } } }
private static void Main() { // Start console ConsoleManager.Start(); ConsoleManager.Initialize(); // Wait for console to get ready TODO: Actually check for when ConsoleManager is ready Thread.Sleep(1000); // Ask what game to start StartCommand command; while (true) { // Write available commands Console.WriteLine("Pick one of the following commands", Color.White); foreach (string commandName in Enum.GetNames(typeof(StartCommand))) // TODO: Also number the commands { Console.WriteLine(commandName, Color.White); } // Get and parse input if (!Enum.TryParse(ConsoleManager.GetPriorityInput(), true, out command)) { Console.WriteLine("Input invalid, try again.", Color.Red); } // Break loop on successful parse else { break; } } // Start game switch (command) { case StartCommand.Local: StartLocal(); break; case StartCommand.P2P: StartPeerToPeer(); break; case StartCommand.Client: StartClient(); break; case StartCommand.Server: StartServer(); break; case StartCommand.ClientAndServer: StartClientAndServer(); break; default: throw new ArgumentOutOfRangeException(); } }
// implementations of user commands: /** * Print out some help information. * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { Console.WriteLine("You are lost. You are alone."); Console.WriteLine("You wander around on the Island."); Console.WriteLine(); Console.WriteLine("Your command words are:"); parser.showCommands(); }
static void exit(int ecode = 0) { Console.WriteLine(" "); Console.Write("press any key to continue..."); Console.ReadKey(true); Environment.Exit(ecode); }
static void RainbowText(string inp) { foreach (char c in inp) { Console.Write(c, colors[rng.Next(0, colors.Length - 1)]); } Console.Write("\n"); }
public void Divider() { string divider = "_____________________________________________________"; TextCenter(divider); Console.WriteLine(divider); }
// POSITIONING OF THE CURSOR public void pressAnyKey() { Console.WriteLine(); string lblkey = "PRESS ANY KEY TO CONTINUE"; TextCenter(lblkey); Console.WriteLine(lblkey); }
public static void DrawWelcome() { Console.BackgroundColor = Color.DarkSlateBlue; Console.Clear(); Console.ForegroundColor = Color.LightYellow; Console.SetCursorPosition(0, Console.WindowHeight / 2 - 1); Console.Write(Center(StringWelcome, Console.WindowWidth)); }
public static void LogTermination(string message) { StyleSheet styleSheet = new StyleSheet(Color.White); styleSheet.AddStyle(TerminationString, Color.Red); Console.WriteLineStyled($"[{TerminationString}] {message}", styleSheet); }
public static void LogIdentification(string message) { StyleSheet styleSheet = new StyleSheet(Color.White); styleSheet.AddStyle(IdentificationString, Color.LightBlue); Console.WriteLineStyled($"[{IdentificationString}] {message}", styleSheet); }