The answer is simple if you are using Firefox with the Firebug add-on or Internet Explorer 8: Use the console.log mechanism and write your debug output to the Browser’s debug console.
Here's a simple extension method, which logs an object to the console.log:
public static void Log(this object obj)
{
HtmlWindow window = HtmlPage.Window;
var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
if (isConsoleAvailable)
{
var console = (window.Eval("console.log") as ScriptObject);
if (console != null)
{
console.InvokeSelf(obj);
}
}
}
How to you use it:
"Hello Universe!".Log();
int a = 42;
a.Log();
String.Format("The answer to all questions is {0}.", a).Log();
And that's how the debug output looks within Firebug:











4 Kommentare:
Nice tip! I might just use this. Thanks.
Thanks for this tip! It really helped me out.
I modified the code slightly to check for the existence of console and console.log. That way it will quietly fail (i.e., it won't throw an InvalidOperationException on Eval) if it's running in IE8 with the "Developer Tools" window closed or in earlier versions of IE.
HtmlWindow window = HtmlPage.Window;
object hasConsole = window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
if (hasConsole is bool && (bool)hasConsole)
{
ScriptObject consoleLogFunction = window.Eval("console.log") as ScriptObject;
if (consoleLogFunction != null)
{
consoleLogFunction.InvokeSelf(entry);
}
}
@Bill I totally missed that. Thanks for your comment! I updated the code snippet.
Where can you get System.Windows.Forms for silverlight?
Post a Comment