Xaml Compilation - Object reference not set to an instance of an object

When trying to use XAML Compilation i always get this issue when building:

1> Module: TestApp.dll
1> Resource: TestApp.Page1.xaml...
1> Parsing Xaml... done.
1> Replacing Page1.InitializeComponent ()... failed.
1> C:\ProyectosInvestigacion\TestApp\TestApp\TestApp\TestApp.Page1.xaml : error : Object reference not set to an instance of an object.
1> at Xamarin.Forms.Build.Tasks.SetNamescopesAndRegisterNamesVisitor.CreateNamescope()
1> at Xamarin.Forms.Build.Tasks.SetNamescopesAndRegisterNamesVisitor.Visit(RootNode node, INode parentNode)
1> at Xamarin.Forms.Xaml.RootNode.Accept(IXamlNodeVisitor visitor, INode parentNode)
1> at Xamarin.Forms.Build.Tasks.XamlCTask.Compile()

I've done a simple TestProject in which i added one Xaml page and configured it to compile:

    [XamlCompilation(Xamarin.Forms.Xaml.XamlCompilationOptions.Compile)]
    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();

        }
    }

And the Xaml here:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestApp.Page1">
  <Label x:Name="lblText" Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

This always throws "Object reference not set to an instance of an object" on the Error List using Visual Studio 2013, Xamarin Forms 2.1.0.6529
I'm attaching the whole solution so anyone can reproduce this error.

Is there a known way to get Xaml Compilation working?

