How to Debug XAML Parsing Errors in Silverlight? - silverlight

I run into the following issue semi-regularly: I make changes to XAML or some resources used by it and when I go to load up the Silverlight project in debug mode it only gets as far as the spinning Silverlight-loading animation.
I've tried attaching the VS08 debugger to the process but it doesn't do anything at this point (works fine once I'm in the Silverlight but not before.)
From previous experience I've noticed this happens when there're problems with the XAML or the resources in it but my only solution so far has been to dissect the code line-by-line until I spot the problem.
Is there an easy way to debug/diagnose these situations?
UPDATE
I found this question with some help, but it still doesn't provide a good way to debug these types of issues.

This has been a real pain to debug but I finally found the problem hidden deep in the constructor to one of our custom controls (which was looking for a resource that wasn't there.) The real problem isn't fixing the issue but finding it.
I found that IE responds to exceptions in passed from Silverlight to the DOM but you don't get that same sort of feedback in the Chrome browser (which I use.) A solution that actually helps a great deal (even moreso than the IE tip) is to modify the ReportErrorToDOM() method in App.xaml.cs to the following:
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
string errorMsg = String.Empty;
try
{
errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", #"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
#if DEBUG
MessageBox.Show(errorMsg);
#endif
}
}
This gives you the position in the XAML where the issue is starting. It's not an ideal debugger, but it does help.

This is not the ultimate answer but can often help
In Visual Studio :
Click Debug > Exceptions
Click 'Find' and search for XAML
Click the 'Thrown' button next to System.Windows.Markup.XamlParseException
Start your project in debug mode. Any Xaml exceptions will be shown immediately. Check the inner exception sometimes for further information.
I wasted soooo much time before I finally figured this one out!

This may not apply, but one frequent source of XAML errors is due to uncaught exceptions within converters that you're using as resources. People often forget to use a try-catch block in their converters, and when something blows up in there you end up having to dissect your code line by line.
And, take this with a grain of salt, but depending upon the situation, you may be able to copy-and-paste some of your XAML into a WPF project and get better error messages. I've never relied on this tactic myself, but I recently heard about it from an experienced WPF/SL developer who's far smarter than me, so it might be worth a shot. :-)

Per microsoft: The end user at this time cannot debug the XAML Parser, only MS can do this. The new version of Silverlight 4 XAML Parser has been completely re-written using managed code and hopfully they will give us a better way to debug it. I know this as I just had an issue and opened a support case and was informed this by a Silverlight Dev.
The clkosest I could ever come to seeing what was going on with the parser was using Silverlight Spy:
http://firstfloorsoftware.com/silverlightspy/download-silverlight-spy/
Great tool.

Related

WPF exits in InitializeComponent(), no error, can't debug

