andrew4582

TraceHelper

Aug 11th, 2010
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.97 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.ComponentModel.DataAnnotations;
  7. using System.Configuration;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Web;
  13. using System.Web.Caching;
  14. using System.Web.Mvc;
  15. using System.Web.Routing;
  16. using System.Web.SessionState;
  17.  
  18. namespace Core.Diagnostics {
  19.     using Configuration;
  20.     using Core.Collections.Specialized;
  21.     using Core.Text;
  22.     using Threading;
  23.     using Web;
  24.  
  25.  
  26.     public static class TraceHelper {
  27.  
  28.         public static void TraceRoutes(RouteData routes) {
  29.             if(routes == null)
  30.                 throw new ArgumentNullException("routes");
  31.  
  32.             Trace.WriteLine("--------------- TRACE_ROUTES:" + HttpContext.Current.Request.Url.OriginalString);
  33.             Trace.IndentLevel += 1;
  34.             foreach(string rkey in routes.Values.Keys) {
  35.                 var rval = routes.Values[rkey];
  36.                 Trace.WriteLine(@"{0} : ""{1}""".FormatString(rkey,rval.ToStringEmpty()));
  37.             }
  38.             Trace.IndentLevel -= 1;
  39.             Trace.Flush();
  40.         }
  41.  
  42.         public static void TraceObject(object obj,StringBuilder builder = null) {
  43.  
  44.             if(obj == null)
  45.                 throw new ArgumentNullException("obj");
  46.  
  47.             Trace.IndentSize = 2;
  48.             Trace.IndentLevel += 1;
  49.             Type t = obj.GetType();
  50.  
  51.             string indentPrefix = "".PadLeft(Trace.IndentLevel,'\t');
  52.  
  53.             var dictonary = TypeUtilities.GetPropertyValues(obj);
  54.             Trace.WriteLine("OBJECT_START -> " + t.Name);
  55.             if(builder != null)
  56.                 builder.AppendLine(indentPrefix + "OBJECT_START -> " + t.Name);
  57.  
  58.             foreach(string propname in dictonary.Keys) {
  59.                 var propval = dictonary[propname];
  60.                 if(propval == null) {
  61.                     Trace.WriteLine(@"{0} : {1}".FormatString(propname,"null"));
  62.                     if(builder != null)
  63.                         builder.AppendLine(indentPrefix + indentPrefix + @"{0} : {1}".FormatString(propname,"null"));
  64.                 }
  65.                 else {
  66.                     if(propval.GetType().Namespace.StartsWith("PinotsPalette") && !propval.GetType().IsEnum) {
  67.                         Trace.IndentLevel += 2;
  68.                         try {
  69.                             Trace.WriteLine(propname + " :");
  70.                             if(builder != null)
  71.                                 builder.AppendLine(indentPrefix + indentPrefix + propname + " :");
  72.                             TraceObject(propval,builder);
  73.                         }
  74.                         catch(Exception error) {
  75.                             Trace.WriteLine(error.Message);
  76.                         }
  77.                         finally {
  78.                             Trace.IndentLevel -= 2;
  79.                         }
  80.                     }
  81.                     else {
  82.                         Trace.WriteLine(@"{0} : {1}".FormatString(propname,propval ?? "null"));
  83.                         if(builder != null)
  84.                             builder.AppendLine(indentPrefix + indentPrefix + @"{0} : {1}".FormatString(propname,propval ?? "null"));
  85.                     }
  86.                 }
  87.             }
  88.  
  89.             Trace.WriteLine("OBJECT_END ->   " + t.Name);
  90.             if(builder != null)
  91.                 builder.AppendLine(indentPrefix + "OBJECT_END ->   " + t.Name);
  92.  
  93.             Trace.Flush();
  94.             Trace.IndentLevel -= 1;
  95.         }
  96.  
  97.         public static StringBuilder GetWebSiteValues(ViewContext viewContext) {
  98.             StringBuilder builder = new StringBuilder(5000);
  99.             HttpContext context = HttpContext.Current;
  100.             if(context == null)
  101.                 throw new ArgumentNullException("HttpContext.Current returned null");
  102.  
  103.  
  104.             var routes = viewContext.RouteData;
  105.  
  106.             ModelStateDictionary modelState = viewContext.ViewData.ModelState;
  107.  
  108.             var request = context.Request;
  109.             var session = context.Session;
  110.             var application = context.Application;
  111.  
  112.             System.Web.UI.HtmlControls.HtmlTable table = new System.Web.UI.HtmlControls.HtmlTable();
  113.  
  114.             AppendDataAsTable(RouteValuesToDictionary(routes) as IDictionary,builder,"Routes");
  115.             AppendDataAsTable(ModelStateValuesToDictionary(modelState),builder,"Model State");
  116.             AppendDataAsTable(SessionToDictionary() as IDictionary,builder,"Session Values");
  117.             AppendDataAsTable(ContextToDictionary() as IDictionary,builder,"Http Context Values");
  118.             AppendDataAsTable(ApplicationToDictionary() as IDictionary,builder,"Application Values");
  119.             builder.Append("<p><hr/></p>");
  120.             AppendDataAsTable(request.QueryString,builder,"Request - Query String");
  121.             AppendDataAsTable(request.Params,builder,"Request - All Parameters");
  122.             AppendDataAsTable(request.Form,builder,"Request - Form");
  123.             AppendDataAsTable(request.Headers,builder,"Request - Headers");
  124.             AppendDataAsTable(CookiesToDictionary(request.Cookies),builder,"Request Cookies");
  125.  
  126.             return builder;
  127.         }
  128.         static void AppendDataAsTable(object data,StringBuilder builder,string name) {
  129.             StringBuilder tbuilder = new StringBuilder();
  130.  
  131.             if(data is NameValueCollection) {
  132.                 var nvc = (data as NameValueCollection).AsDictionary();
  133.                 var filtered = nvc.Where(kv => !kv.Value.IsNullOrEmptyTrim());
  134.  
  135.                 DictionaryToHtmlTable.RenderToString(filtered.ToDictionary(d => d.Key,d => d.Value),tbuilder);
  136.             }
  137.             else if(data is Dictionary<string,string>) {
  138.                 var filtered = (data as Dictionary<string,string>).Where(kv => !kv.Value.IsNullOrEmptyTrim());
  139.                 DictionaryToHtmlTable.RenderToString(filtered.ToDictionary(d => d.Key,d => d.Value),tbuilder);
  140.             }
  141.             else
  142.                 return;
  143.  
  144.             TagBuilder div = new TagBuilder("div");
  145.             TagBuilder h2 = new TagBuilder("h2");
  146.  
  147.             h2.SetInnerText(name);
  148.             div.InnerHtml = h2.ToString() + tbuilder.ToString();
  149.  
  150.             builder.Append(div.ToString());
  151.         }
  152.         public static Dictionary<string,string> RouteValuesToDictionary(RouteData routes) {
  153.             if(routes == null)
  154.                 throw new ArgumentNullException("routes is null");
  155.  
  156.             Dictionary<string,string> dict = new Dictionary<string,string>(routes.Values.Count);
  157.             foreach(string rkey in routes.Values.Keys) {
  158.                 dict.Add(rkey,routes.Values[rkey].ToStringEmpty());
  159.             }
  160.             return dict;
  161.         }
  162.         public static Dictionary<string,string> ModelStateValuesToDictionary(ModelStateDictionary model) {
  163.             if(model == null)
  164.                 throw new ArgumentNullException("model is null");
  165.  
  166.             Dictionary<string,string> dict = new Dictionary<string,string>(model.Count);
  167.  
  168.             var sorted = model.OrderByDescending(m => m.Value.Errors.Count > 0);
  169.  
  170.             foreach(var kp in sorted) {
  171.                 string rkey = kp.Key;
  172.                 ModelState state = model[rkey];
  173.                 if(state == null)
  174.                     continue;
  175.                 if(state.Value == null)
  176.                     continue;
  177.                 StringBuilder tbuilder = new StringBuilder();
  178.  
  179.                 tbuilder.Append("<span>");
  180.  
  181.                 object raw = null;
  182.                 if(state.Value.RawValue != null) {
  183.                     if(state.Value.RawValue is string[]) {
  184.                         var arr = state.Value.RawValue as string[];
  185.                         foreach(var item in arr) {
  186.                             raw = arr.First();
  187.                             tbuilder.AppendFormat("{0}",string.Join(";",arr));
  188.                         }
  189.                     }
  190.                     else
  191.                         tbuilder.AppendFormat("{0}",state.Value.RawValue);
  192.                 }
  193.                 if(state.Value.AttemptedValue != null) {
  194.                     if(raw.ToStringEmpty() != state.Value.AttemptedValue)
  195.                         tbuilder.AppendFormat(" -> Attempted Value: {0}",state.Value.AttemptedValue);
  196.                 }
  197.                 foreach(ModelError err in state.Errors) {
  198.                     tbuilder.AppendFormat("<b style='color:Red;'>Error: {0}</b>",err.ErrorMessage);
  199.                     if(err.Exception != null)
  200.                         tbuilder.AppendFormat("<b style='color:Red;'>Exception: {0}</b>",err.Exception.ToString().Replace(Environment.NewLine,"<br/>"));
  201.                 }
  202.                 tbuilder.Append("</span>");
  203.  
  204.                 dict.Add(rkey,tbuilder.ToString());
  205.             }
  206.             return dict;
  207.         }
  208.         public static Dictionary<string,string> CookiesToDictionary(HttpCookieCollection cookies) {
  209.             Dictionary<string,string> dict = new Dictionary<string,string>();
  210.             foreach(string key in cookies.AllKeys) {
  211.                
  212.                 var val = cookies[key];
  213.                
  214.                 StringBuilder builder = new StringBuilder();
  215.                 builder.Append("<div>");
  216.                
  217.                 TraceObject(val,builder);
  218.                
  219.                 builder.Append("</div>");
  220.                 dict.Add(key,TraceToHtml(builder.ToString()));
  221.             }
  222.             return dict;
  223.         }
  224.         public static Dictionary<string,string> SessionToDictionary() {
  225.             HttpContext context = HttpContext.Current;
  226.             if(context == null)
  227.                 throw new ArgumentNullException("HttpContext.Current returned null");
  228.  
  229.             var session = context.Session;
  230.  
  231.             Dictionary<string,string> dict = new Dictionary<string,string>(session.Count);
  232.             foreach(string key in session.Keys)
  233.                 if(key != null)
  234.                     if(!dict.ContainsKey(key.ToString())) {
  235.                         var val = session[key.ToString()];
  236.                         if(val != null) {
  237.                             if(val.GetType().Namespace.StartsWith("PinotsPalette")) {
  238.                                 StringBuilder tbuilder = new StringBuilder();
  239.  
  240.                                 TraceObject(val,tbuilder);
  241.  
  242.                                 string html = TraceToHtml(tbuilder.ToString());
  243.  
  244.                                 dict.Add(key.ToString(),"<pre></pre><div>" + html + "</div>");
  245.                             }
  246.                             else
  247.                                 dict.Add(key.ToString(),session[key.ToString()].ToStringEmpty());
  248.                         }
  249.                     }
  250.             return dict;
  251.         }
  252.  
  253.         static string TraceToHtml(string data) {
  254.             data = data.Replace("\t","&nbsp;");
  255.             data = data.Replace("OBJECT_START","<b>OBJECT_START</b>");
  256.             data = data.Replace("OBJECT_END","<i><b>OBJECT_END</b></i>");
  257.             data = data.Replace(Environment.NewLine,"<br/>");
  258.             return data;
  259.         }
  260.         public static Dictionary<string,string> ApplicationToDictionary() {
  261.             HttpContext context = HttpContext.Current;
  262.             if(context == null)
  263.                 throw new ArgumentNullException("HttpContext.Current returned null");
  264.  
  265.             var application = context.Application;
  266.  
  267.             Dictionary<string,string> dict = new Dictionary<string,string>(application.Count);
  268.             foreach(object key in application.Keys)
  269.                 if(key != null)
  270.                     if(!dict.ContainsKey(key.ToString()))
  271.                         if(!application[key.ToString()].ToStringEmpty().IsNullOrEmptyTrim())
  272.                             dict.Add(key.ToString(),application[key.ToString()].ToStringEmpty());
  273.             return dict;
  274.         }
  275.         public static Dictionary<string,string> ContextToDictionary() {
  276.             HttpContext context = HttpContext.Current;
  277.             if(context == null)
  278.                 throw new ArgumentNullException("HttpContext.Current returned null");
  279.  
  280.             var items = context.Items;
  281.  
  282.             Dictionary<string,string> dict = new Dictionary<string,string>(items.Count);
  283.             foreach(object key in items.Keys)
  284.                 if(key != null)
  285.                     if(!dict.ContainsKey(key.ToString()))
  286.                         if(!items[key.ToString()].ToStringEmpty().IsNullOrEmptyTrim())
  287.                             dict.Add(key.ToString(),items[key.ToString()].ToStringEmpty());
  288.             return dict;
  289.         }
  290.     }
  291.     public class RuntimeTraceListener:TraceListener {
  292.         public StringBuilder TracedData { get; set; }
  293.         public RuntimeTraceListener() {
  294.             TracedData = new StringBuilder();
  295.         }
  296.         public override void Write(string message) {
  297.             TracedData.Append(message);
  298.         }
  299.         public override void WriteLine(string message) {
  300.             TracedData.AppendLine(message);
  301.         }
  302.     }
  303. }
Advertisement
Add Comment
Please, Sign In to add comment