How to find out the XAML file that produces a XamlParseException - c#

I get the following error at runtime from a C# WPF application:
A first chance exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll
Additional information: 'Set property
'System.Windows.Controls.ContentControl.Content' threw an exception.'
Line number '6' and line position '6'.
How can I find which file this is associated with? The Visual Studio solution contains two XAML files, app.xaml and MainWindow.xaml.
I am using VS 2010 on Windows 7. The application targets .NET 4.0.
UPDATE:
Following up on Kasper's helpful suggestion, I displayed the exception in detail, and this is what it showed:
Based on the information in there, I was able to gather that a certain DLL was missing. Supplying the DLL fixed this problem, but I still have other XAML parse errors coming up.

In the code-behind, the XAML code is parsed in the method InitializeComponent which is automatically generated. This method is called in the Window object's constructor. So to have more details about the exception, put the call to InitializeComponent in a try/catch block. This way, you have access to the useless XamlParseException, but also to its InnerExceptions and to the StackTrace.
UPDATE!
You can call the inner exception using a MessageDialog.
public partial class Window1 : System.Windows.Window
{
public Window1()
{
try
{
InitializeComponent();
}
catch ( Exception ex )
{
// Log error (including InnerExceptions!)
// Handle exception
MessageDialog dialog = new MessageDialog(ex.InnerException);
dialog.ShowAsync();
}
}
}
Hope that helps :)
There is also another trick to this:
Open the "Exceptions" window (Debug/Exceptions) in Visual Studio.
Click "add"
Add "System.Windows.Markup.XamlParseException"
Check the box to break on throw for this exception.
Hit F5!
You'll find that the XamlParseException you catch is much more descriptive, and will give the correct position in the xaml file.
Let me know if this was easier :)

Related

C# DLL calls property "get" for no reason

