My favorites
▼
|
Sign in
Project Hosting will be READ-ONLY
Thursday at 3:00pm UTC
for up to 3 hours for network maintenance.
xsharper
Framework for writing console applications in .NET
Project Home
Downloads
Issues
Source
Checkout
Browse
Changes
Source path:
svn
/
trunk
/
XSharper.Core
/
Reusables
/
Dump.cs
‹r18
r95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
#region -- Copyrights --
// ***********************************************************************
// This file is a part of XSharper (http://xsharper.com)
//
// Copyright (C) 2006 - 2010, Alexei Shamov, DeltaX Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ************************************************************************
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace XSharper.Core
{
/// Dump configuration
public class DumpSettings
{
/// <summary>
/// Maximum number of list or IEnumerable items to display
/// </summary>
public int MaxItems = 50;
/// <summary>
/// true = display private members of the class/struct
/// </summary>
public bool DisplayPrivate = false;
/// <summary>
/// Limit tree depth to this (default 5)
/// </summary>
public int MaxDepth = 5;
/// <summary>
/// Use full class names
/// </summary>
public bool UseFullClassNames = false;
}
/// <summary>
/// Utility class to dump all properties and fields of the object to the output
/// </summary>
public class Dump
{
#region --- Constructors ---
/// Constructor
public Dump(object objectToDump)
: this(objectToDump, null, null, 0)
{
}
/// Constructor with explicit type specification
public Dump(object objectToDump, Type type)
: this(objectToDump, type, null, 0)
{
}
/// Constructor with explicit type specification
public Dump(object objectToDump, DumpSettings settings)
: this(objectToDump, null, null, 0, settings)
{
}
/// Constructor with explicit type specification and prefix
public Dump(object objectToDump, Type type, string name)
: this(objectToDump, type, name, 0)
{
}
/// Constructor with explicit type specification, prefix, indent level
public Dump(object objectToDump, Type type, string name, int level)
: this(objectToDump, type, name, level, s_defaultSettings)
{
}
/// Constructor with explicit type specification
public Dump(object objectToDump, Type type, DumpSettings settings)
: this(objectToDump, type, null, 0, settings)
{
}
/// Constructor with explicit type specification, prefix, indent level and depth level
public Dump(object objectToDump, Type type, string name, int level, DumpSettings settings)
{
_object = objectToDump;
_type = type;
if (_type == null)
if (objectToDump != null)
_type = objectToDump.GetType();
else
_type = typeof(object);
_name = name;
_level = level;
_settings = settings ?? s_defaultSettings;
}
#endregion
/// Returns dump of the object
public override string ToString()
{
try
{
_out.Length = 0;
process2(_name, _type, _object, _level);
return _out.ToString();
}
catch (Exception e)
{
return "??? thrown " + e.GetType().FullName;
}
}
#region --- ToDump static methods ---
/// Dump object to string
public static string ToDump<T>(T objectToDump)
{
return ToDump<T>(objectToDump, null, null);
}
/// Dump object to string
public static string ToDump<T>(T objectToDump, DumpSettings settings)
{
return ToDump<T>(objectToDump, null, settings);
}
/// Dump object to string, adding 'name=' prefix before output
public static string ToDump<T>(T objectToDump, string name)
{
return ToDump(objectToDump, name, null);
}
/// Dump object to string, adding 'name=' prefix before output
public static string ToDump<T>(T objectToDump, string name, DumpSettings settings)
{
return ToDump(objectToDump, (objectToDump == null) ? typeof(T) : objectToDump.GetType(), name, settings);
}
/// Dump object to string, interpreting object as the object of type
public static string ToDump(object objectToDump, Type type)
{
return ToDump(objectToDump, type, string.Empty);
}
/// Dump object to string, interpreting object as the object of type , adding 'name=' prefix before output
public static string ToDump(object objectToDump, Type type, string name)
{
return new Dump(objectToDump, type, name, 0).ToString();
}
/// Dump object to string, interpreting object as the object of type , adding 'name=' prefix before output
public static string ToDump(object objectToDump, Type type, string name, DumpSettings settings)
{
return new Dump(objectToDump, type, name, 0, settings).ToString();
}
/// Dump object to string, interpreting object as the object of type , adding 'name=' prefix before output
public static string ToDump(object objectToDump, Type type, string name, int level)
{
return new Dump(objectToDump, type, name, level).ToString();
}
/// Dump object to string, interpreting object as the object of type , adding 'name=' prefix before output
public static string ToDump(object objectToDump, Type type, string name, int level, DumpSettings settings)
{
return new Dump(objectToDump, type, name, level, settings).ToString();
}
#endregion
#region -- Public static utility methods --
/// <summary>
/// Return a user-friendly type name of a given type. For example, int?[] instead of the default name
/// </summary>
/// <param name="type">Type</param>
/// <returns>Type name</returns>
static public string GetFriendlyTypeName(Type type)
{
return GetFriendlyTypeName(type, false);
}
/// <summary>
/// Return a user-friendly type name of a given type. For example, int?[] instead of the default name
/// </summary>
/// <param name="type">Type</param>
/// <param name="fullName">Return full name of the type</param>
/// <returns>Type name</returns>
static public string GetFriendlyTypeName(Type type, bool fullName)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type st = Nullable.GetUnderlyingType(type);
if (st != null)
return GetFriendlyTypeName(st) + "?";
return "T?";
}
if (type.IsArray)
return GetFriendlyTypeName(type.GetElementType()) + "[" + new string(',', type.GetArrayRank() - 1) + "]";
string s;
if (!fullName && s_friendlyName.TryGetValue(type, out s))
return s;
string name = fullName ? type.FullName : type.Name;
if (type.IsGenericParameter || type.IsPrimitive || !type.IsGenericType || type == typeof(decimal))
return name;
StringBuilder builder = new StringBuilder();
int index = name.IndexOf('`');
if (index == -1)
builder.Append(name);
else
builder.Append(name.Substring(0, index));
builder.Append('<');
bool first = true;
foreach (Type arg in type.GetGenericArguments())
{
if (!first)
{
builder.Append(',');
}
builder.Append(GetFriendlyTypeName(arg));
first = false;
}
builder.Append('>');
return builder.ToString();
}
#endregion
#region -- Static configuration methods --
/// Mark type as bloat. For bloattypes its ToString() output is copied to the dump instead of the proper tree walking.
public static void AddBloatType(Type exc)
{
lock (s_bloatTypes)
s_bloatTypes[exc.FullName] = true;
}
/// Mark type as bloat . For bloat types its ToString() output is copied to the dump instead of the proper tree walking.
public static void AddBloatType(string typename)
{
lock (s_bloatTypes)
s_bloatTypes.Add(typename, true);
}
/// Mark a property as bloat . For bloat properties its ToString() output is copied to the dump instead of the proper tree walking.
public static void AddBloatProperty(Type type, string propertyName)
{
addProperty(type, propertyName, false);
}
/// Mark a property as one that should not be dumped, for example if the property has a side effect.
public static void AddHiddenProperty(Type type, string propertyName)
{
addProperty(type, propertyName, true);
}
/// Add a friendly type name
public static void AddTypeName(Type type, string typename)
{
lock (s_bloatTypes)
s_friendlyName.Add(type, typename);
}
#endregion
#region --- Implementation details ---
private readonly object _object;
private readonly Type _type;
private readonly string _name;
private readonly int _level;
private readonly DumpSettings _settings;
private static readonly DumpSettings s_defaultSettings = new DumpSettings();
private static void addProperty(Type type, string propertyName, bool sideEffect)
{
lock (s_propertyHints)
{
Dictionary<string, bool> prop;
if (!s_propertyHints.TryGetValue(type, out prop))
{
prop = new Dictionary<string, bool>();
s_propertyHints.Add(type, prop);
}
prop[propertyName] = sideEffect;
}
}
private class ReferenceComparer : IEqualityComparer<object>
{
bool IEqualityComparer<object>.Equals(object x, object y)
{
return ReferenceEquals(x, y);
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
if (ReferenceEquals(obj, null))
return 0;
return obj.GetHashCode();
}
}
private static readonly Dictionary<string, bool> s_bloatTypes = initBloatTypes();
// For each special store true=side effect, false=bloat
private static readonly Dictionary<Type, Dictionary<string, bool>> s_propertyHints = initPropertyHints();
private static readonly Dictionary<Type, string> s_friendlyName = initFriendlyNames();
private static Dictionary<string, bool> initBloatTypes()
{
Dictionary<string, bool> ret = new Dictionary<string, bool>();
foreach (string s in new string[] {"System.DateTime",
"System.Type",
"System.Guid",
"System.Security.Principal.SecurityIdentifier",
"System.Xml.Linq.XElement",
"System.Xml.Linq.XDocument",
"System.Reflection.RuntimeConstructorInfo",
"System.Reflection.RuntimePropertyInfo",
"System.Reflection.RuntimeMethodInfo",
"System.RuntimeType",
"System.Reflection.MethodBase",
"System.Security.Policy.Evidence",
"System.Globalization.CultureInfo",
"System.Version"})
ret[s] = true;
return ret;
}
private static Dictionary<Type, string> initFriendlyNames()
{
Dictionary<Type, string> r = new Dictionary<Type, string>();
r.Add(typeof(string), "string");
r.Add(typeof(int), "int");
r.Add(typeof(uint), "uint");
r.Add(typeof(long), "long");
r.Add(typeof(ulong), "ulong");
r.Add(typeof(short), "short");
r.Add(typeof(ushort), "ushort");
r.Add(typeof(char), "char");
r.Add(typeof(byte), "byte");
r.Add(typeof(decimal), "decimal");
r.Add(typeof(object), "object");
r.Add(typeof(void), "void");
r.Add(typeof(bool), "bool");
return r;
}
private static Dictionary<Type, Dictionary<string, bool>> initPropertyHints()
{
Dictionary<Type, Dictionary<string, bool>> s = new Dictionary<Type, Dictionary<string, bool>>();
// FileSystemInfo Parent and Root properties are examples of "bloat" properties and should be dumped with ToString
Dictionary<string, bool> data = new Dictionary<string, bool>();
data["Parent"] = false;
data["Root"] = false;
s[typeof(FileSystemInfo)] = data;
return s;
}
private readonly StringBuilder _out = new StringBuilder(10000);
readonly Dictionary<object, int> _usedMap = new Dictionary<object, int>(new ReferenceComparer());
private int _counter = 0;
void process2(string name, Type t, object o, int depth)
{
string typeName = GetFriendlyTypeName(t, _settings.UseFullClassNames);
_out.Append(new string(' ', depth * 2));
if (!string.IsNullOrEmpty(name))
_out.Append(name + " = ");
_out.Append("(" + typeName + ") ");
if (o == null)
{
_out.Append("<null>");
return;
}
if ((t != typeof(string) && (o is string)) || _settings.MaxDepth <= depth)
{
_out.Append("\"" + toEscapedString(o) + "\" /* ToString */");
return;
}
if (t == typeof(string) || (o is string))
{
_out.Append("\"" + toEscapedString(o) + "\"");
return;
}
BindingFlags flags = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public;
if (_settings.DisplayPrivate)
flags |= BindingFlags.NonPublic;
PropertyInfo[] props = t.GetProperties(flags | BindingFlags.GetProperty);
FieldInfo[] fi = t.GetFields(flags);
if (t.IsPrimitive || t.IsEnum || (t.IsValueType && props.Length == 0 && fi.Length == 0) || s_bloatTypes.ContainsKey(t.FullName) || t == typeof(decimal))
{
if ((t == typeof(int)) || (t == typeof(byte)) || (t == typeof(uint)) || t == typeof(long) ||
t == typeof(ulong))
_out.AppendFormat(" {0} (0x{0:x})", o);
else if (t == typeof(DateTime) || t == typeof(DateTime?))
_out.AppendFormat("{0:o} ({1})", o, ((DateTime)o).Kind);
else if (t == typeof(Guid))
_out.Append(((Guid)o).ToString("B"));
else if (t == typeof(bool))
_out.Append(((bool)o) ? "true" : "false");
else if (t.IsEnum)
_out.AppendFormat("[{0}] /* 0x{0:x} */", o);
else
_out.AppendFormat("[{0}]", toEscapedString(o));
return;
}
if (t.IsClass)
{
int id;
if (_usedMap.TryGetValue(o, out id))
{
_out.AppendFormat("<see #{0}, {1:x8} above>", id, o.GetHashCode());
return;
}
_usedMap[o] = ++_counter;
}
if (t.IsArray && ((Array)o).Rank == 1)
{
Array arr;
if (t.IsArray)
arr = (o as Array);
else
arr = t.GetMethod("ToArray").Invoke(o, new object[] { }) as Array;
processArray(t, arr, depth);
}
else if (o as IEnumerable != null)
{
writeBrace(o);
processEnumerables(o as IEnumerable, depth);
}
else
{
writeBrace(o);
Dictionary<string, bool> propNames = null;
foreach (KeyValuePair<Type, Dictionary<string, bool>> info in s_propertyHints)
if (t == info.Key || t.IsSubclassOf(info.Key))
{
propNames = info.Value;
break;
}
foreach (PropertyInfo p in props)
{
bool sideEffect;
if (propNames != null && propNames.TryGetValue(p.Name, out sideEffect))
{
if (!sideEffect)
dumpProperty(p, o, depth + 1, true);
else
{
process2(p.Name, p.PropertyType, "<ignored>", depth + 1);
_out.AppendLine();
}
}
else
dumpProperty(p, o, depth + 1, false);
}
foreach (FieldInfo f in fi)
dumpField(f, o, depth + 1);
}
_out.Append(new string(' ', depth * 2));
_out.Append("}");
}
private static string toEscapedString(object o)
{
return o.ToString().Replace("\r", "\\r").Replace("\n", "\\n").Replace("\b", "\\b").Replace("\t", "\\t");
}
private void writeBrace(object o)
{
_out.AppendFormat("{{ /* #{0}, {1:x8} */ ", _counter, o.GetHashCode());
_out.AppendLine();
}
private void dumpProperty(PropertyInfo p, object o, int level, bool asString)
{
try
{
if (p.GetIndexParameters().Length == 0)
{
object obj = p.GetValue(o, null);
if (asString)
process2(p.Name, (obj == null) ? p.PropertyType : obj.GetType(), (obj ?? "<null>").ToString(), level);
else
process2(p.Name, (obj == null) ? p.PropertyType : obj.GetType(), obj, level);
_out.AppendLine();
}
else
{
_out.Append(new string(' ', level * 2));
_out.AppendLine(p.Name + " = " + "(" + GetFriendlyTypeName(p.PropertyType) + ") ??? indexed property ignored");
}
}
catch (Exception e)
{
_out.Append(new string(' ', level * 2));
_out.AppendLine(p.Name + " = " + "??? thrown " + e.GetType().FullName);
}
}
private void dumpField(FieldInfo p, object o, int level)
{
try
{
object obj = p.GetValue(o);
process2(p.Name, (obj == null) ? p.FieldType : obj.GetType(), obj, level);
_out.AppendLine();
}
catch (Exception e)
{
_out.Append(new string(' ', level * 2));
_out.AppendLine(p.Name + " = " + "??? thrown " + e.GetType().FullName);
}
}
private void processEnumerables(IEnumerable enumerable, int nLevel)
{
int index = 0;
foreach (object info in enumerable)
{
Type tinside = info == null ? typeof(object) : info.GetType();
process2("[" + index + "]", tinside, info, nLevel + 1);
_out.AppendLine();
if (index++ > _settings.MaxItems)
{
_out.AppendLine("...");
break;
}
}
}
private void processArray(Type t, Array arr, int nLevel)
{
Type tInside = t.GetElementType();
if (tInside == typeof(byte))
{
byte[] b = (byte[])arr;
_out.AppendFormat(" {0} bytes [ ", arr.Length);
for (int i = 0; i < b.Length; ++i)
{
if (i != 0)
_out.Append(' ');
_out.Append(b[i].ToString("x2"));
if (i > _settings.MaxItems)
{
_out.Append("...");
break;
}
}
_out.Append(" ]");
return;
}
_out.Append(" array[" + arr.Length + "] ");
writeBrace(arr);
processEnumerables(arr, nLevel);
}
#endregion
}
}
Show details
Hide details
Change log
r75
by xsharper.root on Apr 25, 2011
Diff
[No log message]
Go to:
....Core/Properties/AssemblyInfo.cs
.../XSharper.Core/Reusables/Dump.cs
...arper/Properties/AssemblyInfo.cs
...k/XSharper/Resources/xsharper.rc
Project members,
sign in
to write a code review
Older revisions
r18
by xsharper.root on Apr 21, 2010
Diff
Added sample code, some bug fixes
r17
by xsharper.root on Apr 18, 2010
Diff
[No log message]
r2
by xsharper.root on Mar 25, 2010
Diff
[No log message]
All revisions of this file
File info
Size: 23402 bytes, 602 lines
View raw file
Powered by
Google Project Hosting