private static Command richList() { List <Post> Posts = new List <Post>(); var client = new HttpClient(); var task = client.GetAsync("https://jsonplaceholder.typicode.com/posts") .ContinueWith((taskwithresponse) => { var response = taskwithresponse.Result; var jsonString = response.Content.ReadAsStringAsync(); jsonString.Wait(); Posts = JsonConvert.DeserializeObject <List <Post> >(jsonString.Result); }); task.Wait(); var cmd = new Command("list"); cmd.Handler = CommandHandler.Create(() => { var table = new TableView <Post> { Items = Posts.Take(20).ToList() }; table.AddColumn(user => user.ID, "ID"); table.AddColumn(user => user.Title, "Title"); var screen = new ScreenView(_consoleRenderer, _invocationContext.Console) { Child = table }; screen.Render(); }); return(cmd); }
public Command NewProject(List <Projects> repositories, InvocationContext invocationContext, ConsoleRenderer consoleRenderer) { var cmd = new Command("new", "Comando para criar um novo projeto"); foreach (var command in repositories) { var repositoryCommad = new Command(command.Description, $"Comando para criar um projeto à partir do template {command.Description}"); repositoryCommad.AddOption(new Option(new[] { "--name", "-n" }, "Nome da solução") { Argument = new Argument <string> { Arity = ArgumentArity.ExactlyOne } }); repositoryCommad.Handler = CommandHandler.Create <string>((name) => { if (string.IsNullOrEmpty(name)) { Console.WriteLine("Usage: new [template] [options]"); Console.WriteLine("\n"); Console.WriteLine("Options:"); Console.WriteLine("-n, --name <NomeDoSeuProjeto>"); return; } CreateProject(name, command.Url); }); cmd.Add(repositoryCommad); } cmd.Handler = CommandHandler.Create(() => { var table = new TableView <Projects> { Items = repositories }; Console.WriteLine("\n"); Console.WriteLine("Usage: new [template]"); Console.WriteLine("\n"); table.AddColumn(template => template.Description, "Template"); var screen = new ScreenView(consoleRenderer, invocationContext.Console) { Child = table }; screen.Render(); Console.WriteLine("-----"); Console.WriteLine("\n"); Console.WriteLine("Exemples:"); Console.WriteLine($" CodInsightsCLI new { repositories[0].Description } --name NomeDoSeuProjeto"); }); return(cmd); }
private static Command listCommand() { var command = new Command("list"); command.Description = "list all your albums"; command.AddOption(new Option("--search", "provide a text that is in the album title.", new Argument <string>())); command.Handler = CommandHandler.Create <string>(async(s) => { if (!String.IsNullOrWhiteSpace(s)) { // TODO: implement search throw new NotImplementedException("The search option isn't implemented yet."); } await graphService.Login(); var albumService = new AlbumService(graphService); var result = await albumService.GetAlbums(); var console = new SystemConsole(); var tableView = new TableView <Album>() { Items = (await albumService.GetAlbums()).ToList() }; tableView.AddColumn(a => a.name, "Name"); tableView.AddColumn(a => a.createdDateTime.ToLocalTime().ToLongDateString(), "created"); tableView.AddColumn(a => a.createdBy.user.displayName, "Author"); tableView.AddColumn(a => a.lastModifiedDateTime.ToLocalTime().ToLongDateString(), "modifed"); tableView.AddColumn(A => A.lastModifiedBy.user.displayName, "last Author"); var consoleRenderer = new ConsoleRenderer(console); var screen = new ScreenView(consoleRenderer) { Child = tableView }; screen.Render(); }); return(command); }
static void Main(InvocationContext context, DirectoryInfo argument = null) { argument ??= new DirectoryInfo("."); var consoleRenderer = new ConsoleRenderer( context.Console, context.BindingContext.OutputMode(), true); var tableView = new TableView <FileInfo> { Items = argument.EnumerateFiles().ToList() }; tableView.AddColumn(f => f.Name, "Name"); tableView.AddColumn(f => f.LastWriteTime, "Modified"); tableView.AddColumn(f => f.Length, "Size"); var screen = new ScreenView(consoleRenderer, context.Console) { Child = tableView }; screen.Render(); }
private static void RenderFrequencyTable(Dictionary <string, int> referenceHistogram, IConsole console) { Dictionary <int, int> referenceCountHistogram = new Dictionary <int, int>(); foreach (var(_, count) in referenceHistogram) { referenceCountHistogram.AddRange(count); } var normalizedFactor = (int)Math.Ceiling(referenceCountHistogram.Values.Max() / 50.0); var lines = referenceCountHistogram .GroupBy(kvp => kvp.Key) .OrderByDescending(x => x.Key) .SelectMany(x => x) .Where(x => x.Value / normalizedFactor > 1); var view = new TableView <KeyValuePair <int, int> > { Items = lines.ToArray() }; view.AddColumn(cellValue: x => x.Key, header: new ContentView("# of References".Underline())); view.AddColumn(cellValue: x => string.Join("", Enumerable.Repeat("*", x.Value / normalizedFactor)), new ContentView("Frequency".Underline())); var consoleRenderer = new ConsoleRenderer(console, mode: console.GetTerminal().DetectOutputMode(), resetAfterRender: true); var screen = new ScreenView(renderer: consoleRenderer, console) { Child = view }; screen.Render(new Region(0, 0, width: Console.WindowWidth, height: int.MaxValue)); console.GetTerminal().ShowCursor(); }
private static void RenderReferenceTable(Dictionary <string, int> referenceHistogram, int?numberOfRows, IConsole console) { var lines = referenceHistogram .GroupBy(kvp => kvp.Value) .OrderByDescending(x => x.Key) .SelectMany(x => x); if (numberOfRows is int rows) { lines = lines.Take(rows); } var view = new TableView <KeyValuePair <string, int> > { Items = lines.ToArray() }; view.AddColumn(cellValue: x => Path.GetFileName(x.Key).Replace("\"", ""), new ContentView("Assembly Name".Underline())); view.AddColumn(cellValue: x => x.Value, new ContentView("Times Projects Referenced This Assemby".Underline())); var consoleRenderer = new ConsoleRenderer(console, mode: console.GetTerminal().DetectOutputMode(), resetAfterRender: true); var screen = new ScreenView(renderer: consoleRenderer, console) { Child = view }; screen.Render(new Region(0, 0, width: Console.WindowWidth, height: int.MaxValue)); console.GetTerminal().ShowCursor(); }
public void RenderReport(BaseReportView baseViewModel) { CrashReportView viewModel = (CrashReportView)baseViewModel; var region = new Region(0, 0, 1080, 10800, true); var console = _invocationContext; if (console is ITerminal terminal) { terminal.Clear(); } console.Append(new ContentView("Dump details")); console.Append(new SplitterView()); console.Append(new DumpDetailsView(viewModel)); StackLayoutView stackLayoutView2 = new StackLayoutView { new TemplateStackView("Thread details", new ThreadsDetailView(viewModel)), new TemplateStackView("Threads with exceptions", new StackFramesStackView(viewModel)), new SplitterView() }; var screen = new ScreenView(_consoleRenderer, _invocationContext) { Child = stackLayoutView2 }; screen.Render(region); }
/// <summary> /// The RenderTableData. /// </summary> /// <param name="avDatas">The avDatas<see cref="List{AvData}"/>.</param> /// <param name="serviceProvider">The serviceProvider<see cref="IServiceProvider"/>.</param> public static void RenderTableData(List <AvData> avDatas, IServiceProvider serviceProvider) { var region = new Region(0, 0, Console.WindowWidth, Console.WindowHeight, false); var context = serviceProvider.GetService <InvocationContext>(); var console = context.Console; if (console is ITerminal terminal) { terminal.Clear(); } var consoleRenderer = new ConsoleRenderer( console, mode: context.BindingContext.OutputMode(), resetAfterRender: true); var tableView = new TableView <AvData> { Items = avDatas }; tableView.AddColumn(data => $"{data.Title.Shorten(8)}", "Title"); tableView.AddColumn(data => $"{data.Number}", "Number"); tableView.AddColumn(data => $"{data.Time}", "Time"); tableView.AddColumn(data => $"{data.Actors?.Join(",")}", "Actors"); tableView.AddColumn(data => $"{data.Tags?.Join(",")}", "Tags"); //table.AddColumn(process => ContentView.FromObservable(process.TrackCpuUsage(), x => $"{x.UsageTotal:P}"), "CPU", ColumnDefinition.Star(1)); var screen = new ScreenView(renderer: consoleRenderer, console) { Child = tableView }; screen.Render(region); }
public void Render_hides_the_cursor() { var screen = new ScreenView(_renderer, _terminal, _synchronizationContext); screen.Render(); _terminal.Events.Should().BeEquivalentSequenceTo(new TestTerminal.CursorHidden()); }
public void Rendering_without_a_child_view_should_not_throw() { var screen = new ScreenView(_renderer, _synchronizationContext); Action renderAction = () => screen.Render(); renderAction.Should().NotThrow(); }
static void UpdateUi(List <Capture> items) { var captureView = new CaptureView(items); Screen = new ScreenView(Renderer, Console) { Child = captureView }; Screen.Render(Region); }
private static void RenderView <T>(ItemsView <T> view) { var context = Program.InvocationContext; var consoleRenderer = new ConsoleRenderer( context.Console, context.BindingContext.OutputMode()); var screen = new ScreenView(consoleRenderer, context.Console) { Child = view }; screen.Render(new Region(0, 0, new Size(Console.WindowWidth, view.Items.Count + 1))); screen.Dispose(); Console.WriteLine("\n"); }
public static async Task Handler(InvocationContext invocationContext, Uri fhirServer) { var region = new Region( 0, 0, Console.WindowWidth, Console.WindowHeight, true); var httpClient = new HttpClient { BaseAddress = fhirServer, }; var jsonResult = await httpClient.GetStringAsync(new Uri("/_schema/versions")); List <JToken> resultsJson = JArray.Parse(jsonResult).ToList(); var tableView = new TableView <JToken> { Items = resultsJson, }; tableView.AddColumn( cellValue: f => f["id"], header: new ContentView("Version")); tableView.AddColumn( cellValue: f => f["script"], header: new ContentView("Script")); var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); var screen = new ScreenView(renderer: consoleRenderer) { Child = tableView }; screen.Render(region); }
/// <summary> /// Execute the list command /// </summary> public override Task <int> InvokeAsync(InvocationContext context) { var store = new BackupStore(Options.Server, Microsoft.Extensions.Options.Options.Create(Options.GetBackupStoreSettings())); _ = Options.SourceServer ?? throw new NotSupportedException("The source server must be defined."); _ = Options.SourceDatabase ?? throw new NotSupportedException("The source database must be defined."); IEnumerable <BackupHeader> backups = store.GetLatestBackupSet ( Options.SourceServer, Options.SourceDatabase, Options.BackupType == BackupRestoreType.Diff || Options.BackupType == BackupRestoreType.All, Options.BackupType == BackupRestoreType.Log || Options.BackupType == BackupRestoreType.All, Options.Before ); DatabaseRestore?restore = backups.Any() ? new DatabaseRestore( Options.Server, Options.Database, backups, null, ServiceProvider.GetRequiredService <ILogger <DatabaseRestore> >()) : null; var view = new RestoreView(backups, Options); view.Initialize(); if (!Options.Silent) { _ = context.Console ?? throw new ArgumentException("Console property is null", nameof(context)); using var screen = new ScreenView(ConsoleRenderer, context.Console) { Child = view }; screen.Render(); } if (restore != null) { restore.Execute(); return(Task.FromResult(0)); } else { return(Task.FromResult(-1)); } }
public void RenderReport(BaseReportView baseViewModel) { MemoryReportView viewModel = (MemoryReportView)baseViewModel; var region = new Region(0, 0, 1080, 10800, true); var console = _invocationContext; if (console is ITerminal terminal) { terminal.Clear(); } console.Append(new ContentView("Dump details")); console.Append(new SplitterView()); console.Append(new DumpDetailsView(viewModel)); console.Append(new ContentView("\n\n")); StackLayoutView stackLayoutView2 = new StackLayoutView { new SplitterView(), new ContentView($"Total GC Heap Size: {viewModel.TotalGCMemory}"), new SplitterView(), new ContentView("\n\n"), new TemplateStackView("GC split per logical heap", new HeapBalanceView(viewModel)), new TemplateStackView("Memory stats per GC type", new GCHeapBreakupView(viewModel)), new TemplateStackView("LOH stats", new LOHView(viewModel)), new TemplateStackView("Finalizer Object Stats", new FinalizerView(viewModel)), new TemplateStackView("Top 50 Types consumig memory", new HeapStatsView(viewModel)), new SplitterView() }; var screen = new ScreenView(_consoleRenderer, _invocationContext) { Child = stackLayoutView2 }; screen.Render(region); }
public void List() { var consoleRenderer = new ConsoleRenderer(Console); var protobufElements = Project.GetItems(ProtobufElement).ToList(); var table = new TableView <ProjectItem> { Items = protobufElements }; // Required columns (always displayed) table.AddColumn(r => r.UnevaluatedInclude, CoreStrings.TableColumnProtobufReference); table.AddColumn(r => { var serviceType = r.GetMetadataValue(GrpcServicesElement); return(string.IsNullOrEmpty(serviceType) ? "Both" : serviceType); }, CoreStrings.TableColumnServiceType); // Optional columns (only displayed if an element is not default) if (protobufElements.Any(r => !string.IsNullOrEmpty(r.GetMetadataValue(SourceUrlElement)))) { table.AddColumn(r => r.GetMetadataValue(SourceUrlElement), CoreStrings.TableColumnSourceUrl); } // The default value is Public set by Grpc.Tools so skip this column if everything is default if (protobufElements.Any(r => !string.Equals(r.GetMetadataValue(AccessElement), Access.Public.ToString(), StringComparison.OrdinalIgnoreCase))) { table.AddColumn(r => r.GetMetadataValue(AccessElement), CoreStrings.TableColumnAccess); } if (protobufElements.Any(r => !string.IsNullOrEmpty(r.GetMetadataValue(AdditionalImportDirsElement)))) { table.AddColumn(r => r.GetMetadataValue(AdditionalImportDirsElement), CoreStrings.TableColumnAdditionalImports); } var screen = new ScreenView(consoleRenderer, Console) { Child = table }; screen.Render(new Region(0, 0, System.Console.WindowWidth, System.Console.WindowWidth)); }
private async Task HandlerAsync(InvocationContext invocationContext, Uri server, CancellationToken cancellationToken) { var availableVersions = await _schemaManager.GetAvailableSchema(server, cancellationToken); var region = new Region( 0, 0, Console.WindowWidth, Console.WindowHeight, true); var tableView = new TableView <AvailableVersion> { Items = new ReadOnlyCollection <AvailableVersion>(availableVersions), }; tableView.AddColumn( cellValue: availableVersion => availableVersion.Id, header: new ContentView("Version")); tableView.AddColumn( cellValue: availableVersion => availableVersion.ScriptUri, header: new ContentView("Script")); tableView.AddColumn( cellValue: availableVersion => string.IsNullOrEmpty(availableVersion.DiffUri) ? "N/A" : availableVersion.DiffUri, header: new ContentView("Diff")); var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); using (var screen = new ScreenView(renderer: consoleRenderer)) { screen.Child = tableView; screen.Render(region); } }
private async Task HandlerAsync(InvocationContext invocationContext, string connectionString, Uri server, CancellationToken cancellationToken = default) { var region = new Region( 0, 0, Console.WindowWidth, Console.WindowHeight, true); IList <CurrentVersion> currentVersions = await _schemaManager.GetCurrentSchema(connectionString, server, cancellationToken).ConfigureAwait(false); var tableView = new TableView <CurrentVersion> { Items = new ReadOnlyCollection <CurrentVersion>(currentVersions), }; tableView.AddColumn( cellValue: currentVersion => currentVersion.Id, header: new ContentView("Version")); tableView.AddColumn( cellValue: currentVersion => currentVersion.Status, header: new ContentView("Status")); tableView.AddColumn( cellValue: currentVersion => string.Join(", ", currentVersion.Servers), header: new ContentView("Servers")); var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); using var screen = new ScreenView(renderer: consoleRenderer) { Child = tableView }; screen.Render(region); }
/// <summary> /// invoke as an asynchronous operation. /// </summary> /// <param name="context">The context.</param> /// <returns>System.Int32.</returns> /// <exception cref="ArgumentException">Console property is null - context.</exception> /// <exception cref="FileNotFoundException">File name not defined.</exception> /// <autogeneratedoc/> public async Task <int> InvokeAsync(InvocationContext context) { var view = new QueryCommandView(Options); view.Initialize(); _ = context.Console ?? throw new ArgumentException("Console property is null", nameof(context)); using var screen = new ScreenView(ConsoleRenderer, context.Console) { Child = view, }; screen.Render(); try { using Server server = new Server(Options.Server ?? string.Empty, Options.PersonalAccessToken ?? string.Empty); server.Connect(); var project = new Project(server, Options.Project ?? string.Empty); var id = project.Id; using var query = new EffortQuery(project, Options.Query ?? string.Empty, Options.ActivityOrder ?? new List <string>(), Options.ParentDepth ?? 0); var export = new Export(query); await export.ToFile(Options.OutputFile ?? throw new FileNotFoundException("File name not defined."), Options.Culture); } catch (Exception e) { Exception?inner = e; string message = e.Message; while ((inner = inner.InnerException) != null) { message += "\n" + e.Message; } Logger.LogError(0, e, message); throw; } return(0); }
public static async Task HandlerAsync(InvocationContext invocationContext, Uri server, string connectionString, CancellationToken cancellationToken = default) { var region = new Region( 0, 0, Console.WindowWidth, Console.WindowHeight, true); List <CurrentVersion> currentVersions = null; ISchemaClient schemaClient = new SchemaClient(server); try { // Base schema is required to run the schema migration tool. // This method also initializes the database if not initialized yet. await BaseSchemaRunner.EnsureBaseSchemaExistsAsync(connectionString, cancellationToken); // If InstanceSchema table is just created(as part of baseSchema), it takes a while to insert a version record // since the Schema job polls and upserts at the specified interval in the service. await BaseSchemaRunner.EnsureInstanceSchemaRecordExistsAsync(connectionString, cancellationToken); currentVersions = await schemaClient.GetCurrentVersionInformationAsync(cancellationToken); } catch (SchemaManagerException ex) { CommandUtils.PrintError(ex.Message); return; } catch (HttpRequestException) { CommandUtils.PrintError(string.Format(Resources.RequestFailedMessage, server)); return; } var tableView = new TableView <CurrentVersion> { Items = currentVersions, }; tableView.AddColumn( cellValue: currentVersion => currentVersion.Id, header: new ContentView("Version")); tableView.AddColumn( cellValue: currentVersion => currentVersion.Status, header: new ContentView("Status")); tableView.AddColumn( cellValue: currentVersion => string.Join(", ", currentVersion.Servers), header: new ContentView("Servers")); var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); using (var screen = new ScreenView(renderer: consoleRenderer)) { screen.Child = tableView; screen.Render(region); } }
static async Task <int> WatchAsync( StringLocalizer stringLocalizer, InvocationContext invocationContext, CancellationToken terminationToken, uint interval, bool plot, bool scan, byte scanRange, byte[] skip, bool hydra) { var console = new VirtualTerminal(invocationContext.Console, VirtualTerminalMode.TryEnable()); var reporter = new NvmeSmartAttributesReporter(stringLocalizer); var attributesProviderMap = new Dictionary <int, NvmeSmartAttributesProvider>(); try { try { if (!scan) { console.Out.Write(stringLocalizer["LOG_REGISTERING_PERFORMANCE_COUNTERS"]); reporter.CreateCategory(); } console.Out.Write(stringLocalizer["LOG_DETECTING_NVME_DRIVES"]); for (ushort driveNumber = 0; driveNumber < scanRange; ++driveNumber) { if (skip.Contains((byte)driveNumber)) { continue; } var attributesProvider = NvmeSmartAttributesProvider.Create((byte)driveNumber); if (attributesProvider == null) { continue; } if (attributesProvider.Query(out var _)) { attributesProviderMap.Add(driveNumber, attributesProvider); if (!scan) { reporter.AddInstance(attributesProvider.Moniker, attributesProvider.Model, attributesProvider.SerialNumber); } console.Out.Write($"\t{attributesProvider.Moniker.Replace("_", string.Empty)}: {attributesProvider.Model ?? stringLocalizer["NOT_AVAILABLE"]} (S/N: {attributesProvider.SerialNumber ?? stringLocalizer["NOT_AVAILABLE"]})\r\n"); } else { attributesProvider.Dispose(); } } if (attributesProviderMap.Count == 0) { console.Out.Write(stringLocalizer["LOG_CANNOT_DETECT_ANY_NVME_DRIVES"]); return(1); } if (scan) { return(0); } console.Out.Write(stringLocalizer["LOG_START_MONITORING"]); if (plot) { if (console is ITerminal terminal) { terminal.Clear(); terminal.SetCursorPosition(0, 0); terminal.HideCursor(); } var renderer = new ConsoleRenderer(console, invocationContext.BindingContext.OutputMode(), true); var table = new TableView <NvmeSmartAttributesReporterInstance>() { Items = reporter.Instances }; table.AddColumn(item => item.Moniker.Replace("_", string.Empty), new ContentView("#".Underline())); table.AddColumn(item => item.Model, new ContentView("Model".Underline())); table.AddColumn(item => item.SerialNumber, new ContentView("S/N".Underline())); table.AddColumn(item => ContentView.FromObservable(item.PercentageUsedEstimate, value => $"{value}%"), new ContentView("PUE".Underline())); table.AddColumn(item => ContentView.FromObservable(item.TemperatureDegCelsius, value => $"{value}°C"), new ContentView("CTemp".Underline())); table.AddColumn(item => ContentView.FromObservable(item.WarningCompositeTemperatureTime, value => $"{value} mins."), new ContentView("WCTemp".Underline())); table.AddColumn(item => ContentView.FromObservable(item.CriticalCompositeTemperatureTime, value => $"{value} mins."), new ContentView("CCTemp".Underline())); table.AddColumn(item => ContentView.FromObservable(item.HostReadCommands), new ContentView("HRC".Underline())); table.AddColumn(item => ContentView.FromObservable(item.HostWriteCommands), new ContentView("HWC".Underline())); table.AddColumn(item => ContentView.FromObservable(item.DataUnitsRead), new ContentView("DUR".Underline())); table.AddColumn(item => ContentView.FromObservable(item.DataUnitsWrite), new ContentView("DUW".Underline())); table.AddColumn(item => ContentView.FromObservable(item.MediaErrors), new ContentView("ME".Underline())); table.AddColumn(item => ContentView.FromObservable(item.NumberOfErrorInformationLogEntries), new ContentView("EE".Underline())); var screen = new ScreenView(renderer, console) { Child = table }; var region = new Region(0, 0, Console.WindowWidth, Console.WindowHeight, true); screen.Render(region); } while (!terminationToken.IsCancellationRequested) { foreach (var driveNumber in attributesProviderMap.Keys) { var attributesProvider = attributesProviderMap[driveNumber]; if (!attributesProvider.Query(out var attributes)) { console.Error.Write($"\t{attributesProvider.Moniker}: {stringLocalizer["LOG_FAILED_TO_QUERY_SMART"]}\n"); continue; } reporter.Next(attributesProvider.Moniker, attributes); } await Task.Delay((int)interval, terminationToken); } } finally { if (plot) { if (console is ITerminal terminal) { terminal.Clear(); terminal.SetCursorPosition(0, 0); terminal.ShowCursor(); } } console.Out.Write(stringLocalizer["LOG_QUITTING"]); if (!hydra) { reporter.DeleteCategory(); } reporter.Dispose(); foreach (var attributesProvider in attributesProviderMap.Values) { attributesProvider.Dispose(); } } } catch (TaskCanceledException) { } return(0); }
/// <summary> /// Demonstrates various rendering capabilities. /// </summary> /// <param name="invocationContext"></param> /// <param name="sample">Renders a specified sample</param> /// <param name="height">The height of the rendering area</param> /// <param name="width">The width of the rendering area</param> /// <param name="top">The top position of the render area</param> /// <param name="left">The left position of the render area</param> /// <param name="text">The text to render</param> /// <param name="overwrite">Overwrite the specified region. (If not, scroll.)</param> public static void Main( #pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) InvocationContext invocationContext, SampleName sample = SampleName.Dir, int?height = null, int?width = null, int top = 0, int left = 0, string text = null, bool overwrite = true) #pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { var region = new Region(left, top, width ?? Console.WindowWidth, height ?? Console.WindowHeight, overwrite); if (overwrite && invocationContext.Console is ITerminal terminal) { terminal.Clear(); } var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); switch (sample) { case SampleName.Colors: { var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console); screen.Child = new ColorsView(text ?? "*"); screen.Render(region); } break; case SampleName.Dir: var directoryTableView = new DirectoryTableView(new DirectoryInfo(Directory.GetCurrentDirectory())); directoryTableView.Render(consoleRenderer, region); break; case SampleName.Moby: consoleRenderer.RenderToRegion( $"Call me {StyleSpan.BoldOn()}{StyleSpan.UnderlinedOn()}Ishmael{StyleSpan.UnderlinedOff()}{StyleSpan.BoldOff()}. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and {ForegroundColorSpan.Rgb(60, 0, 0)}methodically{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(90, 0, 0)}knocking{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(120, 0, 0)}people's{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(160, 0, 0)}hats{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(220, 0, 0)}off{ForegroundColorSpan.Reset()} then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.", region); break; case SampleName.Processes: { var view = new ProcessesView(Process.GetProcesses()); view.Render(consoleRenderer, region); } break; case SampleName.TableView: { var table = new TableView <Process> { Items = Process.GetProcesses().Where(x => !string.IsNullOrEmpty(x.MainWindowTitle)).OrderBy(p => p.ProcessName).ToList() }; table.AddColumn(process => $"{process.ProcessName} ", "Name"); table.AddColumn(process => ContentView.FromObservable(process.TrackCpuUsage(), x => $"{x.UsageTotal:P}"), "CPU", ColumnDefinition.Star(1)); var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console) { Child = table }; screen.Render(); } break; case SampleName.Clock: { var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console); var lastTime = DateTime.Now; var clockObservable = new BehaviorSubject <DateTime>(lastTime); var clockView = ContentView.FromObservable(clockObservable, x => $"{x:T}"); screen.Child = clockView; screen.Render(); while (!Console.KeyAvailable) { if (DateTime.Now - lastTime > TimeSpan.FromSeconds(1)) { lastTime = DateTime.Now; clockObservable.OnNext(lastTime); } } } break; case SampleName.GridLayout: { var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console); var content = new ContentView( "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin."); var smallContent = new ContentView("Kevin Bost"); var longContent = new ContentView("Hacking on System.CommandLine"); var gridView = new GridView(); gridView.SetColumns( ColumnDefinition.SizeToContent(), ColumnDefinition.Star(1), ColumnDefinition.Star(0.5) ); gridView.SetRows( RowDefinition.Star(0.5), RowDefinition.Star(0.5) ); gridView.SetChild(smallContent, 0, 0); gridView.SetChild(longContent, 0, 1); //gridView.SetChild(content, 0, 0); gridView.SetChild(content, 1, 1); gridView.SetChild(content, 2, 0); screen.Child = gridView; screen.Render(); } break; default: if (!string.IsNullOrWhiteSpace(text)) { consoleRenderer.RenderToRegion( text, region); } else { var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console); var stackLayout = new StackLayoutView(); var content1 = new ContentView("Hello World!"); var content2 = new ContentView( "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin."); stackLayout.Add(content2); stackLayout.Add(content1); stackLayout.Add(content2); screen.Child = stackLayout; screen.Render(new Region(0, 0, 50, Size.MaxValue)); //screen.Render(writer); } break; } if (!Console.IsOutputRedirected) { Console.ReadKey(); } }
private async Task HandlerAsync(InvocationContext invocationContext, Uri server, CancellationToken cancellationToken) { var region = new Region( 0, 0, Console.WindowWidth, Console.WindowHeight, true); List <AvailableVersion> availableVersions = null; _schemaClient.SetUri(server); try { availableVersions = await _schemaClient.GetAvailabilityAsync(cancellationToken); // To ensure that schema version null/0 is not printed if (availableVersions.First().Id == 0) { availableVersions.RemoveAt(0); } } catch (SchemaManagerException ex) { CommandUtils.PrintError(ex.Message); return; } catch (HttpRequestException) { CommandUtils.PrintError(string.Format(Resources.RequestFailedMessage, server)); return; } var tableView = new TableView <AvailableVersion> { Items = availableVersions, }; tableView.AddColumn( cellValue: availableVersion => availableVersion.Id, header: new ContentView("Version")); tableView.AddColumn( cellValue: availableVersion => availableVersion.ScriptUri, header: new ContentView("Script")); tableView.AddColumn( cellValue: availableVersion => string.IsNullOrEmpty(availableVersion.DiffUri) ? "N/A" : availableVersion.DiffUri, header: new ContentView("Diff")); var consoleRenderer = new ConsoleRenderer( invocationContext.Console, mode: invocationContext.BindingContext.OutputMode(), resetAfterRender: true); using (var screen = new ScreenView(renderer: consoleRenderer)) { screen.Child = tableView; screen.Render(region); } }