I am creating a custom C# Windows Forms control library (a DLL) in Visual Studio 2019 (Professional). My control has a property that takes the following form (this property is aimed to be accessed by applications which use the DLL):
public double Hello
{
get { throw new ApplicationException("Hi!"); }
}
(In my efforts to find out why this is happening, I've simplified the property to just throw an exception and do nothing else.)
For some reason, if I run my User Control (in Debug mode), the exception is raised - even though nowhere else in this code calls that property! (The IDE confirms this - saying "0 references" above it). Why does the property "get" accessor seem to be called for no reason? The stack trace shows that the "get" was called by "[External code]"...
This should be pretty easy to reproduce if you have Visual Studio 2019: create a new "Windows Forms Control Library (.NET Framework)" project under C#, then right click on "UserControl1.cs" in the Solution Explorer and click "View Code", then just add in the above code to the class.
I have reproduced your problem. Based on my test, I find that winformscontrollibary will
load all the properties you set in the code, because it needs to load them into the
property bar of form.
Like the following, if you write the following code.
public partial class UserControl1: UserControl
{
public UserControl1()
{
InitializeComponent();
}
public double Hello
{
get { return 1.02; }
}
public int Number
{
get { return 1; }
}
}
You will see the correct property(Hello and Number) in the right of form.
Therefore, if you write the code throw new ApplicationException("Hi!"); in the get method , it will throw the exception.

Prism.Wpf + Elysium.Extra

I have two test project: 1st for Prism.Wpf, 2nd for Elysium.Extra. Both runs fine. But now I try to use Prism with Elysium in one project.
I have my class Shell : Framework.UI.Controls.Window (not System.Windows.Window, accordig to elysium's examples) with xaml:
<extra:Window x:Class= ... etc.
Bootstrapper's CreateShell() method has single row:
Container.Resolve<Shell>();
When I run my app, this row pass control flow to Shell's constructor, then app fails with exception:
An exception of type
'System.Windows.ResourceReferenceKeyNotFoundException' occurred in
PresentationFramework.dll but was not handled in user code
Additional
information: 'Framework.UI.Controls.Window' resource not found.
Is it possible to use not System.Windows.Window as Prism's shell? Or it's not cause of exception? Please, help.
You can use any custom Window control with Prism. Your problem is that you didn't change your App.xaml and App.xaml.cs to be an ElysiumApplication, which is where the resource for the Window is defined.

Unknown exception at declaration and initalisation of a Class

The main Problem is completely different, please skip to the Edit
I have an exception of an unknown type which doesn't even get thrown properly. Following Code provides the Context:
MMDataAccess.InitDemoDB();
MMDataAccess.InitInternalDB();
MMDataAccess.InitMaintDB();
try
{
SQLiteToDBLib sqltdbl = new SQLiteToDBLib();
sqltdbl.WriteToSQLite();
}
catch(Exception ex)
{
string message = ex.Message;
}
These are the very first lines of my first Activity in my app. The first 3 lines belong to my very own implementation of an in-memory database and are behaving nicely. The problem rises with the next two lines inside the try-block. The declaration and initalistation of the sqltdbl variable never happens. The constructor of SQLiteToDBLib looks like this:
public SQLiteToDBLib()
{
msc = new MSConnection();
}
The MSConnection class doesn't even have a constructor (except for the default one of course).
As you can see i've tried to catch any exceptions, but without success. everything i can figure out is, that a exception is thrown because of the debugger going into the catch section while ignoring everything that has to do with "ex". Without breakpoints everything seems fine. Just without the call to WriteToSQLite which should create a .sqlite file on the external Memory.
What can I do to resolve this error? Is there anything i can catch except the default Exception?
Edit:
After some testing with commented code something interresting happened. I could step into commented code. Well not exactly the commented code, but the code that was there before my changes. Visual Studio somehow shows me the things, that are changed in the file, but is compiling the old code. Up to now i tried to rebuild, clean and build the project in various combinations, unload and reload the project, Restart Visual Studio and restart Windows. Nothing has changed so far. I Will now proceed to create a new .cs File With the exact same Code. I'm working with VS 2013 Community
add static constructor to your SQLiteToDBLib class and perform all static objects initialization in it:
static SQLiteToDBLib()
{
// initialize static members here
}
If this doesn't give you a clue, try enabling CLRE exceptions-break in visual-studio:
DEBUG
Exceptions
Check the 'Common Language Runtime Exceptions' option (under the 'Thrown' column)
Press OK
Restart your app and try again

XAML MarkupCompilePass2 fails on a WPF project

When I try to build my WPF project I get the folowing error:Samotorcan.Client.WPF.Windows8\Views\MainWindow.xaml(1,17): error MC3074: The tag 'Window' does not exist in XML namespace 'clr-namespace:Samotorcan.Client.WPF.Windows8.Controls'. Line 1 Position 17.The problem only occurs when I try to use linq. If I have a line like this new List<object>().ToArray<object>(); somewhere in the MainWindow.xaml.csfile I get the above error and if I change it to new List<object>().ToArray(); the error disappears and the project builds successfully.I also checked the build log and it contains the same error at task MarkupCompilePass2.I am using .NET Framework 4.5 and Visual Studio 2012.EDITAfter playing with it a bit I managed to find out that it's not specificly related to linq an random changes like removing an unused file from a project or just removing parts of code like a simple string creating string s = new String(); fixes the error.At one point a simple change in a constructor from this
public LoggedEventArgs(string message)
{
Message = message;
}
to this
public LoggedEventArgs(string message)
{
// Message = message;
}
fixed the error.
Managed to find a workaround for the above error by moving all my controls from the project into a separate project just for controls.
Now there are no random errors on build because as it looks like it can always find the window and other controls that are now in a separate assembly.

uncatchable exception from unreachable code

I run into a very strange problem in my C# 2.0 WinForms app and I'm not even sure if its worth asking SO, because the problem occurs in a strange setup and I don't think that you could reproduce it without my sources, but I'm totally out of ideas.
I have a Form with a TreeView on the left and an ListView on the right. The TreeView shows all available files and subfolders from a specific folder(which contains documents i need for my app). If a Folder is selected the ListView shows all files and subfolders from the selected folder. At startup I populate the TreeView form the folder and after that I select the first TreeNode by code(in my case it's an folder). After that the Content of the TreeView looks like this:
-folder
-file1
-file2
Selecting the folder triggers the AfterSelecedEvent of the TreeView. Because a folder was selected I populate the ListView using the following methode:
private void fillOverview(FAFolder folder)
{
lv_overview.Items.Clear();
ListViewItem item;
foreach (FAFile file in folder.sortedContent)
{
if (file is FAFolder)
{
item = new ListViewItem(file.Name, "Folder"); //exception got thrown here
}
else
{
item = new ListViewItem(file.Name, file.Name);
}
item.Tag = file;
lv_overview.Items.Add(item);
}
}
As you can see there is no subfolder, so the line item = new ListViewItem(file.Name, "Folder"); should never be touched in this setup, but every now and then a NullReferenceException got thrown. If I wrap this line with try/catch the exception got thrown inside the catch block. I tried checking everything if it's null or not, but ther were no nullreferences. Or if I add a MessageBox right before this line the exceptions got still thrown and no MessageBoxpops up. This brings me to the conclusion that the execption stacktrace is wrong and/or this exceptions comes from an other Thread or something like that.
I'm a very optimistic person and I know how clever the SO community can be, but I don't think that anybody can point out what the problem is. So what i'm actuallly looking for are hints and advices how i could find and debug the cause of this strange behavior.
EDIT:
internal abstract class FAFile
{
internal string Name;
internal readonly FAFolder Parent;
internal FAFile(FAFolder parent)
{
this.Parent = parent;
}
}
internal sealed class FAFolder : FAFile
{
internal readonly IDictionary<string, FAFile> Content = new Dictionary<string, FAFile>();
internal FAFolder(FAFolder parent, string name) : base(parent)
{
this.Name = name;
}
}
internal sealed class FADocument : FAFile
{
public readonly string Path;
public FADocument(FAFolder parent, string path): base(parent)
{
this.Path = path;
this.Name = System.IO.Path.GetFileNameWithoutExtension(path);
}
}
Have you tried an null check on folder.sortedContent ?
Usually ReSharper will prompt me that something like that should have a null check.
If you want to be sure, add the following line to your code, above the foreach loop:
if (folder.sortedContent == null) throw new Exception("It was null, dangit!");
On the line you mention:
item = new ListViewItem(file.Name, "Folder")
the only thing that can cause a NullReferenceException is if file is null (unless the exception is being thrown from within the ListViewItem constructor itself).
You don't provide the code for folder.sortedContent so I can't tell - but is it possible that one of the elements in this collection might be null under certain circumstances?
If the ListViewItem constructor is throwing the exception then you will need to use Reflector to look at the code, or download the reference source.
A co-worker of mine just found the answer(probably). I use a Thread to load the ImageList to the ListView from the HDD and this thread sometimes freezes and if i assign a ImageKey it fails. That's no answer why the exception is uncatchable or why it's thrown at this (unreachable) line. But i strongly belive that this is the cause of the problem.
That line is not unreachable. Because FAFolder derives from FAFile, it is possible that 'file is FAFolder' will return true.
However, that would imply that file is not null, unless it is being changed by another thread.
Edit: file can't be changed by another thread as it's a local reference. Can you provide a stack trace for the exception? This one has me intrigued now.
I just cannot help wondering is the FAFolder contain a '.' or a '..' for parent and subdirectory? and the sorting breaks as a result?
This answer will be edited accordingly if this turns out to be untrue?
Hope this helps,
Best regards,
Tom.
Is this exception reproducible on demand?
Can you show the the stack trace of the exception?
What other threads are running when the exception is thrown?
In general, there are two ways to debug this type of stuff. The first way is so-called "scientific" debugging:
Devise a theory to explain observed behaviour.
Devise an experiment to test the theory.
Run the experiment and observe the results.
The second way is by stripping-down the actual code piece by piece until the exception is no longer triggered. Then you have a significant clue for further investigation.
This brings me to the conclusion that the execption stacktrace is wrong....
It's usually easier to start by assuming that the problem is in your own code.

Categories