├── logo.png ├── .github ├── FUNDING.yml └── workflows │ ├── test.yml │ └── publishnuget.yml ├── TextTableBuilder ├── ValueRow.cs ├── ObjectRow.cs ├── Align.cs ├── RenderColumn.cs ├── Row.cs ├── ObjectHandlers │ ├── IObjectHandler.cs │ ├── ColumnOrderAttribute.cs │ ├── ObjectHandlerCollection.cs │ ├── DelegatingObjectHandler.cs │ └── DefaultObjectHandler.cs ├── TypeHandlers │ ├── INullValueHandler.cs │ ├── ITypeHandler.cs │ ├── NaturalNumberHandler.cs │ ├── BoolHandler.cs │ ├── DefaultTypeHandler.cs │ ├── GuidHandler.cs │ ├── NaturalFractionalNumberHandler.cs │ ├── CharHandler.cs │ ├── IntHandler.cs │ ├── ByteHandler.cs │ ├── LongHandler.cs │ ├── UIntHandler.cs │ ├── SByteHandler.cs │ ├── ShortHandler.cs │ ├── ULongHandler.cs │ ├── UShortHandler.cs │ ├── FloatHandler.cs │ ├── DecimalHandler.cs │ ├── DoubleHandler.cs │ ├── SpecificFormatHandler.cs │ ├── TimeSpanHandler.cs │ ├── DateTimeHandler.cs │ ├── NullValueHandler.cs │ ├── DelegatingTypeHandler.cs │ └── TypeHandlerCollection.cs ├── TableRenderers │ ├── ITableRenderer.cs │ ├── MSDOSTableRenderer.cs │ ├── DefaultTableRenderer.cs │ ├── DotsTableRenderer.cs │ ├── HatchedTableRenderer.cs │ ├── DoubleLineTableRenderer.cs │ ├── SimpleLineTableRenderer.cs │ ├── SingleLineTableRenderer.cs │ ├── MinimalTableRenderer.cs │ ├── RoundedCornersTableRenderer.cs │ ├── SimpleTableRenderer.cs │ ├── BorderedTableRenderer.cs │ └── BaseTableRenderer.cs ├── IsExternalInit.cs ├── HandlerCollection.cs ├── TextTableBuilder.csproj ├── Column.cs ├── Table.cs └── TableBuilder.cs ├── DemoApp ├── DemoApp.csproj └── Program.cs ├── TextTableBuilder.Tests ├── TableBuilderTests.cs └── TextTableBuilder.Tests.csproj ├── LICENSE ├── .vscode ├── launch.json └── tasks.json ├── TextTableBuilder.sln ├── .gitattributes ├── .gitignore └── README.md /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RobThree/TextTableBuilder/HEAD/logo.png -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [RobThree] 2 | custom: ["https://paypal.me/robiii"] 3 | -------------------------------------------------------------------------------- /TextTableBuilder/ValueRow.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder; 2 | 3 | public record ValueRow(object?[] Values) : Row(); 4 | -------------------------------------------------------------------------------- /TextTableBuilder/ObjectRow.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder; 2 | 3 | public record ObjectRow( 4 | object Value 5 | ) : Row(); -------------------------------------------------------------------------------- /TextTableBuilder/Align.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder; 2 | 3 | public enum Align 4 | { 5 | Left, 6 | Right, 7 | Center 8 | } 9 | -------------------------------------------------------------------------------- /TextTableBuilder/RenderColumn.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder; 2 | 3 | public record RenderColumn(string Name, int Width, Align HeaderAlign, Align ValueAlign); -------------------------------------------------------------------------------- /TextTableBuilder/Row.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder; 2 | 3 | public abstract record Row() 4 | { 5 | public const Align DefaultAlign = Align.Left; 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/ObjectHandlers/IObjectHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.ObjectHandlers; 2 | public interface IObjectHandler 3 | { 4 | object?[] Handle(object value, int columnCount); 5 | } 6 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/INullValueHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public interface INullValueHandler 4 | { 5 | string Handle(IFormatProvider formatProvider); 6 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/ITypeHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public interface ITypeHandler 4 | { 5 | string Handle(object value, IFormatProvider formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/NaturalNumberHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public abstract class NaturalNumberHandler : SpecificFormatHandler 4 | { 5 | public NaturalNumberHandler() 6 | : base("N0") { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/BoolHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class BoolHandler : ITypeHandler 4 | { 5 | public string Handle(object value, IFormatProvider formatProvider) => ((bool)value).ToString(formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/DefaultTypeHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class DefaultTypeHandler : ITypeHandler 4 | { 5 | public string Handle(object value, IFormatProvider formatProvider) 6 | => value.ToString(); 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/GuidHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class GuidHandler : ITypeHandler 4 | { 5 | public string Handle(object value, IFormatProvider formatProvider) => ((Guid)value).ToString("D", formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/NaturalFractionalNumberHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public abstract class NaturalFractionalNumberHandler : SpecificFormatHandler 4 | { 5 | public NaturalFractionalNumberHandler() 6 | : base("N2") { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/CharHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class CharHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((char)value).ToString(formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/IntHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class IntHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((int)value).ToString(Format, formatProvider); 6 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/ITableRenderer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace TextTableBuilder.TableRenderers; 4 | 5 | public interface ITableRenderer 6 | { 7 | string Render(ReadOnlyCollection columns, IEnumerable rows); 8 | } 9 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/ByteHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class ByteHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((byte)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/LongHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class LongHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((long)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/UIntHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class UIntHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((uint)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/SByteHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class SByteHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((sbyte)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/ShortHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class ShortHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((short)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/ULongHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class ULongHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((ulong)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/UShortHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class UShortHandler : NaturalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((ushort)value).ToString(Format, formatProvider); 6 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/FloatHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class FloatHandler : NaturalFractionalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((float)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/DecimalHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class DecimalHandler : NaturalFractionalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((decimal)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/DoubleHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class DoubleHandler : NaturalFractionalNumberHandler 4 | { 5 | public override string Handle(object value, IFormatProvider formatProvider) => ((double)value).ToString(Format, formatProvider); 6 | } 7 | -------------------------------------------------------------------------------- /TextTableBuilder/ObjectHandlers/ColumnOrderAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.ObjectHandlers; 2 | 3 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] 4 | public class ColumnOrderAttribute : Attribute 5 | { 6 | public int Order { get; } 7 | 8 | public ColumnOrderAttribute(int order) => Order = order; 9 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/MSDOSTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class MSDOSTableRenderer : SimpleTableRenderer 4 | { 5 | public MSDOSTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base('║', '═', cellPadding, paddingChar) { } 7 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/DefaultTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class DefaultTableRenderer : SimpleTableRenderer 4 | { 5 | public DefaultTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base('|', '-', cellPadding, paddingChar) { } 7 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/DotsTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class DotsTableRenderer : BorderedTableRenderer 4 | { 5 | public DotsTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base("....::::.::....", cellPadding, paddingChar) { } 7 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/HatchedTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class HatchedTableRenderer : BorderedTableRenderer 4 | { 5 | public HatchedTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base(@"/-+\|||+-++\-+/", cellPadding, paddingChar) { } 7 | } -------------------------------------------------------------------------------- /TextTableBuilder/IsExternalInit.cs: -------------------------------------------------------------------------------- 1 | namespace System.Runtime.CompilerServices 2 | { 3 | using System.Diagnostics; 4 | using System.Diagnostics.CodeAnalysis; 5 | 6 | #if !ISEXTERNALINIT_INCLUDE_IN_CODE_COVERAGE 7 | [ExcludeFromCodeCoverage, DebuggerNonUserCode] 8 | #endif 9 | internal static class IsExternalInit 10 | { 11 | } 12 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/DoubleLineTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class DoubleLineTableRenderer : BorderedTableRenderer 4 | { 5 | public DoubleLineTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base("╔═╦╗║║║╠═╬╣╚═╩╝", cellPadding, paddingChar) { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/SimpleLineTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class SimpleLineTableRenderer : BorderedTableRenderer 4 | { 5 | public SimpleLineTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base("+-++|||+-+++-++", cellPadding, paddingChar) { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/SingleLineTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class SingleLineTableRenderer : BorderedTableRenderer 4 | { 5 | public SingleLineTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base("┌─┬┐│││├─┼┤└─┴┘", cellPadding, paddingChar) { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/MinimalTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class MinimalTableRenderer : SimpleTableRenderer 4 | { 5 | public MinimalTableRenderer(char columnSeparator = ' ', int cellPadding = 0, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base(columnSeparator, null, cellPadding, paddingChar) { } 7 | } 8 | -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/RoundedCornersTableRenderer.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TableRenderers; 2 | 3 | public class RoundedCornersTableRenderer : BorderedTableRenderer 4 | { 5 | public RoundedCornersTableRenderer(int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 6 | : base("╭─┬╮│││├─┼┤╰─┴╯", cellPadding, paddingChar) { } 7 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/SpecificFormatHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public abstract class SpecificFormatHandler : ITypeHandler 4 | { 5 | protected string Format { get; } 6 | public SpecificFormatHandler(string format) => Format = format; 7 | 8 | public abstract string Handle(object value, IFormatProvider formatProvider); 9 | } 10 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/TimeSpanHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class TimeSpanHandler : SpecificFormatHandler 4 | { 5 | public TimeSpanHandler(string format = @"hh\:mm\:ss") 6 | : base(format) { } 7 | 8 | public override string Handle(object value, IFormatProvider formatProvider) 9 | => ((TimeSpan)value).ToString(Format, formatProvider); 10 | } -------------------------------------------------------------------------------- /TextTableBuilder/ObjectHandlers/ObjectHandlerCollection.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.ObjectHandlers; 2 | 3 | public class ObjectHandlerCollection : HandlerCollection 4 | { 5 | public void AddHandler(Func func) => AddHandler(new DelegatingObjectHandler(func)); 6 | 7 | public ObjectHandlerCollection() => 8 | AddHandler(new DefaultObjectHandler()); 9 | } 10 | -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/DateTimeHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class DateTimeHandler : SpecificFormatHandler 4 | { 5 | public DateTimeHandler(string format = "yyyy-MM-dd HH:mm:ss") 6 | : base(format) { } 7 | 8 | public override string Handle(object value, IFormatProvider formatProvider) 9 | => ((DateTime)value).ToString(Format, formatProvider); 10 | } 11 | -------------------------------------------------------------------------------- /DemoApp/DemoApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | latest 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /TextTableBuilder.Tests/TableBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | 4 | namespace TextTableBuilder.Tests; 5 | 6 | [TestClass] 7 | public class TableBuilderTests 8 | { 9 | [TestMethod] 10 | public void Foo() 11 | { 12 | var table = new Table() 13 | .AddColumns(new[] { "A", "B", "C" }) 14 | .AddRow(1, Guid.NewGuid(), DateTime.Now); 15 | 16 | var tb = new TableBuilder(); 17 | var result = tb.Build(table); 18 | } 19 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/NullValueHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class NullValueHandler : INullValueHandler 4 | { 5 | public static readonly INullValueHandler Default = new NullValueHandler(); 6 | 7 | private readonly string _nullvalue; 8 | 9 | public NullValueHandler() 10 | : this(string.Empty) { } 11 | public NullValueHandler(string nullValue) 12 | => _nullvalue = nullValue; 13 | 14 | public string Handle(IFormatProvider formatProvider) => _nullvalue; 15 | } -------------------------------------------------------------------------------- /TextTableBuilder/ObjectHandlers/DelegatingObjectHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.ObjectHandlers; 2 | 3 | public class DelegatingObjectHandler : IObjectHandler 4 | { 5 | private readonly Func _delegate; 6 | 7 | public DelegatingObjectHandler(Func handlerFunction) 8 | => _delegate = handlerFunction ?? throw new ArgumentNullException(nameof(handlerFunction)); 9 | 10 | public object?[] Handle(object value, int columnCount) 11 | => _delegate((T)value, columnCount); 12 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/DelegatingTypeHandler.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class DelegatingTypeHandler : ITypeHandler 4 | { 5 | private readonly Func _delegate; 6 | 7 | public DelegatingTypeHandler(Func handlerFunction) 8 | => _delegate = handlerFunction ?? throw new ArgumentNullException(nameof(handlerFunction)); 9 | 10 | public string Handle(object value, IFormatProvider formatProvider) 11 | => _delegate((T)value, formatProvider); 12 | } -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push 5 | 6 | jobs: 7 | build: 8 | 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | dotnet-version: [ '8.0.x' ] 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | 17 | - name: Setup .NET ${{ matrix.dotnet-version }} 18 | uses: actions/setup-dotnet@v4 19 | with: 20 | dotnet-version: ${{ matrix.dotnet-version }} 21 | 22 | - name: Setup NuGet 23 | uses: NuGet/setup-nuget@v2 24 | 25 | - name: Restore dependencies 26 | run: dotnet restore 27 | 28 | - name: Run tests 29 | run: dotnet test --no-restore -------------------------------------------------------------------------------- /TextTableBuilder/HandlerCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | 3 | namespace TextTableBuilder; 4 | 5 | public abstract class HandlerCollection 6 | { 7 | private readonly ConcurrentDictionary _handlers = new(); 8 | 9 | public void AddHandler(Type type, T typeHandler) 10 | => _handlers.AddOrUpdate(type, typeHandler, (t, v) => typeHandler); 11 | public void AddHandler(T typeHandler) 12 | => AddHandler(typeof(THandler), typeHandler); 13 | 14 | public T GetHandler(Type type) 15 | => _handlers.TryGetValue(type, out var typeHandler) 16 | ? typeHandler 17 | : GetHandler(typeof(object)); 18 | } 19 | -------------------------------------------------------------------------------- /TextTableBuilder.Tests/TextTableBuilder.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /DemoApp/Program.cs: -------------------------------------------------------------------------------- 1 | using TextTableBuilder; 2 | using TextTableBuilder.TableRenderers; 3 | 4 | var table = new Table() 5 | .AddColumns("No", "Name", "Position", "^Salary^") 6 | .AddRow(1, "Bill Gates", "Founder Microsoft", 10000m) 7 | .AddRow(2, "Steve Jobs", "Founder Apple", 1200000m) 8 | .AddRow(3, "Larry Page", "Founder Google", 1100000m) 9 | .AddRow(4, "Mark Zuckerberg", "Founder Facebook", 1300000m); 10 | 11 | var renderers = new ITableRenderer[] { 12 | new DefaultTableRenderer(), 13 | new MinimalTableRenderer(), 14 | new MSDOSTableRenderer(), 15 | new SimpleLineTableRenderer(), 16 | new SingleLineTableRenderer(), 17 | new DoubleLineTableRenderer(), 18 | new RoundedCornersTableRenderer(), 19 | new HatchedTableRenderer(), 20 | new DotsTableRenderer() 21 | }; 22 | 23 | var tablebuilder = new TableBuilder() 24 | .AddTypeHandler((v, f) => $"$ {v:N2}"); 25 | 26 | foreach (var r in renderers) 27 | { 28 | Console.Write($"{r.GetType().Name}:\n\n"); 29 | Console.Write(tablebuilder.Build(table, r)); 30 | Console.Write("\n\n"); 31 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Rob Janssen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/publishnuget.yml: -------------------------------------------------------------------------------- 1 | name: Publish Nuget Package 2 | 3 | on: 4 | release: 5 | types: 6 | - created 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | dotnet-version: [ '8.0.x' ] 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Setup .NET ${{ matrix.dotnet-version }} 20 | uses: actions/setup-dotnet@v4 21 | with: 22 | dotnet-version: ${{ matrix.dotnet-version }} 23 | 24 | - name: Setup NuGet 25 | uses: NuGet/setup-nuget@v2 26 | 27 | - name: Restore dependencies 28 | run: dotnet restore 29 | 30 | - name: Build 31 | run: dotnet build -c Release --no-restore /p:Version="${{ github.event.release.tag_name }}" 32 | 33 | - name: Run tests 34 | run: dotnet test -c Release --no-restore --no-build 35 | 36 | - name: Create package 37 | run: dotnet pack ${{ github.event.repository.name }} -c Release --no-restore --no-build -p:Version="${{ github.event.release.tag_name }}" 38 | 39 | - name: Publish 40 | run: dotnet nuget push **\*.nupkg -s 'https://api.nuget.org/v3/index.json' -k ${{secrets.NUGET_API_KEY}} -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/DemoApp/bin/Debug/net6.0/DemoApp.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/DemoApp", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false, 19 | "logging": { 20 | "moduleLoad": false 21 | } 22 | }, 23 | { 24 | "name": ".NET Core Attach", 25 | "type": "coreclr", 26 | "request": "attach" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /TextTableBuilder/TextTableBuilder.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | enable 6 | enable 7 | latest 8 | true 9 | latest 10 | RobIII 11 | Devcorner.nl 12 | Simple, opinionated, modern table builder 13 | (C) 2022 - 2024 Devcorner.nl 14 | https://github.com/RobThree/TextTableBuilder 15 | logo.png 16 | https://github.com/RobThree/TextTableBuilder 17 | git 18 | text;table;simple 19 | README.md 20 | MIT 21 | 22 | 23 | 24 | 25 | True 26 | \ 27 | 28 | 29 | True 30 | \ 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/DemoApp/DemoApp.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/DemoApp/DemoApp.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "--project", 36 | "${workspaceFolder}/DemoApp/DemoApp.csproj" 37 | ], 38 | "problemMatcher": "$msCompile" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /TextTableBuilder/TypeHandlers/TypeHandlerCollection.cs: -------------------------------------------------------------------------------- 1 | namespace TextTableBuilder.TypeHandlers; 2 | 3 | public class TypeHandlerCollection : HandlerCollection 4 | { 5 | public INullValueHandler NullValueHandler { get; set; } = TypeHandlers.NullValueHandler.Default; 6 | 7 | public void AddHandler(Func func) => AddHandler(new DelegatingTypeHandler(func)); 8 | 9 | public TypeHandlerCollection() 10 | { 11 | AddHandler(new BoolHandler()); 12 | AddHandler(new ByteHandler()); 13 | AddHandler(new SByteHandler()); 14 | AddHandler(new CharHandler()); 15 | AddHandler(new DecimalHandler()); 16 | AddHandler(new DoubleHandler()); 17 | AddHandler(new FloatHandler()); 18 | AddHandler(new IntHandler()); 19 | AddHandler(new UIntHandler()); 20 | AddHandler(new LongHandler()); 21 | AddHandler(new ULongHandler()); 22 | AddHandler(new ShortHandler()); 23 | AddHandler(new UShortHandler()); 24 | AddHandler(new DateTimeHandler()); 25 | AddHandler(new TimeSpanHandler()); 26 | AddHandler(new GuidHandler()); 27 | AddHandler(new DefaultTypeHandler()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /TextTableBuilder/ObjectHandlers/DefaultObjectHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Reflection; 3 | 4 | namespace TextTableBuilder.ObjectHandlers; 5 | 6 | public class DefaultObjectHandler : IObjectHandler 7 | { 8 | private static readonly ConcurrentDictionary _propertycache = new(); 9 | private static readonly ConcurrentDictionary _columnordercache = new(); 10 | 11 | public object?[] Handle(object value, int columnCount) 12 | { 13 | // Get properties in correct order 14 | var props = _propertycache.GetOrAdd(value.GetType(), (t) => t 15 | .GetProperties(BindingFlags.Instance | BindingFlags.Public) 16 | .Where(p => p.CanRead) 17 | .OrderBy(p => _columnordercache.GetOrAdd(p, (pi) => pi.GetCustomAttribute()?.Order ?? int.MaxValue)) 18 | .ThenBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase) 19 | .ToArray() 20 | ); 21 | 22 | // Figure out if we need to pad our results with one or more (null) columns 23 | var padcols = columnCount > props.Length ? Enumerable.Repeat(null, columnCount - props.Length) : Array.Empty(); 24 | 25 | // Return property values (and optional padding) 26 | return props.Take(columnCount).Select(p => p.GetValue(value)).Concat(padcols).ToArray(); 27 | } 28 | } -------------------------------------------------------------------------------- /TextTableBuilder/Column.cs: -------------------------------------------------------------------------------- 1 | using TextTableBuilder.TypeHandlers; 2 | 3 | namespace TextTableBuilder; 4 | 5 | public record Column( 6 | string Name, 7 | Align HeaderAlign = Column.DefaultAlign, 8 | Align ValueAlign = Row.DefaultAlign, 9 | int? MinWidth = null, 10 | int? Width = null, 11 | ITypeHandler? TypeHandler = null 12 | ) 13 | { 14 | public const Align DefaultAlign = Align.Left; 15 | 16 | public static Column FromName(string name) 17 | { 18 | var calign = Column.DefaultAlign; 19 | var ralign = Row.DefaultAlign; 20 | 21 | if (name.Length > 1) 22 | { 23 | switch (name[0]) 24 | { 25 | case char s when s == '^' || s == '~': 26 | calign = GetAlignFromChar(name[0]); 27 | name = name.Substring(1); 28 | break; 29 | } 30 | } 31 | 32 | if (name.Length > 1) 33 | { 34 | switch (name[name.Length - 1]) 35 | { 36 | case char s when s == '^' || s == '~': 37 | ralign = GetAlignFromChar(name[name.Length - 1]); 38 | name = name.Substring(0, name.Length - 1); 39 | break; 40 | } 41 | } 42 | 43 | return new Column(name, calign, ralign); 44 | } 45 | 46 | private static Align GetAlignFromChar(char align) 47 | => align switch 48 | { 49 | '^' => Align.Right, 50 | '~' => Align.Center, 51 | _ => Align.Left 52 | }; 53 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/SimpleTableRenderer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Text; 3 | 4 | namespace TextTableBuilder.TableRenderers; 5 | 6 | public abstract class SimpleTableRenderer : BaseTableRenderer 7 | { 8 | private readonly char _paddingchar; 9 | private readonly char _columnseparator; 10 | private readonly char? _rowseparator; 11 | private readonly int _cellpadding; 12 | 13 | public SimpleTableRenderer(char columnSeparator, char? rowSeparator, int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 14 | { 15 | _paddingchar = paddingChar; 16 | _columnseparator = columnSeparator; 17 | _rowseparator = rowSeparator; 18 | _cellpadding = cellPadding; 19 | } 20 | 21 | public override string Render(ReadOnlyCollection columns, IEnumerable rows) 22 | { 23 | var sb = new StringBuilder(); 24 | 25 | // Headers 26 | sb.AppendLine(RenderRow(_columnseparator, columns.Select(c => RenderCell(c.Name, c.HeaderAlign, c.Width, _paddingchar, _cellpadding)))); 27 | 28 | // Header separator 29 | if (_rowseparator is not null) 30 | { 31 | sb.AppendLine(RenderRow(_columnseparator, columns.Select(c => new string(_rowseparator.Value, c.Width + (_cellpadding * 2))))); 32 | } 33 | 34 | // Rows 35 | foreach (var row in rows) 36 | { 37 | sb.AppendLine(RenderRow(_columnseparator, row.Select((value, i) => RenderCell(value, columns[i].ValueAlign, columns[i].Width, _paddingchar, _cellpadding)))); 38 | } 39 | return sb.ToString(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/BorderedTableRenderer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Text; 3 | 4 | namespace TextTableBuilder.TableRenderers; 5 | 6 | public class BorderedTableRenderer : BaseTableRenderer 7 | { 8 | private readonly string _chars; 9 | private readonly char _paddingchar; 10 | private readonly int _cellpadding; 11 | 12 | public BorderedTableRenderer(string borderChars, int cellPadding = DEFAULTCELLPADDING, char paddingChar = DEFAULTPADDINGCHAR) 13 | { 14 | if (borderChars.Length != 15) 15 | { 16 | throw new Exception($"{nameof(borderChars)} must be exactly 15 characters long"); 17 | } 18 | 19 | _chars = borderChars; 20 | _cellpadding = cellPadding; 21 | _paddingchar = paddingChar; 22 | } 23 | 24 | public override string Render(ReadOnlyCollection columns, IEnumerable rows) 25 | { 26 | var sb = new StringBuilder(); 27 | 28 | // Top border 29 | sb.AppendLine(RenderLine(_chars[0], _chars[2], _chars[3], _chars[1], columns, _cellpadding)); 30 | 31 | // Headers 32 | sb.AppendLine($"{_chars[4]}{RenderRow(_chars[5], columns.Select(c => RenderCell(c.Name, c.HeaderAlign, c.Width, _paddingchar, _cellpadding)))}{_chars[6]}"); 33 | 34 | // Header separator 35 | sb.AppendLine(RenderLine(_chars[7], _chars[9], _chars[10], _chars[8], columns, _cellpadding)); 36 | 37 | // Rows 38 | foreach (var row in rows) 39 | { 40 | sb.AppendLine($"{_chars[4]}{RenderRow(_chars[5], row.Select((value, i) => RenderCell(value, columns[i].ValueAlign, columns[i].Width, _paddingchar, _cellpadding)))}{_chars[6]}"); 41 | } 42 | 43 | // Bottom border 44 | sb.AppendLine(RenderLine(_chars[11], _chars[13], _chars[14], _chars[12], columns, _cellpadding)); 45 | return sb.ToString(); 46 | } 47 | } -------------------------------------------------------------------------------- /TextTableBuilder/TableRenderers/BaseTableRenderer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace TextTableBuilder.TableRenderers; 4 | 5 | public abstract class BaseTableRenderer : ITableRenderer 6 | { 7 | public const char DEFAULTPADDINGCHAR = ' '; 8 | public const int DEFAULTCELLPADDING = 1; 9 | 10 | public abstract string Render(ReadOnlyCollection columns, IEnumerable rows); 11 | 12 | protected static string RenderRow(char columnSeparator, IEnumerable values) 13 | => string.Join(columnSeparator.ToString(), values); 14 | 15 | protected static string RenderLine(char left, char mid, char right, char pad, ReadOnlyCollection widths, int cellPadding) 16 | => $"{left}{string.Join(mid.ToString(), widths.Select(c => new string(pad, c.Width + (cellPadding * 2))))}{right}"; 17 | 18 | protected static string RenderCell(string value, Align align, int width, char paddingChar, int cellPadding) 19 | => PadCell(AlignString(TruncateString(value, align, width), align, width, paddingChar), paddingChar, cellPadding); 20 | 21 | protected static string PadCell(string value, char paddingChar, int count) 22 | => value.PadLeft(value.Length + count, paddingChar).PadRight(value.Length + (count * 2), paddingChar); 23 | 24 | protected static string AlignString(string value, Align align, int width, char paddingChar) 25 | => align switch 26 | { 27 | Align.Right => value.PadLeft(width, paddingChar), 28 | Align.Center => value.PadLeft((width - value.Length) / 2 + value.Length, paddingChar).PadRight(width, paddingChar), 29 | _ => value.PadRight(width, paddingChar) 30 | }; 31 | 32 | protected static string TruncateString(string value, Align align, int length) 33 | => align switch 34 | { 35 | Align.Right => value.Substring(Math.Max(value.Length - length, 0), Math.Min(value.Length, length)), 36 | Align.Center => value.Substring(Math.Max((value.Length - length) / 2, 0), Math.Min(length, value.Length)), 37 | _ => value.Substring(0, Math.Min(length, value.Length)) 38 | }; 39 | } 40 | -------------------------------------------------------------------------------- /TextTableBuilder.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32319.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextTableBuilder", "TextTableBuilder\TextTableBuilder.csproj", "{F5214A18-9575-4CCE-9163-F2CD499FF9CF}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextTableBuilder.Tests", "TextTableBuilder.Tests\TextTableBuilder.Tests.csproj", "{86252320-3AF7-41F2-8851-E4C9CE9A4A1D}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F73464FC-8BAC-4D31-BD54-9964CB9A2FEB}" 11 | ProjectSection(SolutionItems) = preProject 12 | README.md = README.md 13 | EndProjectSection 14 | EndProject 15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoApp", "DemoApp\DemoApp.csproj", "{EE019203-07E9-4282-8436-074DCA55557F}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {F5214A18-9575-4CCE-9163-F2CD499FF9CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {F5214A18-9575-4CCE-9163-F2CD499FF9CF}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {F5214A18-9575-4CCE-9163-F2CD499FF9CF}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {F5214A18-9575-4CCE-9163-F2CD499FF9CF}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {86252320-3AF7-41F2-8851-E4C9CE9A4A1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {86252320-3AF7-41F2-8851-E4C9CE9A4A1D}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {86252320-3AF7-41F2-8851-E4C9CE9A4A1D}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {86252320-3AF7-41F2-8851-E4C9CE9A4A1D}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {EE019203-07E9-4282-8436-074DCA55557F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {EE019203-07E9-4282-8436-074DCA55557F}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {EE019203-07E9-4282-8436-074DCA55557F}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {EE019203-07E9-4282-8436-074DCA55557F}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {BE920C11-0572-4258-9161-5ED96D61B2DC} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /TextTableBuilder/Table.cs: -------------------------------------------------------------------------------- 1 | using TextTableBuilder.TypeHandlers; 2 | 3 | namespace TextTableBuilder; 4 | 5 | public class Table 6 | { 7 | private readonly List _columns = new(); 8 | private readonly List _rows = new(); 9 | 10 | public IReadOnlyCollection Columns => _columns; 11 | public IReadOnlyCollection Rows => _rows; 12 | 13 | public Table() { } 14 | public Table(IEnumerable columns) 15 | : this(columns, Enumerable.Empty()) { } 16 | 17 | public Table(IEnumerable columns, IEnumerable rows) 18 | => AddColumns(columns).AddRow(rows); 19 | 20 | public Table AddColumn(string name, Align align = Align.Left, Align rowAlign = Align.Left, int? minWidth = null, int? width = null, ITypeHandler? typeHandler = null) 21 | => AddColumn(new Column(name, align, rowAlign, minWidth, width, typeHandler)); 22 | 23 | public Table AddColumn(Column column) 24 | { 25 | if (column is null) 26 | { 27 | throw new ArgumentNullException(nameof(column)); 28 | } 29 | _columns.Add(column); 30 | return this; 31 | } 32 | 33 | public Table AddColumns(IEnumerable columns) 34 | { 35 | if (columns is null) 36 | { 37 | throw new ArgumentNullException(nameof(columns)); 38 | } 39 | 40 | foreach (var column in columns) 41 | { 42 | AddColumn(column); 43 | } 44 | return this; 45 | } 46 | 47 | public Table AddColumns(IEnumerable columns) 48 | => AddColumns(columns.Select(c => Column.FromName(c))); 49 | 50 | public Table AddColumns(params string[] columns) 51 | => AddColumns(columns.Select(c => Column.FromName(c))); 52 | 53 | public Table AddRow(params object?[] values) 54 | => AddRowImpl(new ValueRow(values)); 55 | 56 | public Table AddRow(params string?[] values) 57 | => AddRowImpl(new ValueRow(values)); 58 | 59 | public Table AddRow(Row row) 60 | => AddRowImpl(row); 61 | 62 | public Table AddRow(T obj) 63 | { 64 | if (obj is not null) 65 | { 66 | return AddRowImpl(new ObjectRow(obj)); 67 | } 68 | 69 | return this; 70 | } 71 | 72 | public Table AddRows(IEnumerable values) 73 | { 74 | foreach (var value in values) 75 | { 76 | AddRow(value); 77 | } 78 | 79 | return this; 80 | } 81 | 82 | private Table AddRowImpl(Row row) 83 | { 84 | if (row is null) 85 | { 86 | throw new ArgumentNullException(nameof(row)); 87 | } 88 | 89 | _rows.Add(row); 90 | return this; 91 | } 92 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /TextTableBuilder/TableBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using TextTableBuilder.ObjectHandlers; 3 | using TextTableBuilder.TableRenderers; 4 | using TextTableBuilder.TypeHandlers; 5 | 6 | namespace TextTableBuilder; 7 | 8 | public class TableBuilder 9 | { 10 | public TypeHandlerCollection TypeHandlers { get; } = new(); 11 | public ObjectHandlerCollection ObjectHandlers { get; } = new(); 12 | 13 | public static readonly ITableRenderer DefaultTableRenderer = new DefaultTableRenderer(); 14 | 15 | public string Build(Table table) 16 | => Build(table, DefaultTableRenderer, CultureInfo.CurrentUICulture); 17 | 18 | public string Build(Table table, ITableRenderer tableRenderer) 19 | => Build(table, tableRenderer, CultureInfo.CurrentUICulture); 20 | 21 | public string Build(Table table, IFormatProvider formatProvider) 22 | => Build(table, DefaultTableRenderer, formatProvider); 23 | 24 | public string Build(Table table, ITableRenderer tableRenderer, IFormatProvider formatProvider) 25 | { 26 | if (table is null) 27 | { 28 | throw new ArgumentNullException(nameof(table)); 29 | } 30 | 31 | if (tableRenderer is null) 32 | { 33 | throw new ArgumentNullException(nameof(tableRenderer)); 34 | } 35 | 36 | if (formatProvider is null) 37 | { 38 | throw new ArgumentNullException(nameof(formatProvider)); 39 | } 40 | 41 | var cols = table.Columns.ToArray(); 42 | 43 | if (cols.Length == 0) 44 | { 45 | throw new InvalidOperationException("At least one column must be specified"); 46 | } 47 | 48 | // Determine preliminary columnwidths 49 | var colwidths = cols.Select((c, i) => Math.Max(cols[i].MinWidth ?? 0, Math.Min(c.Width ?? int.MaxValue, c.Name.Length))).ToArray(); // Initialize column widths to header widths or minimum widths or fixed widths; whichever is larger 50 | 51 | // Iterate all rows, creating strings from all values and keep track of column widths 52 | var rows = new List(table.Rows.Count); 53 | foreach (var row in table.Rows) 54 | { 55 | // Make string array from row values 56 | var rowvalues = (row switch 57 | { 58 | ValueRow vr => vr.Values, 59 | ObjectRow or => (ObjectHandlers.GetHandler(or.Value.GetType()) ?? ObjectHandlers.GetHandler(typeof(object))).Handle(or.Value, cols.Length), 60 | _ => throw new InvalidOperationException("Unknown rowtype") 61 | }).Select( 62 | (v, i) => i >= cols.Length 63 | ? throw new InvalidOperationException($"Number of values must match columns (row index: {rows.Count})") 64 | : v is null 65 | // Handle the special null-case with our NullHandler (if any, empty string otherwise) 66 | ? (TypeHandlers.NullValueHandler?.Handle(formatProvider) ?? string.Empty) 67 | // Use typehandler from colum when specified, else use typehandler from type from value 68 | : (cols[i].TypeHandler ?? TypeHandlers.GetHandler(v.GetType())).Handle(v, formatProvider)).ToArray(); 69 | 70 | // Make sure we have all cells 71 | if (rowvalues.Length != cols.Length) 72 | { 73 | throw new InvalidOperationException($"Number of values must match columns (row index: {rows.Count})"); 74 | } 75 | 76 | // Add row to internal collection 77 | rows.Add(rowvalues); 78 | // Update column widths 79 | for (var i = 0; i < cols.Length; i++) 80 | { 81 | colwidths[i] = colwidths[i] < rowvalues[i].Length ? rowvalues[i].Length : colwidths[i]; 82 | } 83 | } 84 | // For columns width a fixed width we may need to clamp the values 85 | colwidths = cols.Select((w, i) => Math.Min(w.Width ?? int.MaxValue, colwidths[i])).ToArray(); 86 | 87 | // Now build actual table 88 | return tableRenderer.Render( 89 | Array.AsReadOnly(table.Columns.Select((c, i) => new RenderColumn(c.Name, colwidths[i], c.HeaderAlign, c.ValueAlign)).ToArray()), 90 | rows 91 | ); 92 | } 93 | 94 | #region Convenience methods 95 | public TableBuilder AddObjectHandler(Type type, IObjectHandler objectHandler) 96 | { 97 | ObjectHandlers.AddHandler(type, objectHandler); 98 | return this; 99 | } 100 | 101 | public TableBuilder AddObjectHandler(IObjectHandler objectHandler) 102 | { 103 | ObjectHandlers.AddHandler(objectHandler); 104 | return this; 105 | } 106 | 107 | public TableBuilder AddObjectHandler(Func func) 108 | { 109 | ObjectHandlers.AddHandler(func); 110 | return this; 111 | } 112 | 113 | public TableBuilder AddTypeHandler(Type type, ITypeHandler typeHandler) 114 | { 115 | TypeHandlers.AddHandler(type, typeHandler); 116 | return this; 117 | } 118 | 119 | public TableBuilder AddTypeHandler(ITypeHandler typeHandler) 120 | { 121 | TypeHandlers.AddHandler(typeHandler); 122 | return this; 123 | } 124 | 125 | public TableBuilder AddTypeHandler(Func func) 126 | { 127 | TypeHandlers.AddHandler(func); 128 | return this; 129 | } 130 | 131 | public TableBuilder SetTypeHandlerNullValueHandler(INullValueHandler nullValueHandler) 132 | { 133 | TypeHandlers.NullValueHandler = nullValueHandler ?? NullValueHandler.Default; 134 | return this; 135 | } 136 | #endregion 137 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![logo](https://raw.githubusercontent.com/RobThree/TextTableBuilder/master/logo.png) TextTableBuilder 2 | 3 | ![Build Status](https://img.shields.io/github/actions/workflow/status/RobThree/IPNetworkHelper/test.yml?branch=main&style=flat-square) [![Nuget version](https://img.shields.io/nuget/v/TextTableBuilder.svg?style=flat-square)](https://www.nuget.org/packages/TextTableBuilder/) 4 | 5 | A simple, opinionated, modern table builder. Supports configuring how different datatypes will be formatted. Available as [Nuget package](https://www.nuget.org/packages/TextTableBuilder/) 6 | 7 | ## Quickstart 8 | 9 | ```c# 10 | // Create table 11 | var table = new Table(); 12 | table.AddColumn("No") 13 | .AddColumn("Name") 14 | .AddColumn("Position") 15 | .AddColumn("Salary", Align.Right, Align.Right) // Align column header and values to the right 16 | .AddRow(1, "Bill Gates", "Founder Microsoft", 10000) 17 | .AddRow(2, "Steve Jobs", "Founder Apple", 1200000) 18 | .AddRow(3, "Larry Page", "Founder Google", 1100000) 19 | .AddRow(4, "Mark Zuckerberg", "Founder Facebook", 1300000); 20 | 21 | // Use TableBuilder to render table 22 | var tablebuilder = new TableBuilder(); 23 | Console.WriteLine(tablebuilder.Build(table)); 24 | ``` 25 | 26 | ```cmd 27 | No | Name | Position | Salary 28 | -- | --------------- | ----------------- | --------- 29 | 1 | Bill Gates | Founder Microsoft | 10,000 30 | 2 | Steve Jobs | Founder Apple | 1,200,000 31 | 3 | Larry Page | Founder Google | 1,100,000 32 | 4 | Mark Zuckerberg | Founder Facebook | 1,300,000 33 | ``` 34 | 35 | There are more [examples below](#examples). 36 | 37 | ## Convenience methods 38 | 39 | ### Columns 40 | 41 | An easier, quicker way to add columns is to invoke `AddColumns()`. By passing an array of column names all columns can be specified in one call: 42 | 43 | ```c# 44 | var table = new Table() 45 | .AddColumns(new[] { "No.", "Name", "Position", "^Salary^" }) 46 | .AddRow(1, "Bill Gates", "Founder Microsoft", 10000) 47 | // etc... 48 | ``` 49 | 50 | For aligning columns, see [Aligning columns and values](#aligning-columns-and-values). 51 | 52 | ### Rows 53 | 54 | Rows can be added in three ways: 55 | 56 | 1. `AddRow(Row row)`\ 57 | Either pass a `ValueRow` or `ObjectRow` 58 | 2. `AddRow(params object[] values)`\ 59 | Pass all values (e.g. `.AddRow("foo", 123, "bar)`) 60 | 3. `AddRow(value)`\ 61 | Pass an object (e.g `.AddRow(paul)`) (see [Type handling](#type-handling)) 62 | 63 | Method 2 adds a `ValueRow` to the table whereas method 3 adds an `ObjectRow` to the table. Method 1 is provided only for completeness' sake. 64 | 65 | For aligning row values, see [Aligning columns and values](#aligning-columns-and-values). 66 | 67 | ## Aligning columns and values 68 | 69 | Columnames can be prefixed and suffixed with: 70 | 71 | * `^` Align right 72 | * `~` Align center 73 | 74 | When a columnname is specified as `"^Salary"`, the column name will be right aligned, the values will default to left. When the name is specified as `"Salary^"` the column values will be right aligned, the column name itself will default to left aligned. And, finally, when the name is specified as `"^Salary^"` then both the column name and values will be right aligned. 75 | 76 | If you want more control over a column you'll need to use the `AddColumn()` method which allows you to specify a minimum / fixed width for the column as well as a `TypeHandler` (see [Type Handling](#type-handling)). 77 | 78 | ## Column widths 79 | 80 | A column, by default, simply stretches to be wide enough to contain all values in that column. You can, however, specify a minimum width (`MinWidth`) or a width (`Width`). The `MinWidth` ensures the column is always at least the number of specified characters wide, but may be wider when the column contains longer values. The `Width` ensures a column is always exactly the specified width. Longer values will be truncated. Note that truncating depends on the alignment of the values. Right-aligned values will be truncated from the left, left-aligned values will be truncated from the right and center-aligned values will be truncated from both sides. 81 | 82 | To specifiy a width, use either the `AddColumn()` overload that allows you to pass an optional `minWidth` or `width` argument, or the `AddColumn(Column)` overload and specify the `width` or `minWidth` with the `Column`'s constructor arguments. 83 | 84 | ## Internationalization (i18n) 85 | 86 | TextTableBuilder supports i18n by supporting an `IFormatProvider` which can be specified by passing it to the `Build()` method. The above example is based on an `en_US` locale. If we pass another locale, we get: 87 | 88 | ```c# 89 | Console.WriteLine(tablebuilder.Build(table, new CultureInfo("nl_NL"))); 90 | ``` 91 | 92 | ```cmd 93 | No | Name | Position | Salary 94 | -- | --------------- | ----------------- | --------- 95 | 1 | Bill Gates | Founder Microsoft | 10.000 96 | 2 | Steve Jobs | Founder Apple | 1.200.000 97 | 3 | Larry Page | Founder Google | 1.100.000 98 | 4 | Mark Zuckerberg | Founder Facebook | 1.300.000 99 | ``` 100 | 101 | By default, unless specified otherwise, the TaxtTableBuilder uses the current UI locale (`CultureInfo.CurrentUICulture`). 102 | 103 | ## Type handling 104 | 105 | By default TextTableBuilder comes with type handlers for all primitives (e.g. `int`, `decimal`, ...) and some other common types like `DateTime` and `TimeSpan`. However, you can customize how a type is formatted by specifying a `TypeHandler` that implements `ITypeHandler`. 106 | 107 | TextTableBuilder will first try to use the `TypeHandler` for the column being formatted; when no `TypeHandler` is specified for a column then the type of the value is used to determine which `TypeHandler` to use. 108 | 109 | An example of a typehandler is: 110 | 111 | ```c# 112 | public class CurrencyTypeHandler : ITypeHandler 113 | { 114 | public string Handle(object value, IFormatProvider formatProvider) 115 | => string.Format("$ {0:N2}", value); 116 | } 117 | ``` 118 | 119 | So when we then specify our values as decimals (by adding the `m`-suffix)... 120 | 121 | ```c# 122 | var table = new Table() 123 | .AddColumns(new[] { "No.", "Name", "Position", "^Salary^" }) 124 | .AddRow(1, "Bill Gates", "Founder Microsoft", 10000m) 125 | // etc ... 126 | ``` 127 | 128 | ...and we register our new `CurrencyTypeHandler`... 129 | 130 | ```c# 131 | var tablebuilder = new TableBuilder(); 132 | tablebuilder.TypeHandlers.AddHandler(new CurrencyTypeHandler()); 133 | Console.WriteLine(tablebuilder.Build(table, new CultureInfo("en_US"))); 134 | ``` 135 | 136 | ...we get: 137 | 138 | ```cmd 139 | No. | Name | Position | Salary 140 | --- | --------------- | ----------------- | -------------- 141 | 1 | Bill Gates | Founder Microsoft | $ 10,000.00 142 | 2 | Steve Jobs | Founder Apple | $ 1,200,000.00 143 | 3 | Larry Page | Founder Google | $ 1,100,000.00 144 | 4 | Mark Zuckerberg | Founder Facebook | $ 1,300,000.00 145 | ``` 146 | 147 | An alternative method of creating a `TypeHandler` is to inherit from `DelegatingTypeHandler` which allows you to simply use a delegate function: 148 | 149 | ```c# 150 | public class CurrencyTypeHandler : DelegatingTypeHandler 151 | { 152 | public CurrencyTypeHandler() 153 | : base((value, formatProvider) => string.Format("$ {0:N2}", value)) { } 154 | } 155 | ``` 156 | 157 | Or, even shorter: 158 | 159 | ```c# 160 | tablebuilder.TypeHandlers.AddHandler(new DelegatingTypeHandler((value, fp) => string.Format("$ {0:N2}", value))); 161 | ``` 162 | 163 | And still shorter: 164 | 165 | ```c# 166 | tablebuilder.TypeHandlers.AddHandler((value, formatProvider) => string.Format("$ {0:N2}", value)); 167 | ``` 168 | And instead of the `TypeHandlers` property we can also use the `AddTypeHandler()` method: 169 | 170 | ```c# 171 | tablebuilder.AddTypeHandler((value, formatProvider) => string.Format("$ {0:N2}", value)); 172 | ``` 173 | 174 | And for those about to point out this can be written even shorter: 175 | 176 | ```c# 177 | tablebuilder.AddTypeHandler((v, _) => $"$ {v:N2}"); 178 | ``` 179 | 180 | A `TypeHandler` can also be passed to a `Column`'s constructor, in which case that `TypeHandler` is used for all values in that column. 181 | 182 | ### Null value handling 183 | 184 | A special case is the `NullValueHandler`; by default a `null` value is formatted as an empty string. However, you may want to show `null` values as "``" for example. To accomplish this we simply use the built-in `NullValueHandler`: 185 | 186 | ```c# 187 | tablebuilder.TypeHandlers.NullValueHandler = new NullHandler(""); 188 | ``` 189 | 190 | It is possible to implement your own `NullValueHandler` by implementing `INullValueHandler`. 191 | 192 | ### Object handling 193 | 194 | For the following examples we're going to assume a collection of persons: 195 | 196 | ```c# 197 | public record Person(string Name, string Position, decimal Salary); 198 | 199 | var persons = new[] 200 | { 201 | new Person("Bill Gates", "Founder Microsoft", 10000m), 202 | // etc ... 203 | }; 204 | ``` 205 | #### Default object handling 206 | 207 | By default the TextTableBuilder outputs properties of objects in alfabetical order; for our example that just happens to work out: 208 | 209 | ```c# 210 | var table = new Table() 211 | .AddColumns(new[] { "Name", "Position", "^Salary^" }) 212 | .AddRows(persons); 213 | 214 | var tablebuilder = new TableBuilder(); 215 | Console.WriteLine(tablebuilder.Build(table)); 216 | ``` 217 | 218 | The order of the outputted properties can be changed by using a [ColumnOrder attribute](#columnorder-attribute). Properties (or fields) that don't have this attribute will be ordered by name. 219 | 220 | You'll probably want (a lot) more control; in which case you should look into [Custom object handling](#custom-object-handling). 221 | 222 | #### Custom object handling 223 | First, we implement an `IObjectHandler`: 224 | 225 | ```c# 226 | public class PersonHandler : IObjectHandler 227 | { 228 | public object[] Handle(object value, int columnCount) 229 | { 230 | var person = (Person)value; 231 | // Return properties as value array 232 | return new object[] { person.Name, person.Position, person.Salary }; 233 | } 234 | } 235 | ``` 236 | 237 | After that, building a table for this data is simple: 238 | 239 | ```c# 240 | var table = new Table() 241 | .AddColumns(new[] { "Name", "Position", "^Salary^" }) 242 | .AddRows(persons); 243 | 244 | var tablebuilder = new TableBuilder(); 245 | 246 | // Specify object handler to use for persons 247 | tablebuilder.ObjectHandlers.AddHandler(new PersonHandler()); 248 | // Or, alternatively: 249 | tablebuilder.AddObjectHandler(new PersonHandler()); 250 | 251 | 252 | Console.WriteLine(tablebuilder.Build(table)); 253 | ``` 254 | 255 | Which outputs: 256 | 257 | ```cmd 258 | Name | Position | Salary 259 | --------------- | ----------------- | ------------ 260 | Bill Gates | Founder Microsoft | 10,000.00 261 | Steve Jobs | Founder Apple | 1,200,000.00 262 | Larry Page | Founder Google | 1,100,000.00 263 | Mark Zuckerberg | Founder Facebook | 1,300,000.00 264 | ``` 265 | 266 | TextTableBuilder will still use the `TypeHandler`s to handle the types of the values as always. 267 | 268 | A shorter method is to inherit from the `DelegateObjectHandler`: 269 | 270 | ```c# 271 | public class PersonHandler : DelegatingObjectHandler 272 | { 273 | public PersonHandler() 274 | : base((person, columnCount) => new object[] { person.Name, person.Position, person.Salary }) { } 275 | } 276 | ``` 277 | 278 | Even shorter: 279 | 280 | ```c# 281 | tablebuilder.ObjectHandlers.AddHandler(new DelegatingObjectHandler((person, fp) => new object[] { person.Name, person.Position, person.Salary })); 282 | ``` 283 | 284 | Still shorter: 285 | 286 | ```c# 287 | tablebuilder.AddObjectHandler((person, columnCount) => new object[] { person.Name, person.Position, person.Salary }); 288 | ``` 289 | 290 | When no handler for a specific object can be found then the `DefaultObjectHandler` is used which simply takes all readable properties and returns those in alfabetical order unless... 291 | 292 | ### ColumnOrder attribute 293 | 294 | When adding rows by adding objects directly (e.g. `.AddRow(myperson)` where `myperson` is a `Person` objecy) the order of the properties can be specified for the `DefaultObjectHandler`. If you implement your own `IObjectHandler` then you need to either return the values in te correct order or look for the `ColumnOrder` attribute and use it's `Order` property to determine the order of the properties. 295 | 296 | ```c# 297 | public record Person( 298 | [property: ColumnOrder(2)] string Name, 299 | [property: ColumnOrder(1)] string Position, 300 | [property: ColumnOrder(3)] decimal Salary, 301 | [property: ColumnOrder(4)] DateTime DateOfBirth 302 | ); 303 | ``` 304 | 305 | Or, a bit more old-fashioned: 306 | 307 | ```c# 308 | public class Person 309 | { 310 | [ColumnOrder(2)] 311 | public string Name { get; set; } 312 | [ColumnOrder(1)] 313 | public string Position { get; set; } 314 | [ColumnOrder(3)] 315 | public decimal Salary { get; set; } 316 | [ColumnOrder(4)] 317 | public DateTime DateOfBirth { get; set; } 318 | } 319 | ``` 320 | 321 | If we now print the table: 322 | 323 | ```c# 324 | var persons = new[] 325 | { 326 | new Person("Bill Gates", "Founder Microsoft", 10000m, new DateTime(1955, 10, 28)), 327 | // etc ... 328 | }; 329 | 330 | var table = new Table() 331 | .AddColumns(new[] { "Position", "Name", "^Salary^" }) 332 | .AddRows(persons); 333 | 334 | var tablebuilder = new TableBuilder(); 335 | Console.WriteLine(tablebuilder.Build(table)); 336 | ``` 337 | 338 | The result is: 339 | 340 | ```cmd 341 | Position | Name | Salary 342 | ----------------- | --------------- | ------------ 343 | Founder Microsoft | Bill Gates | 10,000.00 344 | Founder Apple | Steve Jobs | 1,200,000.00 345 | Founder Google | Larry Page | 1,100,000.00 346 | Founder Facebook | Mark Zuckerberg | 1,300,000.00 347 | ``` 348 | 349 | Note the DateOfBirth column is missing; this is because the `DefaultObjectHandler`, by default, only takes the number of properties equal to the number of columns. 350 | 351 | However, if we print the table like this: 352 | 353 | ```c# 354 | var table = new Table() 355 | .AddColumns(new[] { "Position", "Name", "^Salary^", "Birthdate", "Alma mater", "Spouse" }) 356 | .AddRows(persons); 357 | 358 | var tablebuilder = new TableBuilder(); 359 | tablebuilder.AddTypeHandler(new DelegatingTypeHandler((date, formatprovider) => $"{date:yyyy-MM-dd}")); 360 | Console.WriteLine(tablebuilder.Build(table)); 361 | ``` 362 | 363 | The result is: 364 | 365 | ```cmd 366 | Position | Name | Salary | Birthdate | Alma mater | Spouse 367 | ----------------- | --------------- | ------------ | ---------- | ---------- | ------ 368 | Founder Microsoft | Bill Gates | 10,000.00 | 1955-10-28 | | 369 | Founder Apple | Steve Jobs | 1,200,000.00 | 1955-02-24 | | 370 | Founder Google | Larry Page | 1,100,000.00 | 1973-03-26 | | 371 | Founder Facebook | Mark Zuckerberg | 1,300,000.00 | 1984-03-14 | | 372 | ``` 373 | 374 | The `DefaultObjectHandler`, by default, pads all rows with missing values with `null` values. 375 | 376 | ## Table Renderers 377 | 378 | The TextTableBuilder uses an `ITableRenderer` to do the actual 'rendering' of the table. The TableRenderer is provided with `RenderColums`, which provide column information, and an `IEnumerable` which represents the rows and values. The values have been formatted at this point; the table renderer takes care of aligning, padding etc. 379 | 380 | By default, the TextTableBuilder uses the `DefaultTableRenderer` which produced the above examples. A few other, very simple, renderers are provided. These are the `MinimalTableRenderer` and `MSDOSTableRenderer`, `SimpleLineTableRenderer`, `SingleLineTableRenderer`, `DoubleLineTableRenderer`, `HatchedTableRenderer`, `DotsTableRenderer` and `RounderCornersTableRenderer`. 381 | 382 | To use a specific `ITableRenderer` you pass one to the `Build()` method: 383 | 384 | ```c# 385 | Console.WriteLine(tablebuilder.Build(table, new MSDOSTableRenderer())); 386 | ``` 387 | 388 | Going back to our [very first example](#quickstart), the following styles are currently provided. More _may_ be added in the future (as well as ANSI color support etc.) but it's also trivial to build your own; just implement `ITableRenderer`: 389 | 390 | ### DefaultTableRenderer: 391 | 392 | ```cmd 393 | No | Name | Position | Salary 394 | ----|-----------------|-------------------|---------------- 395 | 1 | Bill Gates | Founder Microsoft | $ 10,000.00 396 | 2 | Steve Jobs | Founder Apple | $ 1,200,000.00 397 | 3 | Larry Page | Founder Google | $ 1,100,000.00 398 | 4 | Mark Zuckerberg | Founder Facebook | $ 1,300,000.00 399 | ``` 400 | 401 | ### MinimalTableRenderer: 402 | 403 | ```cmd 404 | No Name Position Salary 405 | 1 Bill Gates Founder Microsoft $ 10,000.00 406 | 2 Steve Jobs Founder Apple $ 1,200,000.00 407 | 3 Larry Page Founder Google $ 1,100,000.00 408 | 4 Mark Zuckerberg Founder Facebook $ 1,300,000.00 409 | ``` 410 | 411 | ### MSDOSTableRenderer: 412 | 413 | ```cmd 414 | No ║ Name ║ Position ║ Salary 415 | ════║═════════════════║═══════════════════║════════════════ 416 | 1 ║ Bill Gates ║ Founder Microsoft ║ $ 10,000.00 417 | 2 ║ Steve Jobs ║ Founder Apple ║ $ 1,200,000.00 418 | 3 ║ Larry Page ║ Founder Google ║ $ 1,100,000.00 419 | 4 ║ Mark Zuckerberg ║ Founder Facebook ║ $ 1,300,000.00 420 | ``` 421 | 422 | ### SimpleLineTableRenderer: 423 | 424 | ```cmd 425 | +----+-----------------+-------------------+----------------+ 426 | | No | Name | Position | Salary | 427 | +----+-----------------+-------------------+----------------+ 428 | | 1 | Bill Gates | Founder Microsoft | $ 10,000.00 | 429 | | 2 | Steve Jobs | Founder Apple | $ 1,200,000.00 | 430 | | 3 | Larry Page | Founder Google | $ 1,100,000.00 | 431 | | 4 | Mark Zuckerberg | Founder Facebook | $ 1,300,000.00 | 432 | +----+-----------------+-------------------+----------------+ 433 | ``` 434 | 435 | ### SingleLineTableRenderer: 436 | 437 | ```cmd 438 | ┌────┬─────────────────┬───────────────────┬────────────────┐ 439 | │ No │ Name │ Position │ Salary │ 440 | ├────┼─────────────────┼───────────────────┼────────────────┤ 441 | │ 1 │ Bill Gates │ Founder Microsoft │ $ 10,000.00 │ 442 | │ 2 │ Steve Jobs │ Founder Apple │ $ 1,200,000.00 │ 443 | │ 3 │ Larry Page │ Founder Google │ $ 1,100,000.00 │ 444 | │ 4 │ Mark Zuckerberg │ Founder Facebook │ $ 1,300,000.00 │ 445 | └────┴─────────────────┴───────────────────┴────────────────┘ 446 | ``` 447 | 448 | ### DoubleLineTableRenderer: 449 | 450 | ```cmd 451 | ╔════╦═════════════════╦═══════════════════╦════════════════╗ 452 | ║ No ║ Name ║ Position ║ Salary ║ 453 | ╠════╬═════════════════╬═══════════════════╬════════════════╣ 454 | ║ 1 ║ Bill Gates ║ Founder Microsoft ║ $ 10,000.00 ║ 455 | ║ 2 ║ Steve Jobs ║ Founder Apple ║ $ 1,200,000.00 ║ 456 | ║ 3 ║ Larry Page ║ Founder Google ║ $ 1,100,000.00 ║ 457 | ║ 4 ║ Mark Zuckerberg ║ Founder Facebook ║ $ 1,300,000.00 ║ 458 | ╚════╩═════════════════╩═══════════════════╩════════════════╝ 459 | ``` 460 | 461 | ### RoundedCornersTableRenderer: 462 | 463 | ```cmd 464 | ╭────┬─────────────────┬───────────────────┬────────────────╮ 465 | │ No │ Name │ Position │ Salary │ 466 | ├────┼─────────────────┼───────────────────┼────────────────┤ 467 | │ 1 │ Bill Gates │ Founder Microsoft │ $ 10,000.00 │ 468 | │ 2 │ Steve Jobs │ Founder Apple │ $ 1,200,000.00 │ 469 | │ 3 │ Larry Page │ Founder Google │ $ 1,100,000.00 │ 470 | │ 4 │ Mark Zuckerberg │ Founder Facebook │ $ 1,300,000.00 │ 471 | ╰────┴─────────────────┴───────────────────┴────────────────╯ 472 | ``` 473 | 474 | ### HatchedTableRenderer: 475 | 476 | ```cmd 477 | /----+-----------------+-------------------+----------------\ 478 | | No | Name | Position | Salary | 479 | +----+-----------------+-------------------+----------------+ 480 | | 1 | Bill Gates | Founder Microsoft | $ 10,000.00 | 481 | | 2 | Steve Jobs | Founder Apple | $ 1,200,000.00 | 482 | | 3 | Larry Page | Founder Google | $ 1,100,000.00 | 483 | | 4 | Mark Zuckerberg | Founder Facebook | $ 1,300,000.00 | 484 | \----+-----------------+-------------------+----------------/ 485 | ``` 486 | 487 | ### DotsTableRenderer: 488 | 489 | ```cmd 490 | ............................................................. 491 | : No : Name : Position : Salary : 492 | :....:.................:...................:................: 493 | : 1 : Bill Gates : Founder Microsoft : $ 10,000.00 : 494 | : 2 : Steve Jobs : Founder Apple : $ 1,200,000.00 : 495 | : 3 : Larry Page : Founder Google : $ 1,100,000.00 : 496 | : 4 : Mark Zuckerberg : Founder Facebook : $ 1,300,000.00 : 497 | ............................................................. 498 | ``` 499 | 500 | ## Examples 501 | 502 | With all the examples above demonstrating a specific option each, you may not have noticed how easy this package can make your life (that's what it's meant to do). So here's an example that shows typical usage. Assuming you have a `Person` class/record but you can't (or don't want to) 'pollute' it with `ColumnOrder`-attributes: 503 | 504 | ```c# 505 | var table = new Table() 506 | .AddColumns(new[] { "Name", "Position", "^Salary^" }) 507 | .AddRows(DBContext.Persons.Where(p => p.Salary > 100)); 508 | 509 | var tablebuilder = new TableBuilder() 510 | .AddObjectHandler( // Specify object handler to use for persons 511 | (person, columnCount) => new object[] { person.Name, person.Position, person.Salary } 512 | ); 513 | Console.WriteLine(tablebuilder.Build(table)); 514 | ``` 515 | 516 | --- 517 | 518 | Icon made by [Freepik](http://www.flaticon.com/authors/freepik) from [www.flaticon.com](http://www.flaticon.com) is licensed by [CC 3.0](http://creativecommons.org/licenses/by/3.0/). 519 | --------------------------------------------------------------------------------