Posts

  • GeraldVersluisGeraldVersluis NLUniversity ✭✭✭✭

    You forgot to attach your project!

  • NMackayNMackay GBInsider, University ✭✭✭✭✭

    @AndresBlasPujadas

    I've had this before after upgrading to that version of Forms. I deleted my obj & bin folders in all solutions, closed the solution, deleted the folders (leave repositories.config). Reopen solutions, restore packages and then compile. Just double check Forms has been added to the Droid and iOS projects.

    It might help.

  • AndresBlasPujadasAndresBlasPujadas USMember ✭✭

    While making this post, i've realized that the issue occurs when the Xamarin Forms PCL project references to a dll located on a directory where i place all the output from other projects. Deleting this reference, the problem went away.

    So, if you have a solution in which all your projects build and generate output files into the same folder, and you use those dll files as reference for other projects, there is where the initial issue occurs. I'll try to build this configuration and share it so anyone can reproduce this problem.

  • AndresBlasPujadasAndresBlasPujadas USMember ✭✭

    I've found the way to reproduce this error!

    I you reference a dll from a common output folder, AND there in that folder both files:
    Xamarin.Forms.Xaml.dll
    Xamarin.Forms.Xaml.xml
    exist, the issue occurs.

    I'm attaching the solution now.

  • AndresBlasPujadasAndresBlasPujadas USMember ✭✭

    After solving all Xaml's errors when building, i get a final issue which keeps blocking my development. I've modified the Xamarin.Forms.targets file to increase the verbosity of the XamlCTask. Digging into the build logs i've found this:

    \packages\Xamarin.Forms.2.1.0.6529\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets(62,3): error : Member 'System.DateTime' is declared in another module and needs to be imported
    9> at Mono.Cecil.MetadataBuilder.LookupToken(IMetadataTokenProvider provider)
    9> at Mono.Cecil.SignatureWriter.WriteTypeSignature(TypeReference type)
    9> at Mono.Cecil.SignatureWriter.WriteMethodSignature(IMethodSignature method)
    9> at Mono.Cecil.MetadataBuilder.GetMemberRefSignature(MemberReference member)
    9> at Mono.Cecil.MetadataBuilder.CreateMemberRefRow(MemberReference member)
    9> at Mono.Cecil.MetadataBuilder.GetMemberRefToken(MemberReference member)
    9> at Mono.Cecil.MetadataBuilder.LookupToken(IMetadataTokenProvider provider)
    9> at Mono.Cecil.Cil.CodeWriter.WriteOperand(Instruction instruction)
    9> at Mono.Cecil.Cil.CodeWriter.WriteInstructions()
    9> at Mono.Cecil.Cil.CodeWriter.WriteResolvedMethodBody(MethodDefinition method)
    9> at Mono.Cecil.Cil.CodeWriter.WriteMethodBody(MethodDefinition method)
    9> at Mono.Cecil.MetadataBuilder.AddMethod(MethodDefinition method)
    9> at Mono.Cecil.MetadataBuilder.AddMethods(TypeDefinition type)
    9> at Mono.Cecil.MetadataBuilder.AddType(TypeDefinition type)
    9> at Mono.Cecil.MetadataBuilder.AddTypeDefs()
    9> at Mono.Cecil.MetadataBuilder.BuildTypes()
    9> at Mono.Cecil.MetadataBuilder.BuildModule()
    9> at Mono.Cecil.ModuleWriter.b__0(MetadataBuilder builder, MetadataReader _)
    9> at Mono.Cecil.ModuleDefinition.Read[TItem,TRet](TItem item, Func`3 read)
    9> at Mono.Cecil.ModuleWriter.BuildMetadata(ModuleDefinition module, MetadataBuilder metadata)
    9> at Mono.Cecil.ModuleWriter.WriteModuleTo(ModuleDefinition module, Stream stream, WriterParameters parameters)
    9> at Mono.Cecil.ModuleDefinition.Write(Stream stream, WriterParameters parameters)
    9> at Mono.Cecil.ModuleDefinition.Write(String fileName, WriterParameters parameters)
    9> at Xamarin.Forms.Build.Tasks.XamlCTask.Compile()

    Lost several hours trying to get the Xaml Compilation running. Any ideas? Is this a Xamarin issue?

  • Norman.NeubauerNorman.Neubauer USMember
    edited April 2016

    You might find the following answer useful:

    https://forums.xamarin.com/discussion/61750/xaml-compile-time-checking-problem#Comment_183179

    I had the same problem with a reference to System.DateTime and got it working by changing:

    to:

    (and removing the namespace reference to System from the top of the XAML).

  • Apologies if this double posts (Markdown newbie here), but you might find the following post useful:

    https://forums.xamarin.com/discussion/61750/xaml-compile-time-checking-problem#Comment_183179

    I had a similar issue with System.DateTime and in my case, managed to get XAML compilation working when I changed this:
    <system:DateTime x:FactoryMethod="get_Today" />
    to:
    <x:DateTime x:FactoryMethod="get_Today" />
    (and removed the reference to the System namespace at the top of the file).

  • AndresBlasPujadasAndresBlasPujadas USMember ✭✭

    @Norman.Neubauer your answer looks promising. As soon i can test this, i'll post an update. Thank you!

  • AndresBlasPujadasAndresBlasPujadas USMember ✭✭

    This was the solution:
    Change
    <system:DateTime x:FactoryMethod="get_Today" />
    to:
    <x:DateTime x:FactoryMethod="get_Today" />

    Once again, thanks @Norman.Neubauer !

  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    I tried this solution, but now I get a InvalidProgramException: Invalid IL code

    This is the Xaml Part

      <DatePicker IsVisible="False" x:Name="DateSelector"  HorizontalOptions="Center" VerticalOptions="CenterAndExpand" 
             DateSelected="OnDateSelected">
        <DatePicker.Format>yyyy-MM-dd</DatePicker.Format>
        <DatePicker.MinimumDate>
          <x:DateTime x:FactoryMethod="Parse">
            <x:Arguments>
              <x:String>Jan 1 2000</x:String>
            </x:Arguments>
          </x:DateTime>
        </DatePicker.MinimumDate>
        <DatePicker.MaximumDate>
          <x:DateTime x:FactoryMethod="Parse">
            <x:Arguments>
              <x:String>Dec 31 2050</x:String>
            </x:Arguments>
          </x:DateTime>
        </DatePicker.MaximumDate>
      </DatePicker>
    
  • @ThomasBurkhart said:
    I tried this solution, but now I get a InvalidProgramException: Invalid IL code

    Same problem here.

  • JTEJTE USMember ✭✭

    @SaschaSchwegelbauer said:

    @ThomasBurkhart said:
    I tried this solution, but now I get a InvalidProgramException: Invalid IL code

    Same problem here.

    and here. how to fix it?

  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭

    DateTime is not a Xaml 2009 built-in type: https://msdn.microsoft.com/en-us/library/ee792002(v=vs.110).aspx, but we have a conversion built-in for string to date time, so the 2 version below works

    <DatePicker x:Name="datetime0" Date="2015-01-16"/>
    <DatePicker x:Name="datetime1">
        <DatePicker.Date>2015-01-16</DatePicker.Date>
    </DatePicker>
    

    if you wonder which format your date should be in the xaml, like for everything else (numbers, ...), the xaml parser parses date times using the InvariantCulture

    I'm now looking at why XamlC doesn't work with the "system:" xmlns, and why x:FactoryMethod="Parse" doesn't work, but this should get you started

  • NMackayNMackay GBInsider, University ✭✭✭✭✭

    @StephaneDelcroix

    I had the same error yesterday but it turned out I was binding to a const not a static but it was a really hard issue to debug as you had no clue where to start.

    <Image Source="{markupExtensions:PlatformImageExt SourceImage={x:Static resources:ImageResources.SliderDrawerUserIcon}}"> - SliderDrawerUserIcon was a const.

    Ended up commenting out XAML till I got to the bottom of the issue. I also got the same error for putting a content page within a tab but the content page used constructor injection.

    This may be a Visual Studio tooling issue but it would be nice if the error handling for XAML give some more clues, Object reference not set to an instance of an object means it could be a fairly wide range of issues.

  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭

    @NMackay generic errors are the errors I'm not aware about. For all the known cases, we throw a XamlPArseException with a message and a position in file.

    x:Static is supposed to find: public static fields, properties, consts and enum values. Could you please send me a short project triggering this issue ? thanks

  • NMackayNMackay GBInsider, University ✭✭✭✭✭
  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭

    I fixed the issues related to this here https://github.com/xamarin/Xamarin.Forms/pull/642

    Please note:

    • you shouldn't rely on DateTime being declared in the x: xmlns, but in xmlns:sys="clr-namespace:System;assembly=mscorlib"
    • Parse works, but the date is parsed at runtime. if you do <DatePicker.Date>2015-01-16</DatePicker.Date> the parsing is done at compile time. If performance matters to you, I recommend this approach
    • <system:DateTime x:FactoryMethod="get_Today" /> is creative, a better approach is Date="{x:Static sys:DateTime.Now}"
  • AhmedAlejoAhmedAlejo USMember ✭✭

    @NMackay said:
    @StephaneDelcroix

    I had the same error yesterday but it turned out I was binding to a const not a static but it was a really hard issue to debug as you had no clue where to start.

    <Image Source="{markupExtensions:PlatformImageExt SourceImage={x:Static resources:ImageResources.SliderDrawerUserIcon}}"> - SliderDrawerUserIcon was a const.

    Ended up commenting out XAML till I got to the bottom of the issue. I also got the same error for putting a content page within a tab but the content page used constructor injection.

    This may be a Visual Studio tooling issue but it would be nice if the error handling for XAML give some more clues, Object reference not set to an instance of an object means it could be a fairly wide range of issues.

    That was my issue in this case:

    @StephaneDelcroix the following is the only message i receive:

    Severity    Code    Description Project File    Line    Suppression State
    Error       Object reference not set to an instance of an object.   Mobile.Booking  C:\Build\Mobile.Booking\Views.NoteDetailsView.xaml      
    
  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭

    @NMackay, @AhmedAlejo: I can't reproduce the error message you're getting. x:Static is supposed to works with constants. Please send me a very short project triggering the NullReferenceException and I'll look at it, and make sure it throws a meaningful exception next time.

  • NMackayNMackay GBInsider, University ✭✭✭✭✭

    @StephaneDelcroix

    It was intermittent and I haven't been able to reproduce it since sadly. I wrote a repo project which couldn't reproduce the issue so I didn't waste you time with it.

    No idea if the issue was in Visual Studio/Xamarin extension.

  • EliBlackEliBlack USMember
    edited January 24

    When using XAMLC, I'm getting an "Object reference not set to an instance of an object" error message for a different case: when I define <Grid.Resources> and don't put a <ResourceDictionary> in it.

    i.e.

    <Grid Grid.Row="2" BackgroundColor="#557ea3">
       <Grid.Resources>
         <Style TargetType="Image">
           <Setter Property="Margin" Value="0"/>
         </Style>
       </Grid.Resources>
     </Grid>
    

    It would be nice if there were a more clear error message for this, if possible :)

  • Malcolm.JackMalcolm.Jack ZAMember ✭✭

    For me it was that I had a project dependency that was referencing an older version of the Xamarin Forms nuget package.
    Use Solution | Manage Nuget Packages for Solution -> Consolidate tab to check this

  • FilipeBezerraSousaFilipeBezerraSousa BRMember ✭✭
    edited March 13

    I'm migrating my PCL project to latest Xamarin Forms (2.3.3.193) and all XAML were created with XAMLC and one of XAML is using DatePicker with MinimumDate="{Binding Source={x:Static sys:DateTime.Now}" and the xmlns:sys="clr-namespace:System;assembly=mscorlib".

    With that I'm getting this compilation error: Member 'System.DateTime' is declared in another module and needs to be imported

    I could solve this compilation error skiping the XAML compilation with [XamlCompilation(XamlCompilationOptions.Skip)] and everything work fine, but I wanna use the XAMLC because it give me performance.

    So the question is: How can I fix this? Why the XAML compiler is preventing me to use the DateTime.Now as a static resource?

  • FilipeBezerraSousaFilipeBezerraSousa BRMember ✭✭

    Somebody can help here?

  • aw230012aw230012 USMember ✭✭

    To add another scenario, I see this when switching Git branches while Xamarin Studio is open. The solution to Clean All and restart Xamarin Studio fixes this scenario.

  • tonholistonholis USMember ✭✭

    What worked for me was reinstalling all packages with: Update-Package -reinstall

Sign In or Register to comment.