public static void Main() { var table = new Table().Centered(); // Animate AnsiConsole.Live(table) .AutoClear(false) .Overflow(VerticalOverflow.Ellipsis) .Cropping(VerticalOverflowCropping.Top) .Start(ctx => { void Update(int delay, Action action) { action(); ctx.Refresh(); Thread.Sleep(delay); } // Columns Update(230, () => table.AddColumn("Release date")); Update(230, () => table.AddColumn("Title")); Update(230, () => table.AddColumn("Budget")); Update(230, () => table.AddColumn("Opening Weekend")); Update(230, () => table.AddColumn("Box office")); // Rows Update(70, () => table.AddRow("May 25, 1977", "[yellow]Star Wars[/] [grey]Ep.[/] [u]IV[/]", "$11,000,000", "$1,554,475", "$775,398,007")); Update(70, () => table.AddRow("May 21, 1980", "[yellow]Star Wars[/] [grey]Ep.[/] [u]V[/]", "$18,000,000", "$4,910,483", "$547,969,004")); Update(70, () => table.AddRow("May 25, 1983", "[yellow]Star Wars[/] [grey]Ep.[/] [u]VI[/]", "$32,500,000", "$23,019,618", "$475,106,177")); Update(70, () => table.AddRow("May 19, 1999", "[yellow]Star Wars[/] [grey]Ep.[/] [u]I[/]", "$115,000,000", "$64,810,870", "$1,027,044,677")); Update(70, () => table.AddRow("May 16, 2002", "[yellow]Star Wars[/] [grey]Ep.[/] [u]II[/]", "$115,000,000", "$80,027,814", "$649,436,358")); Update(70, () => table.AddRow("May 19, 2005", "[yellow]Star Wars[/] [grey]Ep.[/] [u]III[/]", "$113,000,000", "$108,435,841", "$850,035,635")); Update(70, () => table.AddRow("Dec 18, 2015", "[yellow]Star Wars[/] [grey]Ep.[/] [u]VII[/]", "$245,000,000", "$247,966,675", "$2,068,223,624")); Update(70, () => table.AddRow("Dec 15, 2017", "[yellow]Star Wars[/] [grey]Ep.[/] [u]VIII[/]", "$317,000,000", "$220,009,584", "$1,333,539,889")); Update(70, () => table.AddRow("Dec 20, 2019", "[yellow]Star Wars[/] [grey]Ep.[/] [u]IX[/]", "$245,000,000", "$177,383,864", "$1,074,114,248")); // Column footer Update(230, () => table.Columns[2].Footer("$1,633,000,000")); Update(230, () => table.Columns[3].Footer("$928,119,224")); Update(400, () => table.Columns[4].Footer("$10,318,030,576")); // Column alignment Update(230, () => table.Columns[2].RightAligned()); Update(230, () => table.Columns[3].RightAligned()); Update(400, () => table.Columns[4].RightAligned()); // Column titles Update(70, () => table.Columns[0].Header("[bold]Release date[/]")); Update(70, () => table.Columns[1].Header("[bold]Title[/]")); Update(70, () => table.Columns[2].Header("[red bold]Budget[/]")); Update(70, () => table.Columns[3].Header("[green bold]Opening Weekend[/]")); Update(400, () => table.Columns[4].Header("[blue bold]Box office[/]")); // Footers Update(70, () => table.Columns[2].Footer("[red bold]$1,633,000,000[/]")); Update(70, () => table.Columns[3].Footer("[green bold]$928,119,224[/]")); Update(400, () => table.Columns[4].Footer("[blue bold]$10,318,030,576[/]")); // Title Update(500, () => table.Title("Star Wars Movies")); Update(400, () => table.Title("[[ [yellow]Star Wars Movies[/] ]]")); // Borders Update(230, () => table.BorderColor(Color.Yellow)); Update(230, () => table.MinimalBorder()); Update(230, () => table.SimpleBorder()); Update(230, () => table.SimpleHeavyBorder()); // Caption Update(400, () => table.Caption("[[ [blue]THE END[/] ]]")); }); }
public static bool Run(ProcessInfo process, IRegistryService?registryService = null) { bool ok = true; var runtime = process.DotnetRuntime; if (runtime == ProcessInfo.Runtime.NetFx) { AnsiConsole.WriteLine(NetFrameworkRuntime); } else if (runtime == ProcessInfo.Runtime.NetCore) { AnsiConsole.WriteLine(NetCoreRuntime); } else { Utils.WriteWarning(runtime == ProcessInfo.Runtime.Mixed ? BothRuntimesDetected : RuntimeDetectionFailed); runtime = ProcessInfo.Runtime.NetFx; } if (FindProfilerModule(process) == null) { Utils.WriteWarning(ProfilerNotLoaded); ok = false; } var tracerModules = FindTracerModules(process).ToArray(); if (tracerModules.Length == 0) { Utils.WriteWarning(TracerNotLoaded); ok = false; } else if (tracerModules.Length > 1) { // There are too many tracers in there. Find out if it's bad or very bad bool areAllVersion2 = true; var versions = new HashSet <string>(); foreach (var tracer in tracerModules) { var version = FileVersionInfo.GetVersionInfo(tracer); versions.Add(version.FileVersion ?? "{empty}"); if (version.FileMajorPart < 2) { areAllVersion2 = false; } } Utils.WriteWarning(MultipleTracers(versions)); if (!areAllVersion2) { Utils.WriteError(VersionConflict); ok = false; } } if (process.EnvironmentVariables.TryGetValue("DD_DOTNET_TRACER_HOME", out var tracerHome)) { if (!Directory.Exists(tracerHome)) { Utils.WriteWarning(TracerHomeNotFoundFormat(tracerHome)); ok = false; } } else { Utils.WriteWarning(EnvironmentVariableNotSet("DD_DOTNET_TRACER_HOME")); ok = false; } string corProfilerKey = runtime == ProcessInfo.Runtime.NetCore ? "CORECLR_PROFILER" : "COR_PROFILER"; process.EnvironmentVariables.TryGetValue(corProfilerKey, out var corProfiler); if (corProfiler != Utils.Profilerid) { Utils.WriteWarning(WrongEnvironmentVariableFormat(corProfilerKey, Utils.Profilerid, corProfiler)); ok = false; } string corEnableKey = runtime == ProcessInfo.Runtime.NetCore ? "CORECLR_ENABLE_PROFILING" : "COR_ENABLE_PROFILING"; process.EnvironmentVariables.TryGetValue(corEnableKey, out var corEnable); if (corEnable != "1") { Utils.WriteError(WrongEnvironmentVariableFormat(corEnableKey, "1", corEnable)); ok = false; } ok &= CheckProfilerPath(process, runtime == ProcessInfo.Runtime.NetCore ? "CORECLR_PROFILER_PATH" : "COR_PROFILER_PATH", requiredOnLinux: true); ok &= CheckProfilerPath(process, runtime == ProcessInfo.Runtime.NetCore ? "CORECLR_PROFILER_PATH_32" : "COR_PROFILER_PATH_32", requiredOnLinux: false); ok &= CheckProfilerPath(process, runtime == ProcessInfo.Runtime.NetCore ? "CORECLR_PROFILER_PATH_64" : "COR_PROFILER_PATH_64", requiredOnLinux: false); if (RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { if (!CheckRegistry(registryService)) { ok = false; } } return(ok); }
public static void Main() { var table = new Table().HideHeaders().NoBorder(); table.Title("[u][yellow]Spectre.Console[/] [b]Features[/][/]"); table.AddColumn("Feature", c => c.NoWrap().RightAligned().Width(10).PadRight(3)); table.AddColumn("Demonstration", c => c.PadRight(0)); table.AddEmptyRow(); // Colors table.AddRow( new Markup("[red]Colors[/]"), GetColorTable()); // Styles table.AddEmptyRow(); table.AddRow( new Markup("[red]OS[/]"), new Grid().Expand().AddColumns(3) .AddRow( "[bold green]Windows[/]", "[bold blue]macOS[/]", "[bold yellow]Linux[/]")); // Styles table.AddEmptyRow(); table.AddRow( "[red]Styles[/]", "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/], [underline]underline[/], " + "[strikethrough]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/]."); // Text table.AddEmptyRow(); table.AddRow( new Markup("[red]Text[/]"), new Markup("Word wrap text. Justify [green]left[/], [yellow]center[/] or [blue]right[/].")); table.AddEmptyRow(); table.AddRow( Text.Empty, GetTextGrid()); // Markup table.AddEmptyRow(); table.AddRow( "[red]Markup[/]", "[bold purple]Spectre.Console[/] supports a simple [i]bbcode[/] like " + "[b]markup[/] for [yellow]color[/], [underline]style[/], and emoji! " + ":thumbs_up: :red_apple: :ant: :bear: :baguette_bread: :bus:"); // Trees and tables table.AddEmptyRow(); table.AddRow( new Markup("[red]Tables and Trees[/]"), GetTreeTable()); // Charts table.AddRow( new Markup("[red]Charts[/]"), new Grid().Collapse().AddColumns(2).AddRow( new Panel(GetBreakdownChart()).BorderColor(Color.Grey), new Panel(GetBarChart()).BorderColor(Color.Grey))); // Exceptions table.AddEmptyRow(); table.AddRow( new Markup("[red]Exceptions[/]"), ExceptionGenerator.GenerateException().GetRenderable()); // Much more table.AddEmptyRow(); table.AddRow( "[red]+ Much more![/]", "Tables, Grids, Trees, Progress bars, Status, Bar charts, Calendars, Figlet, Images, Text prompts, " + "List boxes, Separators, Pretty exceptions, Canvas, CLI parsing"); table.AddEmptyRow(); // Render the table AnsiConsole.WriteLine(); AnsiConsole.Write(table); }
static void editInvoice(string cs) { //Tables Console.Clear(); var rule = new Rule("Edit an existing invoice"); AnsiConsole.Render(rule); Console.WriteLine(); Console.WriteLine(); var table = new Table(); table.Centered(); table.AddColumn("Rooms"); table.AddColumn("Invoice types"); table.AddColumn("Existing invoices"); var roomTable = new Table(); roomTable.Border = TableBorder.Minimal; roomTable.AddColumn("Room ID:s available for charges:"); var invoiceTypeTable = new Table(); invoiceTypeTable.Border = TableBorder.Minimal; invoiceTypeTable.AddColumn("Invoice Type ID:"); invoiceTypeTable.AddColumn("Invoice Type:"); var invoiceTable = new Table(); invoiceTable.Border = TableBorder.Minimal; invoiceTable.AddColumn("Invoice ID"); invoiceTable.AddColumn("Room ID"); invoiceTable.AddColumn("Type ID"); invoiceTable.AddColumn("Amount"); //Sql connection using var con = new SqlConnection(cs); con.Open(); //Select queries var availableRooms = con.Query <Room>("SELECT * FROM Rooms").ToList(); var availableInvoiceType = con.Query <InvoiceTypes>("SELECT * FROM InvoiceTypes").ToList(); var availableInvoices = con.Query <Invoice>("SELECT * FROM Invoices").ToList(); availableRooms.ForEach(room => roomTable.AddRow($"{room.RoomId}")); availableInvoiceType.ForEach(type => invoiceTypeTable.AddRow($"{type.InvoiceTypeId}", $"{type.InvoiceType}")); availableInvoices.ForEach(invoice => invoiceTable.AddRow($"{invoice.InvoiceNumberId}", $"{invoice.RoomId}", $"{invoice.TypeId}", $"{invoice.Amount} USD")); table.AddRow(invoiceTable, roomTable, invoiceTypeTable); AnsiConsole.Render(table); bool validMenuChoice = false; Console.WriteLine("What invoice do you want to edit?"); string invoiceToEdit = Console.ReadLine(); int invoiceToEditInt; Console.WriteLine("What room should be charged?"); string roomToCharge = Console.ReadLine(); int roomToChargeInt; Console.WriteLine("What type of charge is it?"); string invoiceType = Console.ReadLine(); int invoiceTypeInt; Console.WriteLine("How much is the charge?"); string amountToCharge = Console.ReadLine(); int amountToChargeInt; validMenuChoice = int.TryParse(invoiceToEdit, out invoiceToEditInt); validMenuChoice = int.TryParse(roomToCharge, out roomToChargeInt); validMenuChoice = int.TryParse(invoiceType, out invoiceTypeInt); validMenuChoice = int.TryParse(amountToCharge, out amountToChargeInt); if (validMenuChoice) { try { con.Query($"UPDATE Invoices SET RoomId = {roomToCharge}, TypeId = {invoiceType}, Amount = {amountToCharge} WHERE InvoiceNumberId = {invoiceToEdit}"); }catch (System.Data.SqlClient.SqlException) { Console.WriteLine("Sorry, the database did not accept your input. Please try again.."); Console.Read(); } } else { Console.WriteLine("Please enter numbers only.."); Console.Read(); return; } }
public static void PrintError(string message) { AnsiConsole.MarkupLine($"[red bold]error:[/] {message}"); }
public CommandOutputLogger(CommandOutputProvider commandOutputProvider, bool useConsoleColor) { _provider = commandOutputProvider; _outConsole = AnsiConsole.GetOutput(useConsoleColor); }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.DarkCyan; //Azure connection stringbuilder SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = "hoteldatabase-marcus.database.windows.net"; builder.UserID = "MarcusT"; builder.Password = "******"; builder.InitialCatalog = "HotelMMv2"; //Local connectionstring //var cs = @"Server=localhost\SQLEXPRESS;Database=mackesHotel;Trusted_Connection=True;"; bool appRunning = true; while (appRunning) { //Meny Console.Clear(); var rule = new Rule("Hotel M&M Management system"); var menuTable = new Table(); menuTable.Border = TableBorder.Double; menuTable.Centered(); menuTable.AddColumn("Option: "); menuTable.AddColumn("Task:"); menuTable.AddRow("1", "Render list of guests"); menuTable.AddRow("2", "Show unpaid invoices"); menuTable.AddRow("3", "Show archived invoices"); menuTable.AddRow("4", "Pay and archive an invoice"); menuTable.AddRow("5", "Add a new invoice"); menuTable.AddRow("6", "Edit invoice"); menuTable.AddRow("7", "Exit application"); AnsiConsole.Render(rule); Console.WriteLine(); Console.WriteLine(); AnsiConsole.Render(menuTable); int selection; Console.Write("Option: "); string input = Console.ReadLine(); bool validMenuChoice = int.TryParse(input, out selection); switch (selection) { case 1: showGuestList(builder.ConnectionString); break; case 2: showInvoices(builder.ConnectionString); Console.Read(); break; case 3: showResolvedInvoices(builder.ConnectionString); break; case 4: payInvoice(builder.ConnectionString); break; case 5: addInvoice(builder.ConnectionString); break; case 6: editInvoice(builder.ConnectionString); break; case 7: Environment.Exit(0); break; } } }
internal static Command Create() { var logCommand = new Command("log") { new Option <string>("--apiKey", description: "An API key with permission to execute the command") { IsRequired = true, }, new Option <Guid>("--logId", "The ID of the log to send the log message to") { IsRequired = true }, new Option <string>("--application", "Used to identify which application logged this message. You can use this if you have multiple applications and services logging to the same log"), new Option <string>("--detail", "A longer description of the message. For errors this could be a stacktrace, but it's really up to you what to log in there."), new Option <string>("--hostname", "The hostname of the server logging the message."), new Option <string>("--title", "The textual title or headline of the message to log.") { IsRequired = true }, new Option <string>("--titleTemplate", "The title template of the message to log. This property can be used from logging frameworks that supports structured logging like: \"{user} says {quote}\". In the example, titleTemplate will be this string and title will be \"Gilfoyle says It's not magic. It's talent and sweat\"."), new Option <string>("--source", "The source of the code logging the message. This could be the assembly name."), new Option <int>("--statusCode", "If the message logged relates to a HTTP status code, you can put the code in this property. This would probably only be relevant for errors, but could be used for logging successful status codes as well."), new Option <DateTime>("--dateTime", "The date and time in UTC of the message. If you don't provide us with a value in dateTime, we will set the current date and time in UTC."), new Option <string>("--type", "The type of message. If logging an error, the type of the exception would go into type but you can put anything in there, that makes sense for your domain."), new Option <string>("--user", "An identification of the user triggering this message. You can put the users email address or your user key into this property."), new Option <string>("--severity", "An enum value representing the severity of this message. The following values are allowed: Verbose, Debug, Information, Warning, Error, Fatal"), new Option <string>("--url", "If message relates to a HTTP request, you may send the URL of that request. If you don't provide us with an URL, we will try to find a key named URL in serverVariables."), new Option <string>("--method", "If message relates to a HTTP request, you may send the HTTP method of that request. If you don't provide us with a method, we will try to find a key named REQUEST_METHOD in serverVariables."), new Option <string>("--version", "Versions can be used to distinguish messages from different versions of your software. The value of version can be a SemVer compliant string or any other syntax that you are using as your version numbering scheme."), new Option <string>("--correlationId", "CorrelationId can be used to group similar log messages together into a single discoverable batch. A correlation ID could be a session ID from ASP.NET Core, a unique string spanning multiple microsservices handling the same request, or similar."), }; logCommand.Description = "Log a message to the specified log"; logCommand.Handler = CommandHandler.Create <string, Guid, MessageModel>((apiKey, logId, messageModel) => { var api = Api(apiKey); try { var message = api.Messages.CreateAndNotify(logId, new CreateMessage { Application = messageModel.Application, DateTime = messageModel.DateTime ?? DateTime.UtcNow, Detail = messageModel.Detail, Hostname = messageModel.Hostname, Method = messageModel.Method, Severity = messageModel.Severity, Source = messageModel.Source, StatusCode = messageModel.StatusCode, Title = messageModel.Title, TitleTemplate = messageModel.TitleTemplate, Type = messageModel.Type, Url = messageModel.Url, User = messageModel.User, Version = messageModel.Version, CorrelationId = messageModel.CorrelationId, }); if (message != null) { AnsiConsole.MarkupLine($"[#0da58e]Message successfully logged to https://app.elmah.io/errorlog/search?logId={logId}&hidden=true&expand=true&filters=id:%22{message.Id}%22#searchTab[/]"); } else { AnsiConsole.MarkupLine("[#e6614f]Message not logged[/]"); } } catch (Exception e) { AnsiConsole.MarkupLine($"[red]{e.Message}[/]"); } }); return(logCommand); }
public static void Error(string message) { AnsiConsole.MarkupLine("[bold red]{0}[/]", message.EscapeMarkup()); }
public Report(AnsiConsole console) { _console = console; }
private async Task <Capabilities> ReadCapabilities(Settings settings) { var result = new List <Capability>(); var caps = await ReadCapabilitiesString(settings); AnsiConsole.MarkupLine($"Parsing [yellow]{CapsPath}[/]..."); var lines = caps.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); var indices = new Dictionary <CapabilityType, int> { { CapabilityType.Bool, 0 }, { CapabilityType.Num, 0 }, { CapabilityType.String, 0 }, }; foreach (var line in lines) { if (line.StartsWith("#")) { continue; } var columns = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries); var name = columns[0].Trim(); var description = columns[7].Trim(); var type = columns[2] switch { "bool" => CapabilityType.Bool, "num" => CapabilityType.Num, "str" => CapabilityType.String, _ => throw new InvalidOperationException($"Unknown caps type '{columns[2]}' ({line})"), }; var typeName = type switch { CapabilityType.Bool => "bool", CapabilityType.Num => "num", CapabilityType.String => "string", _ => throw new NotSupportedException(), }; var prefix = type switch { CapabilityType.Bool => "indicates", CapabilityType.Num => "is", CapabilityType.String => "is the", _ => throw new NotSupportedException(), }; result.Add(new Capability { Name = name.Pascalize(), Variable = name, Type = type, Index = indices[type], Description = $"The {name} [{columns[0]}, {columns[1]}] {typeName} capability {prefix} {columns[7].Humanize(LetterCasing.LowerCase)}.", }); indices[type] += 1; } var capabilities = new Capabilities(result); return(capabilities); }
private void WaitForUserInput(string message) { AnsiConsole.MarkupLine($"[green][[:check_mark_button: {message}]][/]"); System.Console.ReadLine(); }
/// <summary> /// The program's entry point. /// </summary> public static void Main() { AnsiConsole.WriteLine("Project is set up with a reference to Spectre.Console.Analyzer"); }
public override async Task <bool> Execute(DescribeInput input) { input.HostBuilder.ConfigureServices(x => x.AddTransient <IDescribedSystemPart, ConfigurationPreview>()); using (var host = input.BuildHost()) { var config = host.Services.GetRequiredService <IConfiguration>(); var hosting = host.Services.GetService <IHostEnvironment>(); var about = new AboutThisAppPart(hosting, config); var factories = host.Services.GetServices <IDescribedSystemPartFactory>(); var parts = host.Services.GetServices <IDescribedSystemPart>() .Concat(factories.SelectMany(x => x.Parts())) .Concat(new IDescribedSystemPart[] { about, new ReferencedAssemblies() }).ToArray(); foreach (var partWithServices in parts.OfType <IRequiresServices>()) { partWithServices.Resolve(host.Services); } if (input.ListFlag) { Console.WriteLine("The registered system parts are"); foreach (var part in parts) { Console.WriteLine("* " + part.Title); } return(true); } if (input.TitleFlag.IsNotEmpty()) { parts = parts.Where(x => x.Title == input.TitleFlag).ToArray(); } else if (input.InteractiveFlag) { var prompt = new MultiSelectionPrompt <string>() .Title("What part(s) of your application do you wish to view?") .PageSize(10) .AddChoices(parts.Select(x => x.Title)); var titles = AnsiConsole.Prompt(prompt); parts = parts.Where(x => titles.Contains(x.Title)).ToArray(); } if (!input.SilentFlag) { await WriteToConsole(parts); } if (input.FileFlag.IsNotEmpty()) { using (var stream = new FileStream(input.FileFlag, FileMode.CreateNew, FileAccess.Write)) { var writer = new StreamWriter(stream); await WriteText(parts, writer); await writer.FlushAsync(); } Console.WriteLine("Wrote system description to file " + input.FileFlag); } return(true); } }
private static void Render(Rule rule) { AnsiConsole.Render(rule); AnsiConsole.WriteLine(); }
public void Render() { AnsiConsole.Render(_table); }
protected int Execute(CommandContext context, RunSettings settings, bool enableCiMode) { var args = settings.Command ?? context.Remaining.Raw; var profilerEnvironmentVariables = Utils.GetProfilerEnvironmentVariables( ApplicationContext.RunnerFolder, ApplicationContext.Platform, settings); if (profilerEnvironmentVariables is null) { return(1); } if (enableCiMode) { profilerEnvironmentVariables[Configuration.ConfigurationKeys.CIVisibility.Enabled] = "1"; } if (settings.AdditionalEnvironmentVariables != null) { foreach (var env in settings.AdditionalEnvironmentVariables) { var(key, value) = ParseEnvironmentVariable(env); profilerEnvironmentVariables[key] = value; } } // CI Visibility mode is enabled. // If the agentless feature flag is enabled, we check for ApiKey // If the agentless feature flag is disabled, we check if we have connection to the agent before running the process. if (enableCiMode) { var ciVisibilitySettings = Ci.Configuration.CIVisibilitySettings.FromDefaultSources(); if (ciVisibilitySettings.Agentless) { if (string.IsNullOrWhiteSpace(ciVisibilitySettings.ApiKey)) { Utils.WriteError("An API key is required in Agentless mode."); return(1); } } else if (!Utils.CheckAgentConnectionAsync(settings.AgentUrl).GetAwaiter().GetResult()) { return(1); } } AnsiConsole.WriteLine("Running: " + string.Join(' ', args)); var arguments = args.Count > 1 ? string.Join(' ', args.Skip(1).ToArray()) : null; if (Program.CallbackForTests != null) { Program.CallbackForTests(args[0], arguments, profilerEnvironmentVariables); return(0); } var processInfo = Utils.GetProcessStartInfo(args[0], Environment.CurrentDirectory, profilerEnvironmentVariables); if (args.Count > 1) { processInfo.Arguments = arguments; } return(Utils.RunProcess(processInfo, ApplicationContext.TokenSource.Token)); }
public static void Main(string[] args) { int option; new DataAccess().InitializeDatabase(); new ConfigAccess().InitializeDatabase(); do { Console.ForegroundColor = ConsoleColor.Blue; var panel = new Panel("1-Listar empleados\n2-Agregar empleado\n3-Eliminar empleado\n4-Modificar\n5-Buscar empleado\n6-Configuración\n0-Salir"); panel.Header("Menu", Justify.Center); panel.Border = BoxBorder.Rounded; AnsiConsole.Render(panel); option = AnsiConsole.Ask <int>("[purple]Ingrese la opción[/]"); Console.Clear(); Console.ForegroundColor = ConsoleColor.White; switch (option) { case 1: List <Employes> employees = DataAccess.ReadEmployees(); if (employees is not null) { ShowEmployeesTable(employees); ExportEmployeeListToHtml(); } else { ShowEmployeesTable(null); } break; case 2: DataAccess.CreateEmployee(); break; case 3: DataAccess.DeleteEmployee(); break; case 4: DataAccess.EditEmployee(); break; case 5: string idCard = AnsiConsole.Ask <string>("[green]Ingrese la cedula del empleado[/]"); employees = new List <Employes> { DataAccess.FindEmployeeByIdCard(idCard) }; // Add single employe to list ShowEmployeesTable(employees); break; case 6: var opt = AnsiConsole.Ask <int>("1-Crear configuracion\n2-Eliminar configuración\n3-Mostrar configuración"); Configuration.ConfigurationMenu(opt); Configuration = Configuration.ValidateConfiguration(); break; case 0: option = 0; break; default: Console.WriteLine($"La opción {option} no existe"); break; } } while (option != 0); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Adios!"); Thread.Sleep(1000); }
public SendSimpleMessage(AnsiConsole console, IMailer mailer, IOptions <TestMessageSettings> settings) : base(console) { Mailer = mailer; Settings = settings.Value.SimpleMessageSettings; }
private Reporter(AnsiConsole console) { _console = console; }
static void addInvoice(string cs) { Console.Clear(); var rule = new Rule("Add a new invoice"); AnsiConsole.Render(rule); // Create a table and colums var table = new Table(); table.Centered(); table.AddColumn("Rooms"); table.AddColumn("Invoice types"); var roomTable = new Table(); roomTable.Border = TableBorder.Minimal; roomTable.AddColumn("Room ID:s available for charges:"); var invoiceTypeTable = new Table(); invoiceTypeTable.Border = TableBorder.Minimal; invoiceTypeTable.AddColumn("Invoice Type ID:"); invoiceTypeTable.AddColumn("Invoice Type:"); using var con = new SqlConnection(cs); con.Open(); var availableRooms = con.Query <Room>("SELECT * FROM Rooms").ToList(); var availableInvoiceType = con.Query <InvoiceTypes>("SELECT * FROM InvoiceTypes").ToList(); availableRooms.ForEach(room => roomTable.AddRow($"{room.RoomId}")); availableInvoiceType.ForEach(type => invoiceTypeTable.AddRow($"{type.InvoiceTypeId}", $"{type.InvoiceType}")); table.AddRow(roomTable, invoiceTypeTable); AnsiConsole.Render(table); Console.WriteLine(); Console.WriteLine(); bool validMenuChoice = false; Console.WriteLine("What room do you wanna charge?"); string roomToCharge = Console.ReadLine(); int roomToChargeInt; Console.WriteLine("What type of charge is it?"); string chargeType = Console.ReadLine(); int chargeTypeInt; Console.WriteLine("How much do you want to charge? USD"); string amountToCharge = Console.ReadLine(); int amountToChargeInt; validMenuChoice = int.TryParse(roomToCharge, out roomToChargeInt); validMenuChoice = int.TryParse(chargeType, out chargeTypeInt); validMenuChoice = int.TryParse(amountToCharge, out amountToChargeInt); if (validMenuChoice) { try { con.Query($"INSERT INTO Invoices VALUES({roomToCharge}, {chargeType}, {amountToCharge})"); } catch (System.Data.SqlClient.SqlException) { Console.WriteLine("Sorry, the database did not accept your input. Please try again.."); Console.Read(); return; } } else { Console.WriteLine("Please enter numbers only.."); Console.Read(); return; } Console.WriteLine("New invoice successfully Added!"); Console.Read(); }
void NewGuid() { AnsiConsole.MarkupLine($"[silver][[{Guid.NewGuid():D}]][/]"); AnsiConsole.WriteLine(); }
public static void PrintInfo(string message) { AnsiConsole.MarkupLine($"[grey]info:[/] {message}"); }
private static void WriteLogMessage(string message) { AnsiConsole.MarkupLine($"[grey]LOG:[/] {message}[grey]...[/]"); }
public static void PrintException(Exception exception) { AnsiConsole.WriteException(exception, ExceptionFormats.ShortenEverything); }
static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; string lastStateSave; PrintList printList = new PrintList(); // класс для вывода списка Properties properties = new Properties(); // класс настроек properties.SetProperetiesPath(); if (File.Exists(properties.ProperetiesPath)) //если файл настроек уже существует - загрузка настроек { properties.LoadSettings(); } if (properties.LastState != null) // если существует настройка с последним активным каталогом - загружаем его { Directory.SetCurrentDirectory(properties.LastState); printList.ListDirsAndFiles(); } else //в другом случае проводим первый старт программы { printList.InitialStart(); var helpPanel = new Table(); helpPanel.AddColumn("write help to get controls"); helpPanel.Collapse(); helpPanel.Alignment(Justify.Right); helpPanel.RightAligned(); helpPanel.HeavyBorder(); AnsiConsole.Render(helpPanel); Properties.PageLength = 100; } List <Command> commands = new List <Command>(); // создаем список доступных команд commands.Add(new GoToCommand()); commands.Add(new CopyCommand()); commands.Add(new DeleteCommand()); commands.Add(new InfoCommand()); commands.Add(new HelpCommand()); commands.Add(new PageCommand()); while (true) { var table = new Table(); userCommand = AnsiConsole.Ask <string>("Command Line:"); string userCommandToLowerCase = userCommand.ToLower(); if (userCommandToLowerCase == "exit") // комманда выведена отдельно вне списка т.к. не имеет аргументов и исполняется в одну строку { break; } else if (userCommandToLowerCase == "up") //тоже вне спика т.к. нет аргументов и метод исполнения внутри класса PrintList { printList.GoUp(); } var parsedCommand = Regex.Match(userCommandToLowerCase, @"^([\w\-]+)").ToString(); // считывание команды var parsedArgument = userCommandToLowerCase.Split(' ', 2).Skip(1).FirstOrDefault(); // считывание аргумента foreach (Command command in commands) { if (command.CanHandle(parsedCommand)) { command.Handle(parsedArgument); } } } lastStateSave = Directory.GetCurrentDirectory(); properties.Save(lastStateSave, Properties.PageLength); // сохранение настроек при завершении программы }
public CommandOutputLogger(CommandOutputProvider commandOutputProvider, string loggerName, bool useConsoleColor) { _provider = commandOutputProvider; _outConsole = AnsiConsole.GetOutput(useConsoleColor); _loggerName = loggerName; }
public override int Execute(CommandContext context, LegacySettings options) { var args = options.Command ?? context.Remaining.Raw; // Start logic var profilerEnvironmentVariables = Utils.GetProfilerEnvironmentVariables( ApplicationContext.RunnerFolder, ApplicationContext.Platform, options); if (profilerEnvironmentVariables is null) { return(1); } // We try to autodetect the CI Visibility Mode if (!options.EnableCIVisibilityMode) { // Support for VSTest.Console.exe and dotcover if (args.Count > 0 && ( string.Equals(args[0], "VSTest.Console", StringComparison.OrdinalIgnoreCase) || string.Equals(args[0], "dotcover", StringComparison.OrdinalIgnoreCase))) { options.EnableCIVisibilityMode = true; } // Support for dotnet test and dotnet vstest command if (args.Count > 1 && string.Equals(args[0], "dotnet", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(args[1], "test", StringComparison.OrdinalIgnoreCase) || string.Equals(args[1], "vstest", StringComparison.OrdinalIgnoreCase)) { options.EnableCIVisibilityMode = true; } } } if (options.EnableCIVisibilityMode) { // Enable CI Visibility mode by configuration profilerEnvironmentVariables[Configuration.ConfigurationKeys.CIVisibility.Enabled] = "1"; } if (options.SetEnvironmentVariables) { AnsiConsole.WriteLine("Setting up the environment variables."); CIConfiguration.SetupCIEnvironmentVariables(profilerEnvironmentVariables, null); } else if (!string.IsNullOrEmpty(options.CrankImportFile)) { return(Crank.Importer.Process(options.CrankImportFile)); } else { string cmdLine = string.Join(' ', args); if (!string.IsNullOrWhiteSpace(cmdLine)) { // CI Visibility mode is enabled. // If the agentless feature flag is enabled, we check for ApiKey // If the agentless feature flag is disabled, we check if we have connection to the agent before running the process. if (options.EnableCIVisibilityMode) { var ciVisibilitySettings = Ci.Configuration.CIVisibilitySettings.FromDefaultSources(); if (ciVisibilitySettings.Agentless) { if (string.IsNullOrWhiteSpace(ciVisibilitySettings.ApiKey)) { Utils.WriteError("An API key is required in Agentless mode."); return(1); } } else if (!Utils.CheckAgentConnectionAsync(options.AgentUrl).GetAwaiter().GetResult()) { return(1); } } AnsiConsole.WriteLine("Running: " + cmdLine); var arguments = args.Count > 1 ? string.Join(' ', args.Skip(1).ToArray()) : null; if (Program.CallbackForTests != null) { Program.CallbackForTests(args[0], arguments, profilerEnvironmentVariables); return(0); } var processInfo = Utils.GetProcessStartInfo(args[0], Environment.CurrentDirectory, profilerEnvironmentVariables); if (args.Count > 1) { processInfo.Arguments = arguments; } return(Utils.RunProcess(processInfo, ApplicationContext.TokenSource.Token)); } } return(0); }
public void Run() { Console.WriteLine("Welcome to the import data checker!"); var folder = new DirectoryInfo(_workpath); var successFolder = folder.Parent.CreateSubdirectory("Success"); Console.WriteLine("We will now process each folder to check if they contain the correct file!"); var requiredFiles = new string[] { "amusement.csv", "ov.csv", "stad.csv", "twitter.csv", "weer.csv" }; DirectoryInfo[] directories = folder.GetDirectories(); var dirLength = directories.Length - 1; List <DirectoryInfo> directoriesFailed = new List <DirectoryInfo>(); for (int i = 0; i <= dirLength; i++) { DirectoryInfo item = directories[i]; if (requiredFiles.All(x => item.GetFiles().Any(c => x == c.Name.ToLower()))) { if (!Directory.Exists($@"{successFolder}\{item.Name}")) { Directory.CreateDirectory($@"{successFolder}\{item.Name}"); } foreach (var reqFile in requiredFiles) { var f = item.GetFiles().Where(c => c.Name.ToLower() == reqFile).FirstOrDefault(); f.MoveTo($@"{successFolder}\{item.Name}\{reqFile}"); } Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found correctly."); } else { directoriesFailed.Add(item); Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found incorrectly and has been moved to the next round!."); } } Console.WriteLine("Next round! begin!"); Console.WriteLine("We will browse the subfolders too to find the correct files!"); dirLength = directoriesFailed.Count - 1; List <DirectoryInfo> directoriesFailedTwice = new List <DirectoryInfo>(); for (int i = 0; i <= dirLength; i++) { DirectoryInfo item = directoriesFailed[i]; var allFiles = item.GetFiles().ToList(); allFiles.AddRange(recursiveFolderLoop(item)); if (requiredFiles.All(x => allFiles.Any(c => x == c.Name.ToLower()))) { if (!Directory.Exists($@"{successFolder}\{item.Name}")) { Directory.CreateDirectory($@"{successFolder}\{item.Name}"); } foreach (var reqFile in requiredFiles) { var f = allFiles.Where(c => c.Name.ToLower() == reqFile).FirstOrDefault(); f.MoveTo($@"{successFolder}\{item.Name}\{reqFile}"); } Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found correctly."); } else { directoriesFailedTwice.Add(item); Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found incorrectly and has been moved to the next round!."); } } Console.WriteLine("Next round! begin!"); Console.WriteLine("We will browse the subfolders too to find the correct files AND check if it's part of the name!"); dirLength = directoriesFailedTwice.Count - 1; List <DirectoryInfo> directoriesFailedThrice = new List <DirectoryInfo>(); requiredFiles = requiredFiles.Select(c => c.Substring(0, c.IndexOf('.'))).ToArray(); for (int i = 0; i <= dirLength; i++) { DirectoryInfo item = directoriesFailed[i]; var allFiles = item.GetFiles().ToList(); allFiles.AddRange(recursiveFolderLoop(item)); if (requiredFiles.All(x => allFiles.Any(c => c.Name.ToLower().Contains(x)))) { if (!Directory.Exists($@"{successFolder}\{item.Name}")) { Directory.CreateDirectory($@"{successFolder}\{item.Name}"); } foreach (var reqFile in requiredFiles) { var f = allFiles.Where(c => c.Name.ToLower().Contains(reqFile)).FirstOrDefault(); f.MoveTo($@"{successFolder}\{item.Name}\{reqFile}.csv"); } Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found correctly."); } else { directoriesFailedThrice.Add(item); Console.WriteLine($"[{i}/{dirLength}]: {item.Name} Has been found incorrectly and has been moved to the next round!."); } } Console.WriteLine("Well... that was a rollercoaster."); Console.WriteLine($"Here are the {directoriesFailedThrice.Count - 1} failing failing the three tests..."); var resultInspect = AnsiConsole.Prompt( new MultiSelectionPrompt <DirectoryInfo>() .Title("Please select the one you want to inspect.") .NotRequired() .PageSize(10) .AddChoices(directoriesFailedThrice.ToArray()) .UseConverter(c => c.Name)); foreach (var item in resultInspect) { Console.WriteLine($"{item.Name}:"); var allFiles = recursiveFolderLoop(item); foreach (var file in allFiles) { Console.WriteLine(file.Name); } } }
private static async Task MainAsync() { var portfolioRepository = await PortfolioEventStoreStream.Factory(); var key = string.Empty; while (key != "X") { AnsiConsole.Clear(); PrintMenuItem("Deposit", ConsoleColor.DarkRed); PrintMenuItem("Withdraw", ConsoleColor.DarkCyan); PrintMenuItem("Buy Stock", ConsoleColor.DarkGray); PrintMenuItem("Sell Stock", ConsoleColor.DarkGreen); PrintMenuItem("Portfolio", ConsoleColor.DarkYellow); PrintMenuItem("Events", ConsoleColor.Yellow); AnsiConsole.Write("> "); key = Console.ReadLine()?.ToUpperInvariant(); AnsiConsole.WriteLine(); var username = GetUsername(); var portfolio = await portfolioRepository.Get(username); switch (key) { case "D": var moneyToDeposit = GetAmount(); portfolio.Deposit(moneyToDeposit); AnsiConsole.WriteLine($"{username} Received: {moneyToDeposit}"); break; case "W": var moneyToWithdraw = GetAmount(); portfolio.Withdrawal(moneyToWithdraw); AnsiConsole.WriteLine($"{username} Withdrew: {moneyToWithdraw}"); break; case "P": AnsiConsole.WriteLine($"Money: {portfolio.GetState().Money:0.##}"); if (portfolio.GetState().Shares != null) { foreach (var stockOwned in portfolio.GetState().Shares) { AnsiConsole.WriteLine($"Stock Ticker: {stockOwned.Key} Quantity: {stockOwned.Value.NumberOfShares} Average Price: {stockOwned.Value.Price:0.##} Profit: {portfolio.GetState().Profit:0.##}"); } } break; case "B": var amountOfSharesToBuy = GetAmount(); var stock = GetStock(); var price = GetPrice(); portfolio.BuyShares(stock, amountOfSharesToBuy, price); AnsiConsole.WriteLine($"{username} Bought: {stock} Amount: {amountOfSharesToBuy} Price: {price:0.##}"); break; case "S": var amountOfSharesToSell = GetAmount(); stock = GetStock(); price = GetPrice(); portfolio.SellShares(stock, amountOfSharesToSell, price); AnsiConsole.WriteLine($"{username} Sold: {stock} Amount: {amountOfSharesToSell} Price: {price:0.##}"); break; case "E": var events = await portfolioRepository.GetAllEvents(username); Console.WriteLine($"Events: {username}"); foreach (var evnt in events) { switch (evnt) { case SharesSold sharesSold: AnsiConsole.WriteLine($"[{sharesSold.DateTime}] {sharesSold.Amount} shares SOLD from {sharesSold.Stock} at Price {sharesSold.Price:0.##}"); break; case SharesBought sharesBought: AnsiConsole.WriteLine($"[{sharesBought.DateTime}] {sharesBought.Amount} shares BOUGHT from {sharesBought.Stock} at Price {sharesBought.Price:0.##}"); break; case DepositMade depositMade: AnsiConsole.WriteLine($"[{depositMade.DateTime}] {depositMade.Amount} EUR DEPOSIT"); break; case WithdrawalMade withdrawalMade: AnsiConsole.WriteLine($"[{withdrawalMade.DateTime}] {withdrawalMade.Amount} EUR WITHDRAWAL"); break; } } break; } await portfolioRepository.Save(portfolio); AnsiConsole.WriteLine(); Console.ReadLine(); } }
new = Reporter(AnsiConsole.GetOutput());