What is causing XamlParseException in WPF application?

3.6k views Asked by At

Update: The loading of the controls.Resources.dll occurs after the trouble point, (in both applications) so that's likely a red herring.

I've got two applications, one that's working perfectly, and one that won't start with various exceptions. They are WPF applications both running under .NET 3.5 and Windows7. They are both built over the same set of references/dependencies. They're largely identical programs. I've manually compared their main files in search of the problem source to no avail.

The problem occurs during start up. The exception is always a XamlParseException, but the causes (ranging from a SQL exception to multi-touch exceptions) differ. The immediate stack is:

Unable to cast object of type 'System.Windows.Controls.ListView' to type 'Lightning.Controls.Configuration.MaterialsImportExportControl'.  

Error at object 'System.Windows.Controls.ListView' in markup file 'Lightning.UI.Controls;component/configuration/materials/xaml/materialsimportexportcontrol.xaml'. 
---> System.InvalidCastException:
Unable to cast object of type 'System.Windows.Controls.ListView' 
to type 'Lightning.Controls.Configuration.MaterialsImportExportControl'.
   at Lightning.Controls.Configuration.MaterialsImportExportControl.System.Windows.Markup.IComponentConnector.Connect(Int32 connectionId, Object target)
   at System.Windows.Markup.BamlRecordReader.ReadConnectionId(BamlConnectionIdRecord bamlConnectionIdRecord)
   at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
   --- End of inner exception stack trace ---
   at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
   at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
   at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
   at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
   at System.Windows.Markup.BamlRecordReader.GetElementAndFlags(BamlElementStartRecord bamlElementStartRecord, Object& element, ReaderFlags& flags, Type& delayCreatedType, Int16& delayCreatedTypeId)
   at System.Windows.Markup.BamlRecordReader.BaseReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
   at System.Windows.Markup.BamlRecordReader.ReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
   at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
   at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
   at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
   at System.Windows.Markup.TreeBuilder.Parse()
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at EndeavorUI.EndeavorPartIdWindow.InitializeComponent()
   at EndeavorUI.EndeavorPartIdWindow..ctor()
   at EndeavorUI.SystemBootUpWindow.WaitToCollapseWindow(Object sender, RoutedEventArgs e)

Based on my reading here and elsewhere, this might actually be caused by a resource DLLs not properly loading, or resource conflicts.

I've run Process Explorer, and have observed that in the working program, in the .NET assemblies tab, there are multiple entries for Controls.resources.dll files that are not present in the non-working program.

I would think that those dlls should be loaded in the non-working program as well; would anyone have any ideas about why they wouldn't be?

Edited to add: Here's an edited version of the xaml file it's trying to process:

    <controls:UserControlMultiTouchEnabled x:Class="Lightning.Controls.Configuration.MaterialsImportExportControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:configuration="clr-namespace:Lightning.Controls.Configuration"
        xmlns:KB="clr-namespace:Lightning.UI.Controls.KeyBoard"
        xmlns:controls="clr-namespace:Lightning.Controls"
    Loaded="LoadedHandler">
        <controls:UserControlMultiTouchEnabled.Resources>
            <controls:ConverterBooleanInverter x:Key="converterBooleanInverter" />
            <controls:MultiConverterObjectReferenceToVisibilityAndBooleanGeneralized x:Key="converterObjectRefAndBooleanToVisibility" />
            <controls:MultiConverterObjectReferenceToVisibilityAndBooleanGeneralized InvertBooleans="True" x:Key="converterObjectRefAndBooleanToVisibilityInvertBooleans" />
            <controls:ConverterObjectReferenceToVisibilityGeneralized x:Key="converterObjectRefToVisibility" />
            <controls:ConverterObjectReferenceToVisibilityGeneralized Invert="True" x:Key="converterObjectRefToVisibilityInverted" />
            <controls:ConverterBooleanToVisibilityGeneralized x:Key="converterBoolToVisibility" />
            <controls:ConverterBooleanToVisibilityGeneralized Invert="True" x:Key="converterBoolToVisibilityInverted" />
            <controls:ConverterBooleanToSelectionModeGeneralized x:Key="converterSelectionMode" />
            <controls:MultiConverterImportedMaterialDisplayInfoPropertiesToBooleanEnabled x:Key="enabledConverter" />
            <controls:MultiConverterImportedMaterialDisplayInfoPropertiesToVisibility x:Key="converterIMDIVisibility" />
            <controls:MultiConverterImportedMaterialDisplayInfoPropertiesToVisibility Invert="True" x:Key="converterIMDIVisibilityInverted" />
            <sys:String x:Key="LocStrings">Configuration.Materials.resx.MaterialsInternationalizedStrings</sys:String>
            <sys:String x:Key="AssemblyName">Lightning.UI.Controls</sys:String>

            <Style TargetType="{x:Type TextBox}">
                <Setter Property="VerticalContentAlignment" Value="Center" />
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Opacity" Value="0.5"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

            <Style TargetType="{x:Type GroupBox}" BasedOn="{StaticResource {x:Type GroupBox}}">
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Opacity" Value="0.5"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

            <Style TargetType="{x:Type Label}">
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Opacity" Value="0.5"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

            <LinearGradientBrush x:Key="SelectedBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFE1E0E8" Offset="0"/>
                <GradientStop Color="#FFA2A4A4" Offset="1"/>
                <GradientStop Color="#FF797A7D" Offset="0.521"/>
            </LinearGradientBrush>
        </controls:UserControlMultiTouchEnabled.Resources>

        <StackPanel Orientation="Vertical">
            <GroupBox Header="{Localize GroupBoxLabelImportMaterials, {StaticResource AssemblyName}, {StaticResource LocStrings}, DefaultValue=Import Materials}">
                <ListView VerticalAlignment="Top"
                      Visibility="{Binding Path=ImportedMaterials, Converter={StaticResource converterObjectRefToVisibility}}"
                      MouseMove="MouseMoveHandler"
                      StylusDown="StylusDownHandler"
                      ScrollViewer.CanContentScroll="True"
                      MaxHeight="450"
                      ItemsSource="{Binding ImportedMaterials}" 
                      SelectedItem="{Binding CurrentImportedMaterialSelection}"
                Margin="4,2">
                    <ListView.View>
