Thursday, May 21, 2009

Silverlight Logging Extension Method

Most of you will know that a Silverlight application runs in the Browser and Console.WriteLine() doesn’t work. During the development process you could use System.Diagnostics.Debug.WriteLine() to write messages to Visual Studio’s Output window. But what if an application is deployed and no Visual Studio is nearby and you just want simple Console output and not a logging framework like Clog, where a web service is involved? Or don’t want to use Visual Studio’s Output window?

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:













Shout it Submit this story to DotNetKicks

4 Kommentare:

Jonathan van de Veen said...

Nice tip! I might just use this. Thanks.

Bill Menees said...

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);
}
}

Rene Schulte said...

@Bill I totally missed that. Thanks for your comment! I updated the code snippet.

Anonymous said...

Where can you get System.Windows.Forms for silverlight?

Post a Comment