├── .gitignore ├── ConsoleDump.sln ├── ConsoleDump ├── ColorString.cs ├── ColumnDetails.cs ├── ConsoleDump.csproj ├── ConsoleWriter.cs ├── DataTableDetails.cs ├── Extensions.cs ├── MemberDetails.cs ├── MemberValue.cs └── TypeDetails.cs ├── CoreDemo ├── CoreDemo.csproj └── Program.cs ├── DemoLib ├── Demo.cs └── DemoLib.csproj ├── LICENSE ├── README.md └── WindowsDemo ├── App.config ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── ScreenShotDemo.cs ├── WindowsDemo.csproj └── packages.config /.gitignore: -------------------------------------------------------------------------------- 1 | .vs/ 2 | 3 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 4 | [Bb]in/ 5 | [Oo]bj/ 6 | 7 | # mstest test results 8 | TestResults 9 | 10 | ## Ignore Visual Studio temporary files, build results, and 11 | ## files generated by popular Visual Studio add-ons. 12 | 13 | # User-specific files 14 | *.suo 15 | *.user 16 | *.sln.docstates 17 | 18 | # Build results 19 | [Dd]ebug/ 20 | [Rr]elease/ 21 | x64/ 22 | *_i.c 23 | *_p.c 24 | *.ilk 25 | *.meta 26 | *.obj 27 | *.pch 28 | *.pdb 29 | *.pgc 30 | *.pgd 31 | *.rsp 32 | *.sbr 33 | *.tlb 34 | *.tli 35 | *.tlh 36 | *.tmp 37 | *.log 38 | *.vspscc 39 | *.vssscc 40 | .builds 41 | 42 | # Visual C++ cache files 43 | ipch/ 44 | *.aps 45 | *.ncb 46 | *.opensdf 47 | *.sdf 48 | 49 | # Visual Studio profiler 50 | *.psess 51 | *.vsp 52 | *.vspx 53 | 54 | # Guidance Automation Toolkit 55 | *.gpState 56 | 57 | # ReSharper is a .NET coding add-in 58 | _ReSharper* 59 | 60 | # NCrunch 61 | *.ncrunch* 62 | .*crunch*.local.xml 63 | 64 | # Installshield output folder 65 | [Ee]xpress 66 | 67 | # DocProject is a documentation generator add-in 68 | DocProject/buildhelp/ 69 | DocProject/Help/*.HxT 70 | DocProject/Help/*.HxC 71 | DocProject/Help/*.hhc 72 | DocProject/Help/*.hhk 73 | DocProject/Help/*.hhp 74 | DocProject/Help/Html2 75 | DocProject/Help/html 76 | 77 | # Click-Once directory 78 | publish 79 | 80 | # Publish Web Output 81 | *.Publish.xml 82 | 83 | # NuGet Packages Directory 84 | packages 85 | 86 | # Windows Azure Build Output 87 | csx 88 | *.build.csdef 89 | 90 | # Windows Store app package directory 91 | AppPackages/ 92 | 93 | # Others 94 | [Bb]in 95 | [Oo]bj 96 | sql 97 | TestResults 98 | [Tt]est[Rr]esult* 99 | *.Cache 100 | ClientBin 101 | [Ss]tyle[Cc]op.* 102 | ~$* 103 | *.dbmdl 104 | Generated_Code #added for RIA/Silverlight projects 105 | 106 | # Backup & report files from converting an old project file to a newer 107 | # Visual Studio version. Backup files are not needed, because we have git ;-) 108 | _UpgradeReport_Files/ 109 | Backup*/ 110 | UpgradeLog*.XML 111 | 112 | # vim 113 | *.swp 114 | -------------------------------------------------------------------------------- /ConsoleDump.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2036 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleDump", "ConsoleDump\ConsoleDump.csproj", "{82FB80A8-F660-430E-9A23-AE12F4E80217}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoreDemo", "CoreDemo\CoreDemo.csproj", "{F25FDFBC-5B40-44EE-A204-25FDD1F8F302}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoLib", "DemoLib\DemoLib.csproj", "{F1E3277D-062F-4729-993D-92E18674ABBC}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsDemo", "WindowsDemo\WindowsDemo.csproj", "{E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {82FB80A8-F660-430E-9A23-AE12F4E80217}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {82FB80A8-F660-430E-9A23-AE12F4E80217}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {82FB80A8-F660-430E-9A23-AE12F4E80217}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {82FB80A8-F660-430E-9A23-AE12F4E80217}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {F25FDFBC-5B40-44EE-A204-25FDD1F8F302}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {F25FDFBC-5B40-44EE-A204-25FDD1F8F302}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {F25FDFBC-5B40-44EE-A204-25FDD1F8F302}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {F25FDFBC-5B40-44EE-A204-25FDD1F8F302}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {F1E3277D-062F-4729-993D-92E18674ABBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {F1E3277D-062F-4729-993D-92E18674ABBC}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {F1E3277D-062F-4729-993D-92E18674ABBC}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {F1E3277D-062F-4729-993D-92E18674ABBC}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {6F1DA6C1-E099-4650-99E4-8B73B0462095} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /ConsoleDump/ColorString.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace ConsoleDump 7 | { 8 | internal struct ColorString 9 | { 10 | public readonly String String; 11 | public readonly ConsoleColor Foreground; 12 | public readonly ConsoleColor Background; 13 | 14 | public ColorString(string s, ConsoleColor foreground, ConsoleColor background) 15 | { 16 | this.String = s; 17 | this.Foreground = foreground; 18 | this.Background = background; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ConsoleDump/ColumnDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Text; 5 | 6 | namespace ConsoleDump 7 | { 8 | internal class ColumnDetails : MemberDetails 9 | { 10 | public readonly DataColumn DataColumn; 11 | public ColumnDetails(DataColumn column) : base(column.ColumnName, TypeDetails.Get(column.DataType)) 12 | { 13 | DataColumn = column; 14 | } 15 | 16 | public override MemberValue GetValue(object instance) 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | 21 | public override string ToString() => DataColumn.ToString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ConsoleDump/ConsoleDump.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net45;net40 5 | 7.1 6 | 0.7.0.0 7 | 0.7.0.0 8 | 0.7.0.0 9 | Copyright 2018 Cameron Jordan 10 | http://opensource.org/licenses/Apache-2.0 11 | https://github.com/cameronism/ConsoleDump 12 | https://github.com/cameronism/ConsoleDump 13 | Dump;PrettyPrint;Console;Text 14 | netstandard 2.0 and DataTable support 15 | Cameron Jordan 16 | cameronism 17 | 18 | .Dump() extension method to visualize your collections and objects in color at the console 19 | true 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ConsoleDump/ConsoleWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace ConsoleDump 7 | { 8 | internal class ConsoleWriter 9 | { 10 | #region console interaction - all virtual methods 11 | protected virtual void WritePlain(string s) 12 | { 13 | Console.Write(s); 14 | } 15 | 16 | protected virtual void Write(string s, ConsoleColor foreground, ConsoleColor background) 17 | { 18 | Console.ForegroundColor = foreground; 19 | Console.BackgroundColor = background; 20 | Console.Write(s); 21 | Console.ResetColor(); 22 | } 23 | 24 | protected virtual void WriteLine() 25 | { 26 | Console.WriteLine(); 27 | } 28 | #endregion 29 | 30 | #region const-ish 31 | static readonly ColorString _Null = new ColorString("null", ConsoleColor.Green, ConsoleColor.Black); 32 | static readonly ColorString _Separator = new ColorString(" ", ConsoleColor.White, ConsoleColor.DarkMagenta); 33 | static readonly ColorString _Ellipsis = new ColorString("\u2026", ConsoleColor.DarkMagenta, ConsoleColor.Cyan); // TODO see how this looks 34 | 35 | const ConsoleColor HEADING_FOREGROUND = ConsoleColor.White; 36 | const ConsoleColor HEADING_BACKGROUND = ConsoleColor.DarkCyan; 37 | #endregion 38 | 39 | #region write helpers 40 | private void Write(ColorString cs) 41 | { 42 | Write(cs.String, cs.Foreground, cs.Background); 43 | } 44 | 45 | private void WriteFixed(ColorString value, int width, TypeCode typeCode) 46 | { 47 | var len = value.String.Length; 48 | if (len == width) 49 | { 50 | Write(value); 51 | } 52 | else if (len < width) 53 | { 54 | // right align numbers 55 | string padded = typeCode >= TypeCode.SByte && typeCode <= TypeCode.Decimal ? 56 | value.String.PadLeft(width) : 57 | value.String.PadRight(width); 58 | Write(padded, value.Foreground, value.Background); 59 | } 60 | else 61 | { 62 | Write(value.String.Substring(0, width - 1), value.Foreground, value.Background); 63 | Write(_Ellipsis); 64 | } 65 | } 66 | 67 | private void WritePadding(int padding) 68 | { 69 | if (padding < 1) return; 70 | WritePlain(new String(' ', padding)); 71 | } 72 | 73 | private void WriteLabel(string label, int padding) 74 | { 75 | WritePadding(padding); 76 | Write(label, ConsoleColor.White, ConsoleColor.DarkBlue); 77 | } 78 | 79 | private void WriteEnumerableLabel(TypeDetails details, int shown, int? count, int padding, int enumerableLimit) 80 | { 81 | string label; 82 | if (shown < enumerableLimit || count == enumerableLimit) 83 | { 84 | label = " (" + shown + " items)"; 85 | } 86 | else if (count.HasValue) 87 | { 88 | label = " (First " + shown + " items of " + count + ")"; 89 | } 90 | else 91 | { 92 | label = " (First " + shown + " items)"; 93 | } 94 | WriteLabel(details.TypeLabel + label, padding); 95 | WriteLine(); 96 | } 97 | #endregion 98 | 99 | private ColorString GetString(TypeDetails details, object instance) 100 | { 101 | if (instance == null) 102 | { 103 | return _Null; 104 | } 105 | 106 | var typeCode = details.SimpleTypeCode; 107 | 108 | var foreground = 109 | typeCode == TypeCode.String ? ConsoleColor.Cyan : // string 110 | typeCode != TypeCode.Object ? ConsoleColor.White : // primitive 111 | details.Type.IsClass ? ConsoleColor.Magenta : // class 112 | ConsoleColor.Yellow; // struct 113 | 114 | return new ColorString( 115 | instance.ToString(), 116 | foreground, 117 | details.NullableStruct ? ConsoleColor.DarkGreen : ConsoleColor.Black); 118 | } 119 | 120 | private ColorString GetString(MemberValue value) 121 | { 122 | if (value.Exception != null) 123 | { 124 | return new ColorString(value.Exception.Message, ConsoleColor.Red, ConsoleColor.Black); 125 | } 126 | else 127 | { 128 | return GetString(value.Details, value.Value); 129 | } 130 | } 131 | 132 | private void DumpComplexEnumerable(TypeDetails details, object instance, int padding, int enumerableLimit) 133 | { 134 | int? count; 135 | var items = details.GetEnumerableMemberValues(instance, enumerableLimit, out count); 136 | 137 | var itemType = details.ItemDetails; 138 | int columnCount = itemType.Members.Length; 139 | var columnWidths = new int[columnCount]; 140 | int columnIndex; 141 | ColorString[] row; 142 | var allValues = new List(items.Count + 1); 143 | 144 | // get the column headings 145 | columnIndex = 0; 146 | row = new ColorString[columnCount]; 147 | foreach (var member in itemType.Members) 148 | { 149 | row[columnIndex] = new ColorString(member.Name, HEADING_FOREGROUND, HEADING_BACKGROUND); 150 | columnWidths[columnIndex] = member.Name.Length; 151 | 152 | columnIndex++; 153 | } 154 | allValues.Add(row); 155 | 156 | // get all the values 157 | foreach (var item in items) 158 | { 159 | if (item == null) 160 | { 161 | allValues.Add(null); 162 | continue; 163 | } 164 | 165 | columnIndex = 0; 166 | row = new ColorString[columnCount]; 167 | foreach (var value in item) 168 | { 169 | var cs = GetString(value); 170 | row[columnIndex] = cs; 171 | if (cs.String.Length > columnWidths[columnIndex]) 172 | { 173 | columnWidths[columnIndex] = cs.String.Length; 174 | } 175 | 176 | columnIndex++; 177 | } 178 | allValues.Add(row); 179 | } 180 | 181 | 182 | // echo 183 | WriteEnumerableLabel(details, items.Count, count, padding, enumerableLimit); 184 | padding++; 185 | 186 | int rowCount = 0; 187 | foreach (var item in allValues) 188 | { 189 | WritePadding(padding); 190 | if (item == null) 191 | { 192 | Write(_Null); 193 | } 194 | else 195 | { 196 | columnIndex = 0; 197 | foreach (var value in item) 198 | { 199 | // grab TypeCode but not for headings 200 | var typeCode = rowCount == 0 ? 201 | TypeCode.String : 202 | itemType.Members[columnIndex].TypeDetails.SimpleTypeCode; 203 | 204 | Write(_Separator); 205 | WriteFixed(value, columnWidths[columnIndex], typeCode); 206 | columnIndex++; 207 | } 208 | } 209 | WriteLine(); 210 | rowCount++; 211 | } 212 | } 213 | 214 | private void DumpSimpleEnumerable(TypeDetails details, object instance, int padding, int enumerableLimit) 215 | { 216 | int? count; 217 | var items = details.GetEnumerableSimpleValues(instance, enumerableLimit, out count); 218 | 219 | // get all strings 220 | int maxLength = 0; 221 | var values = new List(items.Count); 222 | foreach (var value in items) 223 | { 224 | var cs = GetString(details.ItemDetails, value); 225 | values.Add(cs); 226 | 227 | if (cs.String.Length > maxLength) 228 | { 229 | maxLength = cs.String.Length; 230 | } 231 | } 232 | 233 | // echo 234 | WriteEnumerableLabel(details, items.Count, count, padding, enumerableLimit); 235 | padding++; 236 | foreach (var value in values) 237 | { 238 | WritePadding(padding); 239 | WriteFixed(value, maxLength, details.ItemDetails.SimpleTypeCode); 240 | WriteLine(); 241 | } 242 | } 243 | 244 | private void DumpMembers(TypeDetails details, object instance, int padding) 245 | { 246 | WriteLabel(details.TypeLabel, padding); 247 | WriteLine(); 248 | 249 | var stringified = instance.ToString(); 250 | if (!String.IsNullOrEmpty(stringified) && stringified != details.Type.FullName && stringified != instance.GetType().FullName) 251 | { 252 | WritePadding(padding); 253 | Write( 254 | stringified, 255 | details.Type.IsClass ? 256 | ConsoleColor.Magenta : // class 257 | ConsoleColor.Yellow, // struct 258 | ConsoleColor.Black); 259 | WriteLine(); 260 | } 261 | 262 | padding++; 263 | var values = details.GetMemberValues(instance); 264 | 265 | foreach (var value in values) 266 | { 267 | WritePadding(padding); 268 | Write(value.MemberName.PadRight(details.MaxMemberNameLength, ' '), HEADING_FOREGROUND, HEADING_BACKGROUND); 269 | Write(_Separator); 270 | Write(GetString(value)); 271 | WriteLine(); 272 | } 273 | } 274 | 275 | private void Dump(TypeDetails details, object instance, int padding, int enumerableLimit) 276 | { 277 | if (instance == null || details.SimpleTypeCode != TypeCode.Object) 278 | { 279 | WritePadding(padding); 280 | Write(GetString(details, instance)); 281 | WriteLine(); 282 | } 283 | else if (!details.IsEnumerable) 284 | { 285 | DumpMembers(details, instance, padding); 286 | WriteLine(); // extra 287 | } 288 | else if (details.ItemDetails.SimpleTypeCode != TypeCode.Object) 289 | { 290 | DumpSimpleEnumerable(details, instance, padding, enumerableLimit); 291 | WriteLine(); // extra 292 | } 293 | else 294 | { 295 | DumpComplexEnumerable(details, instance, padding, enumerableLimit); 296 | WriteLine(); // extra 297 | } 298 | } 299 | 300 | public T Dump(T it, string label, int enumerableLimit) 301 | { 302 | object o = it; 303 | int padding = 0; 304 | 305 | if (!String.IsNullOrEmpty(label)) 306 | { 307 | Write(label, ConsoleColor.Black, ConsoleColor.Gray); 308 | WriteLine(); 309 | padding = 1; 310 | } 311 | 312 | if (o == null) 313 | { 314 | WritePadding(padding); 315 | Write(_Null); 316 | WriteLine(); 317 | return it; 318 | } 319 | 320 | var type = o.GetType(); 321 | if (type != typeof(T) && typeof(T) != typeof(object) && !type.IsPublic && typeof(T).IsPublic) 322 | { 323 | type = typeof(T); 324 | } 325 | 326 | TypeDetails details; 327 | if (it is System.Data.DataTable datatable) 328 | { 329 | details = new DataTableDetails(datatable); 330 | } 331 | else if (it is System.Data.DataSet dataset) 332 | { 333 | foreach (System.Data.DataTable table in dataset.Tables) 334 | { 335 | Dump(table, table.Namespace, enumerableLimit); 336 | } 337 | return it; 338 | } 339 | else 340 | { 341 | details = TypeDetails.Get(type); 342 | } 343 | Dump(details, o, padding, enumerableLimit); 344 | 345 | return it; 346 | } 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /ConsoleDump/DataTableDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Text; 6 | 7 | namespace ConsoleDump 8 | { 9 | internal class DataTableDetails : TypeDetails 10 | { 11 | readonly DataTable _table; 12 | public DataTableDetails(DataTable table) : base(table) 13 | { 14 | _table = table; 15 | } 16 | 17 | public override List GetEnumerableMemberValues(object instance, int limit, out int? count) 18 | { 19 | var size = Math.Min(_table.Rows.Count, limit); 20 | var values = new List(size); 21 | var rows = _table.Rows; 22 | count = rows.Count; 23 | var columns = _table.Columns.Count; 24 | var details = Members; 25 | 26 | for (var i = 0; i < size; i++) 27 | { 28 | var members = new MemberValue[columns]; 29 | values.Add(members); 30 | 31 | for (int j = 0; j < members.Length; j++) 32 | { 33 | members[j] = new MemberValue(details[j], rows[i][j], null); 34 | } 35 | } 36 | return values; 37 | } 38 | 39 | public override bool IsEnumerable => true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /ConsoleDump/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Reflection; 7 | using System.Diagnostics; 8 | 9 | namespace ConsoleDump 10 | { 11 | public static class Extensions 12 | { 13 | public static ushort? RowLimit { get; set; } 14 | 15 | private static readonly ConsoleWriter _Writer = new ConsoleWriter(); 16 | 17 | public static T Dump(this T it, string label = null) 18 | { 19 | return _Writer.Dump(it, label, GetEnumerableLimit()); 20 | } 21 | 22 | // Non generic version for easier calling from reflection, powershell, etc. 23 | public static void DumpObject(object it, string label = null) 24 | { 25 | _Writer.Dump(it, label, GetEnumerableLimit()); 26 | } 27 | 28 | private static int GetEnumerableLimit() 29 | { 30 | if (RowLimit is ushort limit) return limit; 31 | 32 | int height; 33 | try 34 | { 35 | height = Console.WindowHeight; 36 | } 37 | catch (Exception) 38 | { 39 | return 24; 40 | } 41 | 42 | return Math.Max(height - 5, 16); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ConsoleDump/MemberDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | 8 | namespace ConsoleDump 9 | { 10 | internal class MemberDetails 11 | { 12 | public readonly TypeDetails TypeDetails; 13 | public readonly FieldInfo FieldInfo; 14 | public readonly PropertyInfo PropertyInfo; 15 | public readonly string Name; 16 | 17 | private MemberDetails(FieldInfo fi) 18 | { 19 | FieldInfo = fi; 20 | Name = fi.Name; 21 | TypeDetails = TypeDetails.Get(fi.FieldType); 22 | } 23 | 24 | private MemberDetails(PropertyInfo pi) 25 | { 26 | PropertyInfo = pi; 27 | Name = pi.Name; 28 | TypeDetails = TypeDetails.Get(pi.PropertyType); 29 | } 30 | 31 | protected MemberDetails(string name, TypeDetails details) 32 | { 33 | Name = name; 34 | TypeDetails = details; 35 | } 36 | 37 | public virtual MemberValue GetValue(object instance) 38 | { 39 | Exception exception = null; 40 | object value; 41 | 42 | if (FieldInfo != null) 43 | { 44 | value = FieldInfo.GetValue(instance); 45 | } 46 | else 47 | { 48 | try 49 | { 50 | value = PropertyInfo.GetValue(instance, null); 51 | } 52 | catch (TargetInvocationException tie) 53 | { 54 | value = null; 55 | exception = tie.InnerException ?? tie; 56 | } 57 | } 58 | 59 | return new MemberValue(this, value, exception); 60 | } 61 | 62 | public static MemberDetails[] GetAllMembers(TypeDetails details) 63 | { 64 | var properties = details.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public); 65 | var fields = details.Type.GetFields(BindingFlags.Instance | BindingFlags.Public); 66 | 67 | var members = properties 68 | .Where(pi => pi.GetGetMethod() != null && pi.GetIndexParameters().Length == 0) 69 | .Select(pi => new MemberDetails(pi)); 70 | 71 | members = members.Concat( 72 | fields.Select(fi => new MemberDetails(fi)) 73 | ); 74 | 75 | return members.ToArray(); 76 | } 77 | 78 | public override string ToString() 79 | { 80 | return ((object)PropertyInfo ?? FieldInfo).ToString(); 81 | } 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /ConsoleDump/MemberValue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace ConsoleDump 8 | { 9 | internal struct MemberValue 10 | { 11 | public readonly TypeDetails Details; 12 | public readonly string MemberName; 13 | public readonly object Value; 14 | public readonly Exception Exception; 15 | 16 | public MemberValue(MemberDetails md, object value, Exception exception) : this(md.TypeDetails, md.Name, value, exception) 17 | { 18 | } 19 | 20 | public MemberValue(TypeDetails td, string memberName, object value, Exception exception) 21 | { 22 | Details = td; 23 | MemberName = memberName; 24 | this.Value = value; 25 | this.Exception = exception; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ConsoleDump/TypeDetails.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System.Text; 8 | 9 | namespace ConsoleDump 10 | { 11 | internal class TypeDetails 12 | { 13 | const string _AnonymousLabel = "\u00f8"; 14 | 15 | public readonly Type Type; 16 | public readonly string TypeLabel; 17 | 18 | /// 19 | /// TypeCode unwrapping Nullable<> if needed 20 | /// 21 | public readonly TypeCode SimpleTypeCode; 22 | public readonly bool NullableStruct; 23 | 24 | public readonly MemberDetails[] Members; 25 | public readonly TypeDetails ItemDetails; 26 | private readonly GetGenericEnumeratorDelegate _GetItemEnumerator; 27 | public readonly int MaxMemberNameLength; 28 | 29 | private TypeDetails(Type type) 30 | { 31 | Type = type; 32 | _UnderConstruction.Push(this); 33 | try 34 | { 35 | TypeLabel = GetFullName(type); 36 | Members = null; 37 | var underlying = Nullable.GetUnderlyingType(type); 38 | NullableStruct = underlying != null; 39 | SimpleTypeCode = Type.GetTypeCode(underlying ?? type); 40 | 41 | if (SimpleTypeCode != TypeCode.Object) 42 | { 43 | // primitive-ish, that's enough details 44 | return; 45 | } 46 | 47 | // IEnumerable<> 48 | Type elementType = null; 49 | if (type.IsArray) 50 | { 51 | elementType = type.GetElementType(); 52 | } 53 | else 54 | { 55 | IEnumerable interfaces = type.GetInterfaces(); 56 | if (type.IsInterface) 57 | { 58 | interfaces = new[] { type }.Concat(interfaces); 59 | } 60 | 61 | var ienumerableType = interfaces.FirstOrDefault(ti => ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(IEnumerable<>)); 62 | 63 | if (ienumerableType != null) 64 | { 65 | elementType = ienumerableType.GetGenericArguments()[0]; 66 | } 67 | } 68 | 69 | if (elementType != null) 70 | { 71 | ItemDetails = Get(elementType); 72 | _GetItemEnumerator = CreateDelegate(ItemDetails.Type); 73 | return; 74 | } 75 | 76 | // not IEnumerable<> 77 | Members = MemberDetails.GetAllMembers(this); 78 | if (Members.Any()) 79 | { 80 | MaxMemberNameLength = Members.Max(m => m.Name.Length); 81 | } 82 | } 83 | finally 84 | { 85 | _UnderConstruction.Pop(); 86 | } 87 | } 88 | 89 | protected TypeDetails(DataTable table) 90 | { 91 | SimpleTypeCode = TypeCode.Object; 92 | ItemDetails = this; 93 | Members = new MemberDetails[table.Columns.Count]; 94 | for (int i = 0; i < Members.Length; i++) 95 | { 96 | Members[i] = new ColumnDetails(table.Columns[i]); 97 | } 98 | } 99 | 100 | public virtual bool IsEnumerable { get { return _GetItemEnumerator != null; } } 101 | public MemberValue[] GetMemberValues(object instance) 102 | { 103 | var members = Members; 104 | var values = new MemberValue[members.Length]; 105 | for (int i = 0; i < values.Length; i++) 106 | { 107 | values[i] = members[i].GetValue(instance); 108 | } 109 | return values; 110 | } 111 | 112 | public List GetEnumerableSimpleValues(object instance, int limit, out int? count) 113 | { 114 | IEnumerator enumerator; 115 | IDisposable disposable; 116 | 117 | _GetItemEnumerator(instance, out enumerator, out disposable, out count); 118 | var itemValues = new List(Math.Min(count ?? ushort.MaxValue, limit)); 119 | using (disposable) 120 | { 121 | int total = 0; 122 | while (enumerator.MoveNext() && total++ < limit) 123 | { 124 | itemValues.Add(enumerator.Current); 125 | } 126 | } 127 | 128 | return itemValues; 129 | } 130 | 131 | public virtual List GetEnumerableMemberValues(object instance, int limit, out int? count) 132 | { 133 | var values = GetEnumerableSimpleValues(instance, limit, out count); 134 | var memberValues = new List(values.Count); 135 | foreach (var value in values) 136 | { 137 | memberValues.Add(value == null ? null : ItemDetails.GetMemberValues(value)); 138 | } 139 | return memberValues; 140 | } 141 | 142 | public override string ToString() 143 | { 144 | return this.Type.ToString(); 145 | } 146 | 147 | #region static 148 | private static string[] _Namespaces = { "System", "System.Collections.Generic" }; 149 | internal static string GetFullName(Type type) 150 | { 151 | var underlying = Nullable.GetUnderlyingType(type); 152 | if (underlying != null) 153 | { 154 | return GetFullName(underlying) + "?"; 155 | } 156 | 157 | if (type.IsArray) 158 | { 159 | return GetFullName(type.GetElementType()) + "[]"; 160 | } 161 | 162 | var fullName = _Namespaces.Contains(type.Namespace) ? type.Name : type.FullName; 163 | 164 | if (type.IsGenericType) 165 | { 166 | if (fullName.StartsWith("<>", StringComparison.Ordinal)) 167 | { 168 | return _AnonymousLabel; 169 | } 170 | 171 | int index = fullName.IndexOf('`'); 172 | if (index != -1) 173 | { 174 | fullName = fullName.Substring(0, index); 175 | } 176 | 177 | var genericArgs = type.GetGenericArguments(); 178 | fullName += 179 | "<" + 180 | string.Join(", ", genericArgs.Select(t => GetFullName(t))) + 181 | ">"; 182 | } 183 | 184 | return fullName; 185 | } 186 | 187 | private delegate void GetGenericEnumeratorDelegate(object enumerable, out IEnumerator enumerator, out IDisposable disposable, out int? count); 188 | 189 | private static void GetGenericEnumerator(object enumerable, out IEnumerator enumerator, out IDisposable disposable, out int? count) 190 | { 191 | var genericEnumerator = ((IEnumerable)enumerable).GetEnumerator(); 192 | enumerator = (IEnumerator)genericEnumerator; 193 | disposable = (IDisposable)genericEnumerator; 194 | 195 | var collection = enumerable as ICollection; 196 | count = collection == null ? (int?)null : collection.Count; 197 | } 198 | 199 | private static MethodInfo _GenericDefinition = ((GetGenericEnumeratorDelegate)GetGenericEnumerator).Method.GetGenericMethodDefinition(); 200 | private static GetGenericEnumeratorDelegate CreateDelegate(Type itemType) 201 | { 202 | return (GetGenericEnumeratorDelegate)Delegate.CreateDelegate( 203 | typeof(GetGenericEnumeratorDelegate), 204 | _GenericDefinition.MakeGenericMethod(itemType)); 205 | } 206 | 207 | 208 | 209 | private static Dictionary _Cache = new Dictionary(); 210 | [ThreadStatic] 211 | static Stack _UnderConstruction; 212 | 213 | public static TypeDetails Get(Type type) 214 | { 215 | TypeDetails md; 216 | lock (_Cache) 217 | { 218 | if (_Cache.TryGetValue(type, out md)) 219 | { 220 | return md; 221 | } 222 | } 223 | 224 | var underConstruction = _UnderConstruction; 225 | if (underConstruction == null) 226 | { 227 | _UnderConstruction = new Stack(); 228 | } 229 | else 230 | { 231 | md = underConstruction.FirstOrDefault(td => td.Type == type); 232 | if (md != null) return md; 233 | } 234 | 235 | md = new TypeDetails(type); 236 | 237 | lock (_Cache) 238 | { 239 | _Cache[type] = md; 240 | } 241 | return md; 242 | } 243 | #endregion 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /CoreDemo/CoreDemo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /CoreDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using DemoLib; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Net; 7 | 8 | namespace CoreDemo 9 | { 10 | public class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | new CoreDemo().Run(); 15 | } 16 | 17 | class CoreDemo : Demo 18 | { 19 | protected override void ServiceStackPrintDump(T it) 20 | { 21 | ServiceStack.Text.TypeSerializer.PrintDump(it); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /DemoLib/Demo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Net; 6 | 7 | namespace DemoLib 8 | { 9 | public abstract class Demo 10 | { 11 | public struct WhateverStruct 12 | { 13 | public readonly int Top; 14 | public readonly int Right; 15 | public readonly int Bottom; 16 | public readonly int Left; 17 | 18 | public WhateverStruct(int t, int r, int b, int l) 19 | { 20 | Top = t; 21 | Right = r; 22 | Bottom = b; 23 | Left = l; 24 | } 25 | 26 | public override string ToString() 27 | { 28 | return String.Format("t: {0}, r: {1}, b: {2}, l = {3}", Top, Right, Bottom, Left); 29 | } 30 | } 31 | 32 | static IEnumerable Forever() 33 | { 34 | uint num = 0; 35 | while (true) 36 | { 37 | yield return unchecked(num++); 38 | } 39 | } 40 | 41 | public void Run() 42 | { 43 | Show("foo"); 44 | 45 | Show(42); 46 | 47 | Show(new 48 | { 49 | Int32 = 1, 50 | String = "sssstring", 51 | NullObject = (object)null, 52 | Boolean = true, 53 | DateTime = DateTime.UtcNow, 54 | SomeClass = Version.Parse("1.0"), 55 | SomeStruct = new KeyValuePair(1, 1), 56 | }); 57 | 58 | Show(new[] { 1, 22, 333, 4444 }); 59 | 60 | Show(IPAddress.Parse("1.1.1.1")); 61 | 62 | Show(Enumerable.Range(0, 100).ToList()); 63 | 64 | Show(new[] { new { a = 1 }, null, new { a = 1 }, }); 65 | 66 | 67 | Show(Enumerable.Range(4, 8).ToDictionary( 68 | n => n, 69 | n => Convert.ToString(-1 + (long)Math.Pow(2, n), 2))); 70 | 71 | Show(new ArgumentException("my message", "someParam")); 72 | 73 | Show(new WhateverStruct(1, 2, 3, 4)); 74 | 75 | var bigExample = new[] { 200, 201, 202, 400, 404 } 76 | .Select((c, i) => new 77 | { 78 | StringProp = ((HttpStatusCode)c).ToString(), 79 | EnumProp = (HttpStatusCode)c, 80 | NullableInt = i % 3 == 0 ? null : (int?)c, 81 | BiggerInt = (int)Math.Pow(2, i * 4), 82 | IPAddress = i % 3 == 2 ? null : IPAddress.Parse("1.1.1." + (i * 32)), 83 | }); 84 | Show(bigExample); 85 | 86 | ConsoleDump.Extensions.Dump(Forever().Take(5).ToList(), "small list"); 87 | ConsoleDump.Extensions.Dump(Forever().Take(50).ToList(), "bigger list"); 88 | ConsoleDump.Extensions.Dump(Forever(), "infinite enumerable"); 89 | 90 | ConsoleDump.Extensions.Dump(bigExample); 91 | ConsoleDump.Extensions.Dump(IPAddress.Loopback, ".Dump() output can be labeled."); 92 | TakeScreenShot("simple-ip", ++Count); 93 | 94 | var datatable = GetDataTable(); 95 | ConsoleDump.Extensions.Dump(datatable, "datatable label"); 96 | ConsoleDump.Extensions.RowLimit = 64; 97 | ConsoleDump.Extensions.Dump(datatable); 98 | TakeScreenShot("datatable", ++Count); 99 | 100 | ConsoleDump.Extensions.RowLimit = null; 101 | var dataset = new DataSet(); 102 | dataset.Tables.Add(datatable); 103 | ConsoleDump.Extensions.Dump(dataset, "dataset label"); 104 | ConsoleDump.Extensions.Dump(dataset); 105 | TakeScreenShot("dataset", ++Count); 106 | 107 | //Extensions.Dump(new 108 | //{ 109 | // Console.BufferHeight, 110 | // Console.LargestWindowHeight, 111 | // Console.WindowHeight, 112 | //}); 113 | //Console.ReadKey(); 114 | } 115 | 116 | private static DataTable GetDataTable() 117 | { 118 | var dt = new DataTable(); 119 | dt.Columns.Add("foo", typeof(int)); 120 | dt.Columns.Add("bar", typeof(string)); 121 | dt.Columns.Add("bop", typeof(DateTime)); 122 | 123 | var rand = new Random(42); 124 | 125 | for (int i = 0; i < 30; i++) 126 | { 127 | var row = dt.NewRow(); 128 | row[0] = rand.Next() % 4 == 0 ? (object)DBNull.Value : rand.Next(256); 129 | row[1] = rand.Next() % 4 == 0 ? (object)DBNull.Value : "_" + rand.Next(256); 130 | row[2] = rand.Next() % 4 == 0 ? (object)DBNull.Value : new DateTime(2018, 1, rand.Next(1, 31), 0, 0, 0, DateTimeKind.Utc); 131 | 132 | dt.Rows.Add(row); 133 | } 134 | 135 | return dt; 136 | } 137 | 138 | int Count = 0; 139 | protected virtual void Show(T it) 140 | { 141 | Console.WriteLine("// Example: " + (++Count)); 142 | 143 | Console.WriteLine(); 144 | Console.WriteLine("// Console.WriteLine"); 145 | Console.WriteLine(it); 146 | TakeScreenShot("console", Count); 147 | 148 | Console.WriteLine(); 149 | Console.WriteLine("// ServiceStack.Text.TypeSerializer.PrintDump"); 150 | try 151 | { 152 | ServiceStackPrintDump(it); 153 | } 154 | catch (Exception e) 155 | { 156 | Console.WriteLine(e); 157 | } 158 | TakeScreenShot("servicestack", Count); 159 | 160 | Console.WriteLine(); 161 | Console.WriteLine("// ConsoleDump"); 162 | ConsoleDump.Extensions.Dump(it); 163 | TakeScreenShot("consoledump", Count); 164 | 165 | ConsoleDump.Extensions.Dump(it, "ConsoleDump label"); 166 | 167 | ConsoleDump.Extensions.DumpObject(it, "as object"); 168 | } 169 | 170 | protected abstract void ServiceStackPrintDump(T it); 171 | 172 | protected virtual void TakeScreenShot(string label, int example) 173 | { 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /DemoLib/DemoLib.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ConsoleDump 2 | =========== 3 | 4 | **Visualize your collections and objects in color at the console.** 5 | 6 | ![Example output](http://cameronism.github.io/ConsoleDump/images/consoledump-example.png) 7 | 8 | `Console.WriteLine(...)` 9 | cannot begin to compare to [LINQPad](http://www.linqpad.net/)'s `.Dump()` extension method. This library 10 | provides a `.Dump()` extension method that can be used in console apps 11 | and in [scriptcs](http://scriptcs.net/). 12 | 13 | The output above was created with the following code: 14 | ```csharp 15 | new[] { 200, 201, 202, 400, 404 }.Select(CreateSillyExample).Dump(); 16 | 17 | IPAddress.Loopback.Dump(".Dump() output can be labeled."); 18 | ``` 19 | 20 | Features 21 | --------- 22 | 23 | - Available via NuGet: `PM> Install-Package ConsoleDump` 24 | - Single dll, depends only on .NET 4.0 Client Profile 25 | - Output colors based on type: 26 | * `null` is green 27 | * Strings are cyan 28 | * Primitives, enums and nullable primitives are white 29 | * `.ToString()` from a class is purple 30 | * `.ToString()` from a struct is yellow 31 | * If a property throws an exception the exception is shown in red 32 | - Numbers are right aligned 33 | - `IEnumerable<>` support 34 | * Displays count (if available) 35 | * Safe for infinite `IEnumerable<>` 36 | * Only the first 24 items are displayed 37 | - Much more concise and readable than JSON in the console 38 | 39 | 40 | 41 | Disclaimer 42 | ------------- 43 | 44 | This project is not affiliated with [LINQPad](http://www.linqpad.net/) or its author [Joseph Albahari](http://www.albahari.com/). 45 | I've been completely spoiled by an amazing tool and I am trying to keep some of the convenience when working at the console. 46 | Download [LINQPad](http://www.linqpad.net/), it's free; [activate autocompletion](http://www.linqpad.net/Purchase.aspx), it's far 47 | and away the best .NET tool. 48 | 49 | 50 | 51 | TODO 52 | ----- 53 | 54 | - Improve this document 55 | - Improve "count" wording on enumerable views 56 | - Refine colors 57 | - Truncate long strings 58 | - Truncate or omit columns if `IEnumerable<>` view is too wide for screen 59 | - Investigate [scriptcs REPL](http://scriptcs.net/) integration 60 | 61 | 62 | License 63 | --------- 64 | 65 | Apache 2 66 | -------------------------------------------------------------------------------- /WindowsDemo/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /WindowsDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing.Imaging; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace WindowsDemo 11 | { 12 | class Program 13 | { 14 | static void Main(string[] args) 15 | { 16 | new WindowsDemo().Run(); 17 | } 18 | 19 | class WindowsDemo : DemoLib.Demo 20 | { 21 | protected override void ServiceStackPrintDump(T it) 22 | { 23 | ServiceStack.Text.TypeSerializer.PrintDump(it); 24 | } 25 | 26 | protected override void TakeScreenShot(string label, int example) 27 | { 28 | Thread.Sleep(1); 29 | // crop the edges of my powershell window 30 | var img = ScreenShotDemo.ScreenCapture.CaptureWindow(GetConsoleWindow(), 32, 10, 10, 27); 31 | img.Save(String.Format("{0:d2}_{1}.png", example, label), ImageFormat.Png); 32 | } 33 | 34 | } 35 | 36 | [DllImport("kernel32.dll")] 37 | internal static extern IntPtr GetConsoleWindow(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /WindowsDemo/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("WindowsDemo")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("WindowsDemo")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e5eccb5a-efd9-44c5-bacf-5ac41fc311da")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /WindowsDemo/ScreenShotDemo.cs: -------------------------------------------------------------------------------- 1 | // http://www.developerfusion.com/code/4630/capture-a-screen-shot/ 2 | 3 | using System; 4 | using System.Runtime.InteropServices; 5 | using System.Drawing; 6 | using System.Drawing.Imaging; 7 | namespace ScreenShotDemo 8 | { 9 | /// 10 | /// Provides functions to capture the entire screen, or a particular window, and save it to a file. 11 | /// 12 | public static class ScreenCapture 13 | { 14 | /// 15 | /// Creates an Image object containing a screen shot of the entire desktop 16 | /// 17 | /// 18 | public static Image CaptureScreen() 19 | { 20 | return CaptureWindow(User32.GetDesktopWindow()); 21 | } 22 | /// 23 | /// Creates an Image object containing a screen shot of a specific window 24 | /// 25 | /// The handle to the window. (In windows forms, this is obtained by the Handle property) 26 | /// 27 | public static Image CaptureWindow(IntPtr handle, byte topOffset = 0, byte leftOffset = 0, byte bottomOffset = 0, byte rightOffset = 0) 28 | { 29 | // get te hDC of the target window 30 | IntPtr hdcSrc = User32.GetWindowDC(handle); 31 | // get the size 32 | User32.RECT windowRect = new User32.RECT(); 33 | User32.GetWindowRect(handle, ref windowRect); 34 | int width = (windowRect.right - windowRect.left) - (leftOffset + rightOffset); 35 | int height = (windowRect.bottom - windowRect.top) - (topOffset + bottomOffset); 36 | // create a device context we can copy to 37 | IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); 38 | // create a bitmap we can copy it to, 39 | // using GetDeviceCaps to get the width/height 40 | IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height); 41 | // select the bitmap object 42 | IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap); 43 | // bitblt over 44 | GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, leftOffset, topOffset, GDI32.SRCCOPY); 45 | // restore selection 46 | GDI32.SelectObject(hdcDest, hOld); 47 | // clean up 48 | GDI32.DeleteDC(hdcDest); 49 | User32.ReleaseDC(handle, hdcSrc); 50 | // get a .NET image object for it 51 | Image img = Image.FromHbitmap(hBitmap); 52 | // free up the Bitmap object 53 | GDI32.DeleteObject(hBitmap); 54 | return img; 55 | } 56 | /// 57 | /// Captures a screen shot of a specific window, and saves it to a file 58 | /// 59 | /// 60 | /// 61 | /// 62 | public static void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) 63 | { 64 | Image img = CaptureWindow(handle); 65 | img.Save(filename, format); 66 | } 67 | /// 68 | /// Captures a screen shot of the entire desktop, and saves it to a file 69 | /// 70 | /// 71 | /// 72 | public static void CaptureScreenToFile(string filename, ImageFormat format) 73 | { 74 | Image img = CaptureScreen(); 75 | img.Save(filename, format); 76 | } 77 | 78 | /// 79 | /// Helper class containing Gdi32 API functions 80 | /// 81 | private class GDI32 82 | { 83 | 84 | public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter 85 | [DllImport("gdi32.dll")] 86 | public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, 87 | int nWidth, int nHeight, IntPtr hObjectSource, 88 | int nXSrc, int nYSrc, int dwRop); 89 | [DllImport("gdi32.dll")] 90 | public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, 91 | int nHeight); 92 | [DllImport("gdi32.dll")] 93 | public static extern IntPtr CreateCompatibleDC(IntPtr hDC); 94 | [DllImport("gdi32.dll")] 95 | public static extern bool DeleteDC(IntPtr hDC); 96 | [DllImport("gdi32.dll")] 97 | public static extern bool DeleteObject(IntPtr hObject); 98 | [DllImport("gdi32.dll")] 99 | public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); 100 | } 101 | 102 | /// 103 | /// Helper class containing User32 API functions 104 | /// 105 | private class User32 106 | { 107 | [StructLayout(LayoutKind.Sequential)] 108 | public struct RECT 109 | { 110 | public int left; 111 | public int top; 112 | public int right; 113 | public int bottom; 114 | } 115 | [DllImport("user32.dll")] 116 | public static extern IntPtr GetDesktopWindow(); 117 | [DllImport("user32.dll")] 118 | public static extern IntPtr GetWindowDC(IntPtr hWnd); 119 | [DllImport("user32.dll")] 120 | public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC); 121 | [DllImport("user32.dll")] 122 | public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect); 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /WindowsDemo/WindowsDemo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E5ECCB5A-EFD9-44C5-BACF-5AC41FC311DA} 8 | Exe 9 | WindowsDemo 10 | WindowsDemo 11 | v4.6.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\ServiceStack.Text.5.0.2\lib\net45\ServiceStack.Text.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | {82fb80a8-f660-430e-9a23-ae12f4e80217} 60 | ConsoleDump 61 | 62 | 63 | {f1e3277d-062f-4729-993d-92e18674abbc} 64 | DemoLib 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /WindowsDemo/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | --------------------------------------------------------------------------------