Silverlight logging errors to a browser debug console (IE, Chrome, Firebug…)

The title says Silverlight but I think this will work for any C# web application (MVC, Web Forms … this is just where I tried it)

Sometimes debugging web applications with service calls can be … well… fun when you want to see what happens to your app when the service is unreachable.

For web applications Console.Writeline() is not an option, and while System.Diagnostics.Debug.WriteLine() works. I typically still get an exception in the service request and I am not 100% sure that the end user will not see the same thing.

Here’s what I did.

Create a static class and name it something simple like Log.cs

Add a static method like so

public static void Logs(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);
                }
            }
        }

Now anywhere in your application you can call .Logs() like so

if(debugCheck)
    {
        "ClientPingCompleted".Logs();
        var error = "return error : " + e.Error;
        error.Logs();
    }

In the browser console you will see this.

CropperCapture[1]

Advertisements
This entry was posted in Silverlight, Visual Studio. Bookmark the permalink.

4 Responses to Silverlight logging errors to a browser debug console (IE, Chrome, Firebug…)

  1. Thanks.
    It’s very convenient. Great post.

  2. Omar says:

    Hi,

    I have just tried this function on Windows8 IE10 and Windows7 IE10 Release Preview and it throws an InvalidOperation exception. Do you have any more info on that matter? did they change the javascript invoking security on IE10?

    Thank you

  3. chadit says:

    I haven’t done Silverlight development since last build when they killed it off “unofficially” I would assume in IE10, Silverlight will probably either need 1. be updated to support this, 2. Silverlight needs to run in trusted, 3. you might want to try and adjust the Interenet security levels…

  4. Is there a way to make this work in google chrome? I get the console.InvokeSelf method failed. any alternatives that will work cross browser wide?

Comments are closed.