andrew4582

ObjectWriter

Apr 10th, 2011
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.29 KB | None | 0 0
  1. namespace System.Diagnostics {
  2.     using System;
  3.     using System.CodeDom.Compiler;
  4.     using System.Collections.Generic;
  5.     using System.ComponentModel;
  6.     using System.IO;
  7.     using System.Linq;
  8.     using System.Text;
  9.     using System.Collections;
  10.  
  11.     #region ObjectWriter class
  12.  
  13.     public static class ObjectWriter {
  14.  
  15.         public const int DEFAULT_MAXDEPTH = 6;
  16.  
  17.         static int _maxDepth = DEFAULT_MAXDEPTH;
  18.  
  19.         public static int MaxDepth {
  20.             get { return _maxDepth; }
  21.             set {
  22.                 _maxDepth = Math.Max(1,value);
  23.             }
  24.         }
  25.  
  26.         /// <summary>
  27.         /// Traces an object's properties using reflection
  28.         /// </summary>
  29.         /// <param name="obj">The object to be traced</param>
  30.         /// <param name="builder">Optional StringBuilder to append the trace to</param>
  31.         public static void TraceObject(object obj,int depth = -1,StringBuilder builder = null,bool html = false,string tabString = null) {
  32.  
  33.             if(obj == null)
  34.                 throw new ArgumentNullException("obj");
  35.  
  36.             builder = builder ?? new StringBuilder();
  37.  
  38.             WriteObject(obj,depth,builder,html,tabString);
  39.  
  40.             Trace.Write(builder.ToString());
  41.  
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Debugs an object's properties using reflection
  46.         /// </summary>
  47.         /// <param name="obj">The object to be debugged</param>
  48.         /// <param name="builder">Optional StringBuilder to append the debug to</param>
  49.         public static void DebugObject(object obj,int depth = -1,StringBuilder builder = null,bool html = false,string tabString = null) {
  50.             if(obj == null)
  51.                 throw new ArgumentNullException("obj");
  52.  
  53.             builder = builder ?? new StringBuilder();
  54.  
  55.             WriteObject(obj,depth,builder,html,tabString);
  56.  
  57.             Debug.Write(builder.ToString());
  58.  
  59.         }
  60.  
  61.         public static string WriteObjectString(object obj,int depth = -1,bool html = false) {
  62.             StringBuilder builder = new StringBuilder();
  63.             WriteObject(obj,depth,builder,html);
  64.             return builder.ToString();
  65.         }
  66.         /// <summary>
  67.         /// Writes the object's properties to a StringBuilder using reflection
  68.         /// </summary>
  69.         /// <param name="obj">The object to be written</param>
  70.         /// <param name="builder">Optional StringBuilder to append the trace to</param>
  71.         public static void WriteObject(object obj,int depth = -1,StringBuilder builder = null,bool html = false,string tabString = null) {
  72.  
  73.             if(obj == null)
  74.                 throw new ArgumentNullException("obj");
  75.  
  76.             builder = builder ?? new StringBuilder();
  77.  
  78.             tabString = tabString ?? IndentedTextWriter.DefaultTabString;
  79.             if(html) {
  80.                 tabString = "<span class='t'>&nbsp;</span>";
  81.             }
  82.             using(IndentedTextWriter writer = new IndentedTextWriter(new StringWriter(builder),tabString)) {
  83.  
  84.                 if(html) {
  85.                     writer.NewLine = "<br/>" + Environment.NewLine;
  86.  
  87.                     writer.Write(
  88. @"
  89. <style type='text/css'>
  90.    .output {line-height:12px;}
  91.    .t {margin-right:10px;}
  92.    fieldset {margin:10px; padding:10px;border: .5px solid red;}
  93.    legend {}
  94.    fieldset ul {}
  95.    fieldset ul li{}
  96.    fieldset table {margin:0px; margin-top:0px; width:80%;}
  97.    td.pn {width:30%;text-align:left;}
  98.    td.pv {width:80%;text-align:left;color:darkgreen;}
  99.    fieldset h2 {font-weight:bold;font-size:16px;display:inline;color:blue;}
  100. </style>
  101. ");
  102.                 }
  103.                 writer.WriteLine("<div class='output'>");
  104.                 WriteObjectInternal(obj,writer,depth,html);
  105.  
  106.                 if(html) {
  107.                     writer.WriteLine("</div>");
  108.                 }
  109.             }
  110.         }
  111.         /// <summary>
  112.         /// Writes an object's properties using reflection
  113.         /// </summary>
  114.         /// <param name="obj">The object to be traced</param>
  115.         /// <param name="builder">Optional StringBuilder to append the trace to</param>
  116.         static void WriteObjectInternal(object obj,IndentedTextWriter writer,int depth = -1,bool html = false) {
  117.  
  118.             if(depth == -1)
  119.                 depth = MaxDepth;
  120.  
  121.             if(obj == null || writer.Indent >= depth)
  122.                 return;
  123.  
  124.  
  125.             string start_format = "START_OBJECT -> {0} | {1}";
  126.             string end_format = "END_OBJECT -> {0} | {1}";
  127.             string property_start = null;
  128.             string property_end = null;
  129.             string property_format = @"{0,-20}  :    {1,-20}";
  130.             string null_value = "[null]";
  131.  
  132.  
  133.             if(html) {
  134.  
  135.                 string start_format_html = "<fieldset class='fs_" + writer.Indent + "'><legend><h2>{0}</h2> [hash: {1}]</legend>";
  136.                 string end_format_html = "<p><h2>{0}</h2> [hash: {1}]</p></fieldset>";
  137.  
  138.                 string property_start_html = "<table>";
  139.                 string property_end_html = "</table>";
  140.                 //string property_format_html = @"<li><span class='pn'>{0}</span> :<span class='pv'>{1}</span></li>";
  141.                 string property_format_html = @"<tr><td class='pn'>{0}</td><td class='pv'>{1}</td></tr>";
  142.                 string null_value_html = "[null]";
  143.  
  144.                 start_format = start_format_html;
  145.                 end_format = end_format_html;
  146.                 property_start = property_start_html;
  147.                 property_end = property_end_html;
  148.                 property_format = property_format_html;
  149.                 null_value = null_value_html;
  150.             }
  151.  
  152.             //writer.Indent += 1;
  153.             Type t = obj.GetType();
  154.  
  155.             var asilist = obj as IEnumerable<object>;
  156.             if(asilist != null) {
  157.  
  158.                 if(asilist.Count() == 0)
  159.                     return;
  160.  
  161.                 foreach(var item in asilist) {
  162.                     WriteObjectInternal(item,writer,depth,html);
  163.                 }
  164.                 return;
  165.             }
  166.  
  167.             if(t.IsArray) {
  168.                 ICollection col = obj as ICollection;
  169.                 if(col.Count == 0)
  170.                     return;
  171.                 foreach(var item in col) {
  172.                     WriteObjectInternal(item,writer,depth,html);
  173.                 }
  174.                 return;
  175.             }
  176.  
  177.  
  178.             Dictionary<string,object> allProps = GetPropertyValues(obj);
  179.             Dictionary<string,object> complexProps = new Dictionary<string,object>();
  180.  
  181.             writer.WriteLine(start_format.FormatString(t.Name,obj.GetHashCode()));
  182.             writer.Indent += 1;
  183.  
  184.             //write simple properties
  185.             if(property_start != null)
  186.                 writer.Write(property_start);
  187.  
  188.             foreach(string propname in allProps.Keys) {
  189.  
  190.                 object propval = allProps[propname];
  191.                 if(propval == null) {
  192.                     if(html)
  193.                         writer.Write(property_format.FormatString(propname,null_value));
  194.                     else
  195.                         writer.WriteLine(property_format.FormatString(propname,null_value));
  196.                 }
  197.                 else {
  198.                     var propilist = obj as IEnumerable<object>;
  199.                     if(propilist != null) {
  200.                         if(propilist.Count() > 0) {
  201.                             complexProps.Add(propname,propval);
  202.                         }
  203.                     }
  204.                     else if(propval.GetType().IsArray) {
  205.                         complexProps.Add(propname,propval);
  206.                     }
  207.                     if(!propval.GetType().Namespace.StartsWith("System") && !propval.GetType().IsEnum) {
  208.                         if(!complexProps.ContainsKey(propname))
  209.                             complexProps.Add(propname,propval);
  210.                     }
  211.                     else {
  212.                         if(html)
  213.                             writer.Write(property_format.FormatString(propname,propval ?? null_value));
  214.                         else
  215.                             writer.WriteLine(property_format.FormatString(propname,propval ?? null_value));
  216.                     }
  217.                 }
  218.             }
  219.             if(property_end != null)
  220.                 writer.Write(property_end);
  221.  
  222.             //write complex properties
  223.             foreach(string propname in complexProps.Keys) {
  224.                 object propval = allProps[propname];
  225.                 if(propval == null)
  226.                     continue;
  227.  
  228.                 writer.Indent += 1;
  229.                 try {
  230.                     if(propval.GetType().IsArray) {
  231.                         ICollection col = propval as ICollection;
  232.  
  233.                         if(col != null && col.Count > 0 && !propval.GetType().IsEnum) {
  234.                             string writeval = "" + propname + " : Length = " + (col.Count) + " | Type = " + propval.GetType().FullName + "";
  235.  
  236.                             writer.WriteLine();
  237.                             writer.Write("BEGIN PROPERTY ");
  238.                             writer.Write("".PadLeft(10,'*'));
  239.                             writer.Write(writeval);
  240.                             writer.Write("".PadLeft(10,'*'));
  241.                             writer.WriteLine();
  242.  
  243.                             WriteObjectInternal(propval,writer,depth,html);
  244.  
  245.                             writer.WriteLine();
  246.                             writer.Write("END PROPERTY");
  247.                             writer.Write("".PadLeft(10,'*'));
  248.                             writer.Write(writeval);
  249.                             writer.Write("".PadLeft(10,'*'));
  250.                             writer.WriteLine();
  251.                         }
  252.                         else {
  253.                             writer.WriteLine("" + propname + " : ");
  254.  
  255.                             WriteObjectInternal(propval,writer,depth,html);
  256.                         }
  257.  
  258.                     }
  259.                     else {
  260.                         writer.WriteLine("" + propname + " : ");
  261.  
  262.                         WriteObjectInternal(propval,writer,depth,html);
  263.                     }
  264.  
  265.                 }
  266.                 catch(Exception error) {
  267.                     writer.WriteLine(error.Message);
  268.                 }
  269.                 finally {
  270.                     writer.Indent -= 1;
  271.                 }
  272.             }
  273.  
  274.             writer.Indent -= 1;
  275.             writer.WriteLine(end_format.FormatString(t.Name,obj.GetHashCode()));
  276.             writer.Flush();
  277.         }
  278.  
  279.         static Dictionary<string,object> GetPropertyValues(object obj) {
  280.             var dictionary = TypeDescriptor.GetProperties(obj)
  281.               .OfType<PropertyDescriptor>()
  282.               .OrderBy(p => p.Name)
  283.               .ToDictionary(p => p.Name,p => p.GetValue(obj));
  284.             return dictionary;
  285.         }
  286.     }
  287.  
  288.     #endregion
  289.  
  290.     #region String Extensions class
  291.  
  292.     [System.Diagnostics.DebuggerStepThrough]
  293.     public static class StringExtensions {
  294.  
  295.         public static string ToString(this string s,params object[] args) {
  296.             return string.Format(s,args);
  297.         }
  298.  
  299.         public static string FormatWith(this string s,params object[] args) {
  300.             return string.Format(s,args);
  301.  
  302.         }
  303.         public static string FormatString(this string s,params object[] args) {
  304.             return string.Format(s,args);
  305.         }
  306.  
  307.         public static bool IsNull(this string s) {
  308.  
  309.             return (s == null
  310.                 || s.Length == 0
  311.                 || string.IsNullOrWhiteSpace(s));
  312.         }
  313.  
  314.         public static string ValueIfNull(this string s,string value) {
  315.             if(IsNull(s))
  316.                 return value;
  317.             else
  318.                 return s;
  319.         }
  320.  
  321.         public static string ToStringEmpty(this object obj) {
  322.             return obj == null ? string.Empty : obj.ToString();
  323.         }
  324.  
  325.         public static string ToStringEmpty(this object obj,string valueIfNull) {
  326.             return obj == null ? valueIfNull : obj.ToString();
  327.         }
  328.         public static string ToTitleString(this string s) {
  329.             if(s == null)
  330.                 return null;
  331.             string result = "";
  332.             for(int i = 0;i < s.Length;i++) {
  333.                 char c = s[i];
  334.                 if(char.IsUpper(c)) {
  335.                     if(i != 0) {
  336.                         int h = i - 1;
  337.                         if(h > -1) {
  338.                             char p = s[h];
  339.                             if(char.IsUpper(p)) {
  340.                                 result += c.ToString();
  341.                                 continue;
  342.                             }
  343.                         }
  344.                         result += " ";
  345.                     }
  346.                 }
  347.                 result += c.ToString();
  348.             }
  349.             return result;
  350.         }
  351.  
  352.         public static string Repeat(this string s,int num) {
  353.             return Repeat(s,num,string.Empty);
  354.         }
  355.  
  356.         public static string Repeat(this string s,int num,string delimeter) {
  357.             if(IsNull(s))
  358.                 return s;
  359.             StringBuilder sb = new StringBuilder();
  360.             for(int i = 0;i < num;i++) {
  361.                 sb.Append(s);
  362.                 if(delimeter != null)
  363.                     sb.Append(delimeter);
  364.             }
  365.             return sb.ToString();
  366.         }
  367.     }
  368.  
  369.     #endregion
  370.  
  371. }
Advertisement
Add Comment
Please, Sign In to add comment