(removed code)
                    </ListView.View>
                </ListView>
            </GroupBox>
        </StackPanel>
    </controls:UserControlMultiTouchEnabled>

=================================

Update (what the hell):

Now that I've discovered how to reliably cause the exception to occur on my development computer, this is the exception that I receive:

System.Windows.Markup.XamlParseException occurred
  Message="Cannot create instance of 'JobDockControlH' defined in assembly 'cutterUIControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation.  Error at object 'System.Windows.Controls.Grid' in markup file 'cutterUIControls;component/jobqueueviewh/xaml/jobstagingcontrolh.xaml' Line 94 Position 22."
  Source="PresentationFramework"
  LineNumber=94
  LinePosition=22
  NameContext="slidingDockBorder"
  StackTrace:
       at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
  InnerException: System.Reflection.TargetInvocationException
       Message="Exception has been thrown by the target of an invocation."
       Source="mscorlib"
       StackTrace:
            at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
            at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
            at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
            at System.Activator.CreateInstance(Type type, Boolean nonPublic)
            at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
       InnerException: System.TypeInitializationException
            Message="The type initializer for 'Lightning.JobReviewer.JobReviewViewModel' threw an exception."
            Source="Lightning.UI.Controls"
            TypeName="Lightning.JobReviewer.JobReviewViewModel"
            StackTrace:
                 at Lightning.JobReviewer.JobReviewViewModel.get_Instance()
                 at JobQueueViewH.JobDockViewModelH..ctor() in C:\Development\RonAchin\Dev\Z12.0\Endeavor\cutterUIControls\JobQueueViewH\cs\JobDockViewModelH.cs:line 239
                 at JobQueueViewH.JobDockControlH..ctor() in C:\Development\RonAchin\Dev\Z12.0\Endeavor\cutterUIControls\JobQueueViewH\XAML\JobDockControlH.xaml.cs:line 142
            InnerException: System.InvalidCastException
                 Message="Unable to cast COM object of type 'Windows7.Multitouch.ManipulationInterop.ManipulationProcessor' to interface type 'Windows7.Multitouch.ManipulationInterop.IManipulationProcessor'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A22AC519-8300-48A0-BEF4-F1BE8737DBA4}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."
                 Source="Windows7.Multitouch"
                 StackTrace:
                      at Windows7.Multitouch.ManipulationInterop.ManipulationProcessor.set_SupportedManipulations(MANIPULATION_PROCESSOR_MANIPULATIONS value)
                      at Windows7.Multitouch.Manipulation.ManipulationProcessor.set_SupportedManipulations(ProcessorManipulations value) in C:\D\Visual Studio 2008\Projects\Lightning\Dev\Zx\References\Windows7Multitouch\Mutitouch\Windows7.Multitouch\ManipulationProcessor.cs:line 461
                      at Windows7.Multitouch.Manipulation.ManipulationProcessor..ctor(ProcessorManipulations supportedManipulations) in C:\D\Visual Studio 2008\Projects\Lightning\Dev\Zx\References\Windows7Multitouch\Mutitouch\Windows7.Multitouch\ManipulationProcessor.cs:line 402
                      at Lightning.JobReviewer.JobReviewViewModel..ctor() in C:\Development\RonAchin\Dev\Z12.0\Endeavor\Controls\JobReviewer\cs\JobReviewViewModel.cs:line 93
                      at Lightning.JobReviewer.JobReviewViewModel..cctor() in C:\Development\RonAchin\Dev\Z12.0\Endeavor\Controls\JobReviewer\cs\JobReviewViewModel.cs:line 136
                 InnerException:

The strange thing is that I can execute code that causes the instantiation of the ManipulationProcessor over a million times in a loop early in the program with only an out of memory exception to show for it - no E_NOINTERFACE in sight. Harumph.

1

There are 1 answers

0
trapsuutjies On

I've run into the same issue, so I'm posting the solution that worked for me. I used a third party DLL to create a user control in a WPF application. When I started my application directly, it worked fine - but when I started it from another application (which is the normal usage), it failed with the exact same issues as above. To resolve it, I moved the variable declaration of the user control, from the XAML to the code behind. This means that the same DLL is now loaded when you're creating the variable, and instantiating it, so there's no conflict.