I have an app that used to work well, I did some modifications and such. Now, only about 1/2 the time it runs. I installed the app to a laptop and it doesn't run at all.
There are no errors, warnings, or ui shown by the task bar shows the app momentarily.
Even when I run inside visual studio and put a break point on InitalizeComponent(), I can't seem to locate anything causing the problem.
My code essentially looks like this:
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
try
{
InitializeComponent();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
log("Initalizing....");
This is wpf 4 in vs2015. Any ideas how to get some type of error message before it exits and figure out what is causing the problem? The app works fine once it actually runs. The event viewer on the laptop shows some messages, something about faulting in KernalBase.... nothing useful.
I'm not sure if InitalizeComponent() is the issue, but when I put a BP on it and step through the code, it always exits at that point.
As #Breeze mentioned, you need to strengthen the exceptions, like that:
Go to Debug -> Exceptions... OR Ctrl+Alt+E and you'll see this window:
Mark this two:
Common Language Runtime Exceptions and
Manage Debbugging Assistants.
REMEMBER after finish using them unmark them because it also throws exceptions you don't need to deal with a lot of times.

Unknown error caused by DataTemplate

Since a few days back the WPF editor no longer works. Whenever I click somewhere in any editor it becomes disabled with this message:
'NullReferenceException was thrown on "DataTemplate": ... (etc.)'
I have spent a few hours trying to locate the problem without success so if anyone could give a hint on where to look I would greatly appreciate it.
I have tried to debug with CLR exceptions enabled when thrown (VS2010->Debug->Exceptions...->Common Language Exceptions (Thrown) 'Checked') but I get no exceptions from it.
Apparently there's a problem some DataTemplate somewhere that's only showing in design time but I just can't figure out how to locate it.
Cheers
I finally traced the problem to a small markup extension I wrote. Having removed it the DataTemplaring system stopped behaving badly.

MediaElement is repeating clips automatically, and sometimes fails to play them

I have an app which plays a few short sound clips. To play them I simply set the source to the new clip path, which is a WMA I encoded with Expression Encoder using WP7 settings. It's not even worth sharing the code -- there's an event handler. In it, I set the ME.Source property to a new Uri. It's set to AutoPlay, so that's it! Here:
private void PlaySound(ItemViewModel sound) {
Model.CurrentSound = sound;
CurrentSound.Source = new Uri(sound.Path, UriKind.Relative);
}
private void Sounds_SelectionChanged(object sender, SelectionChangedEventArgs e) {
var list = ((ListBox) sender);
var item = (ItemViewModel) list.SelectedItem;
SelectItem(item);
}
Also I should point out that the sounds are all resources (build type = Resource). I need them to be because the app needs to discover them dynamically. The paths are all like this, "sounds/foo/bar/sound.wma". Sometimes there is a space in the path, it is url encoded with %20 (this is how the resource manager returns the path, I didn't do that).
The problem is many people, but not all, are saying that the sound auto-repeats. The sounds are very short, only a few seconds, so it's very annoying. I don't understand how this is happening, the MediaElement doesn't even have an auto repeat feature.
Perhaps related, but some have also complained that every now and then the sound does not play. They have to click it again. All I can think of is that there is something wrong with how the sounds are encoded, but they are WMA, and as I said, I encoded them using the 'playback in WP7' settings in expression encoder. How could it be that it works usually but not other times if that were the case, anyway?
I'm at a loss and my app is getting some bad reviews because of this behavior. Help!
"there's and event handler" but you don't say of what? It could be that event firing over and over or not at all in some cases. Potentially your code has a logical errors where you have failed to detach an existing handler and then added another. As usage progresses you end up with a single event being handled by multiple handlers.
Edit
The Selection changed event is notorious for firing more frequently than we'd like. I suggest you add some debounce code that makes record of the last item selected and how long ago. If the next selected item is the same as the last one and it was say less than a second ago then swallow the event without doing anything else.
It sounds like you might be trying to play Sound Effects - in which case you might be better off using the XNA SoundEffect mechanism
e.g. http://www.japf.fr/2010/08/sound-effect-in-wp7-sl-application/
SoundEffect only works for WAV files (PCM) - but I've used it in several apps and scripts including embedded content files and downloaded files (e.g. translation and ironruby scripts).
The XNA class works well within SL and allows multiple sound effects to be played at the same time.
The problem with repeating turned out to be needing to do this:
MediaPlayer.IsRepeating = false;
I think what happened was the user would be in another app that sets this to true, and upon opening my app that value was still true! That has to be a bug, it's totally unexpected. If you look at other sound-playing apps like soundboard apps, there are users complaining in the reviews about the very same thing.. "I wish it wouldn't repeat the sounds..."

"The DOM/scripting bridge is disabled" error in Blend

I've been given a custom Silverlight control to use, and everytime I open it up in Blend, get the "The DOM/scripting bridge is disabled" error.
Looking in the control's source code, I can see calls to
public override void OnApplyTemplate()
{
...
HtmlPage.Window.Invoke("GetPrimaryGradStart").ToString()
which I'm guessing might be the problem. Any ideas about what I can do, or am I back to pure XAML?
cheers
Toby
usually (i.e. when a Silverlight app is embedded in an HTML page) one has to set the "enablehtmlaccess" parameter to true for the app via HTML or JavaScript, because otherwise calls like HtmlPage.Window.Invoke are not allowed (and throw an exception).
So I guess the problem is that blend does/can not set that parameter and only shows that message instead.
If you have control over the code, you could add a condition that checks whether you are in design mode or runtime mode using DesignerProperties.IsInDesignTool, for example:
if (!DesignerProperties.IsInDesignTool)
{
// Do the "evil stuff"
HtmlPage.Window.Invoke("GetPrimaryGradStart");
}
Hope that helps.
Cheers, Alex
EDIT: If it does help, you might also want to add some pre-compiler directives to your code so that you won't have those design tool stuff statements in your production app:
#if !RELEASE
if (!DesignerProperties.IsInDesignTool)
#endif
HtmlPage.Window.Invoke("GetPrimaryGradStart");

Silverlight 3 XamlReader Exception not caught

when I use XamlReader.Load() with an invalid XAML string, the resulting XAMLParseException is not caught although beeing in a try-catch-block:
try
{
UIElement xamlCode = XamlReader.Load(XamlText) as UIElement;
}
catch (Exception ex)
{
ErrorText = ex.Message;
}
The code is called from the Tick-Event of a DispatcherTimer, but also in Events like MouseLeftButtonDown the exception is not caught resulting in a break in the Line where I call .Load().
Does anyone know how to catch this Exception and resume normal programm activity?
Thanks, Andrej
It is completely unfathomable that this code would not catch the exception. How do you determine that the XAMLParseException is occuring here? Are you sure is not coming from some other Xaml Load in the project?
Is this always the case ? or onlys while debugging ?
I'm aware this is an extremely late answer and you might have found the solution to it, for as reference to people finding your question similar to theirse (like my case ), my answer might still be of use.
If its happening while debuggin, it might be because the exeption is configured to be thrown.
You can change this:
Customize the Debug menu, adding the "Exceptions" command to it.
In the Exceptions configuration, Drill down to System.Windows.Markup.XamlParseException, which is under Common Language Runtime Exceptions.
Remove the check from the "Throw" column.
There are various Silverlight operations that get "re-marshalled" onto separate threads for what are presumably various good and sufficient reasons. It looks kind of like this:
Dispatcher.BeginInvoke(() => LoadSomeXamlOrSomething());
Any exception thrown within LoadSomeXamlOrSomething() won't be caught by normal try/catch blocks. This happens even in SL 4 with things like loading images with invalid formats. It's annoying, and MS needs to come up with a better way to handle this, for instance, by letting you register an exception handler when you make the call.
Until MS figures this out, your options are:
Fix the underlying XAML error.
Catch the exception in App.Application_UnhandledException.

Resources