The "XamlCTask" task failed unexpectedly in Xamarin - xaml

I am currently having a problem building my Xamarin.Forms solution. I'm getting an error of The "XamlCTask" task failed unexpectedly. I tried looking at the Xamarin logs and Stacktrace but I can't seem to find what's the issue. Any suggestions where I can start looking?
Logs
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>0</EventID>
<Type>3</Type>
<SubType Name="Warning">0</SubType>
<Level>4</Level>
<TimeCreated SystemTime="2016-10-11T10:45:07.4999078Z" />
<Source Name="Xamarin.VisualStudio.Android.Designer.MonoAndroidDesignerService" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
<Execution ProcessName="devenv" ProcessID="19260" ThreadID="1" />
<Channel />
<Computer>XXXXXX</Computer>
</System>
<ApplicationData>An unexpected error occurred trying to initialize Android Designer.</ApplicationData>
</E2ETraceEvent>
Stack Trace
Severity Code Description Project File Line Suppression State
Error The "XamlCTask" task failed unexpectedly.
System.ArgumentException: An item with the same key has already been
added.
Server stack trace: at
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue
value, Boolean add) at
Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node,
XmlReader reader) at
Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean
nested) at
Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node,
XmlReader reader) at
Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean
nested) at
Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node,
XmlReader reader) at
Xamarin.Forms.Build.Tasks.XamlCTask.ParseXaml(Stream stream,
TypeReference typeReference) at
Xamarin.Forms.Build.Tasks.XamlCTask.Compile() at
Xamarin.Forms.Build.Tasks.XamlCTask.Execute() at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage
msg)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at Microsoft.Build.Framework.ITask.Execute()
at
Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at
Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() XXXXXXX.XXXXXX.XXXXXX

tl;dr:
disable XamlC on the failing Page
[XamlCompilationAttribute (XamlCompilationOptions.Skip)]
public partial class MyPageThrowing {}
or at the Assembly level
[assembly:XamlCompilationAttribute (XamlCompilationOptions.Skip)]
Long Story
An issue throwing the same exception and the same StackTrace had been fixed in the next (to date) version of xamarin.forms which should be 2.3.3-pre3 or 2.3.4.
The only way to know for sure would be to paste your failing Xaml page here, or even better, on http://bugzilla.xamarin.com.
I really encourage you to do so. If the issue is not fixed already. Either it's an issue in your Xaml and this needs a better exception being thrown, or it's an unsupported case in XamlC, and this require a fix.

First of all this issue will be raised when xamarin.forms version is not compatible with the nuget that you are pointed to. So i'd like to tell you these steps and go ahead.
Step1: Update Xamarin.Forms version in PCL and all other projects.
Step2: Check for matching dependencies with nuget package.i.e make sure everywhere the the solution is using the **same** version of the Xamarin.Forms.
Hope this will helps you.

Hope could be usefull to someone else, I had the same error shown in the question (..."XamlCTask" task failed unexpectedly. System.ArgumentException: An item with the same key has already been added...), my issue was caused by a ListViewTemplate, which contained a DataTemplate, in which I putted two elements, a Label and a Picker.
Grouping Label e Picker in a unique element, a Frame, inside the DataTemplate, solved my issue.

I already resolved the issue. Since I was renaming the namespaces, i named the namespaces alias wrong. I used dots (.) in the alias name like this xmlns:sample.pages="clr-namespace:JustAnotherNamespace". When I removed the dots, the solution was able to build!

I had the same problem. Clean or restart didn't help. Now I tried the simulator instead of the device. This worked. Afterwards I was able to build and run on the device.
Edit:
Now I had the issue a second time. But here it was different. The app didn't compile anymore. Now it seems to work. This is what I've done:
Upgrade to XF 2.3.3.168
Upgrade to XF 2.3.3.168 for the referenced project
Fixed a compile error (only appeared after update)

This occurs sometimes if your Xamarin Forms nugets are going corrupt. Uninstall and reinstall them.

Perhaps you have 2 instances of Visual Studio accessing the same device.

in this case removing bin and obj folder it seems works like a charm!

I had this error too. In my case it turned out to be a xaml issue. I hadn't made any recent changes to any dlls or references. I had just made some recent xaml changes and I suddenly started getting this error. This xaml I wrote had caused the issue:
<StackLayout Grid.Row="4" Orientation="Horizontal" HorizontalOptions="Center" >
<StackLayout.Children>
<Label Text="Holes" BackgroundColor="White" VerticalOptions="Center"/>
<Entry x:Name="entryHoles" BackgroundColor="White" WidthRequest="100"/>
</StackLayout.Children>
<StackLayout.Children>
<Label Text="Par" BackgroundColor="White" VerticalOptions="Center"/>
<Entry x:Name="entryPar" BackgroundColor="White" WidthRequest="100"/>
</StackLayout.Children>
</StackLayout>
There should be only one StackLayout.Children tag. This is what I switched to to get this error to go away:
<StackLayout Grid.Row="4" Orientation="Horizontal" HorizontalOptions="Center" >
<StackLayout.Children>
<Label Text="Holes" BackgroundColor="White" VerticalOptions="Center"/>
<Entry x:Name="entryHoles" BackgroundColor="White" WidthRequest="100"/>
<Label Text="Par" BackgroundColor="White" VerticalOptions="Center"/>
<Entry x:Name="entryPar" BackgroundColor="White" WidthRequest="100"/>
</StackLayout.Children>
</StackLayout>
I'll bet the extra StackLayout.Children tag caused this message: "An item with the same key has already been added." If so, it would have been great if Microsoft could have told us exactly what the duplicate item was. I wasted all kinds of time updating NuGet packages.

This error indicates that the versions of the NuGet packages and the version of Xamarin.Forms do not match.
Just update the NuGet packages in the project or remove Xamarin.Forms from the package list, then add it again.

I had 35 pages in my app with an assembly reference to turn on/off xaml compilation. To find the offending page I had to remove the assembly reference and place the following on each page and rebuild the shared project one at a time until I found the offending page (make sure you have release build selected).
#if (DEBUG != true)
[XamlCompilation(XamlCompilationOptions.Compile)]
#endif
Once you find the page, it's most likely a xaml issue like so many solutions above. For me it was because I had accidentally placed 2 resource dictionaries on the page so it was easy to spot, your's may not be so easy.

Related

Adding child elements to a HorizontalStackLayout causes "A cycle occurred while laying out the GUI" error

Im following allong the Youtube Series "Beyond Monkey" and on part 8, my XAML wont render at runtime (project compiles fine), hitting an error:
A cycle occurred while laying out the GUI.
Ive literally copied and pasted the code from the github repo to check its correct, but it still doesn't like it. I've pulled out bits of XAML everywhere until it builds and it seems it doesn't like the icon XAML:
<!-- Likes -->
<HorizontalStackLayout
Spacing="6"
VerticalOptions="Center">
<Image
Source="imglike.png"
WidthRequest="16"
HeightRequest="16" />
<Label
Style="{StaticResource RegularLightText14}"
Text="{Binding TheVideo.LikesCount, Mode=OneWay}" />
</HorizontalStackLayout>
If I strip the image and label out of the Horizontal Stack Layout it works, but as soon as I try to add any content to them, app.g.i.cs blows up with an unhandled exception
A cycle occurred while laying out the GUI.
Layout cycle detected. Layout could not complete.
The XAML looks ok to me and obviously works for the author, so I'm guessing is something unrelated that a XAML n00b like myself doesn't understand.
Anyone have any ideas?
Thanks

Using Resource files in XAML in Xamarin.Forms

I'm trying to use a resource file in my XAML. For some reason i keep getting the error of not finding the type Texts. Not sure what I'm doing wrong here.
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CashRegisterApp.Resources"
x:Class="CashRegisterApp.Start">
<ContentPage.Content>
<StackLayout
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" >
<Label Text="{x:Static local:Texts.Start}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
RESX
Solution explorer
Creating RESX files within Shared projects is known to cause issues. You can see several lengthy posts in Xamarin Forums regarding this (here and here for example).
The easiest solution that will allow you to use the approach you want is to create a new .NET Standard Library of PCL library in your solution, create your RESX files there and set their visibility to public. Then you will be able to utilize them using the x:Static syntax as expected.
Many developers use an alternative in the form of a custom markup extension like the solution by ClaudioPereira in this forum. This simplifies the syntax even more.
Finally, for most detailed information on Xamarin.Forms you can refer to the official documentation.
I had this issue too and I hope this answer helps people in the future with this issue.
Following this guide taught me how to set up resx files in Xamarin forms.
Their TranslateExtension allows for referring to the resx file directly from Xaml.
Unfortunately, in its raw form it doesn't pick up a runtime change in locales.
This is fixable by changing their "Localize" class (on the native platforms) to keep a reference of the CultureInfo when changed via the SetLocale method and return it when the GetCurrentCultureInfo method is called.

Conditional XAML causes XBF generator error

I am trying to set the Icon property of MenuFlyoutItem on the UWP. As this is only available in contract version 4, I wanted to use conditional XAML statements in form of the IsApiContractPresent statement. Doing this, I came up with this code:
<MenuFlyout>
<MenuFlyoutItem Text="Open">
<contract4Present:MenuFlyoutItem.Icon>
<FontIcon Glyph=""/>
</contract4Present:MenuFlyoutItem.Icon>
</MenuFlyoutItem>
</MenuFlyout>
and added this line in the definition of my page:
xmlns:contract4Present="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsApiContractPresent(Windows.Foundation.UniversalApiContract,5)"
Sadly, Visual Studio is now not able to compile the project anymore, with this error message:
The XAML Binary Format (XBF) generator reported syntax error '0x09C4' : Property Not Found
Strangely, the same errors comes up, when I use the minimal example given in the documentation
<TextBlock contract5NotPresent:Text="Hello, World"
contract5Present:Text="Hello, Fall Creators Update"/>
How can I solve this error? Or is this even a bug of Visual Studio?
Apparently, this functions is only available for Minimum Build versions > 15063. Otherwise, you must use version adaptive code, and not XAML.

How to use a control from a dll / assembly in XAML?

I have a CustomControl derived class in a dll (MyNamespace.UI). How can I use this control in my main application? I've tried adding a reference to the project and then using a custom XAML namespace to point to my namespace, but it can't find it:
<Page ...
xmlns:ui="using:MyNamespace.UI"
...>
<Canvas>
<ui:MyControl />
</Canvas>
</Page>
I get an error:
The name "MyControl" does not exist in the namespace "using:MyNamespace.UI".
Searching around, I managed to find the following quote:
The name of the assembly that defines the backing types for a XAML
namespace is not specified in the mapping. The logic for which
assemblies are available is controlled at the app-definition level and
is part of basic app deployment and security principles. Declare any
assembly that you want included as a code-definition source for XAML
as a dependent assembly in project settings.
http://msdn.microsoft.com/en-gb/library/windows/apps/jj150588.aspx
Can someone point me in the direction of the "dependent assembly" setting in the project settings?
Edit After making sure the root namespace project setting matched the namespace of my control (MyNamespace.UI) I could get the project to compile. But I can't get it to run because I get loads of crashes with the following information:
WinRT information: Cannot create instance of type 'MyNamespace.UI.MyControl' [Line: 44 Position: 37]
No information on why it couldn't make the control though... I stepped through the constructor of MyControl and the exception is thrown in InitializeComponent(). This is the XAML of my UserControl (MyControl):
<UserControl
x:Class="MyNamespace.UI.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
</Grid>
</UserControl>
Edit 2 I deleted the Grid control, built and ran, and it worked, so then I put the Grid control back, and it still worked. Very weird.
You need to make sure the MyNamespace.UI assembly has a RootNamespace property that matches MyNamespace.UI. This property can't be changed in the project settings pages, but you can do it via notepad or equivalent. My RootNamespace was set to UI, and when I changed it, it started working.

Can't access font resource in Silverlight class library

I have a reasonably large Silveright 3.0 project on the go, and I'm having issues accessing a couple of custom font resources from within one of the assemblies.
I've got a working test solution where I have added a custom font as a resource, and can access it fine from XAML using:
<TextBlock Text="Test" FontFamily="FontName.ttf#Font Name" />
The test solution consists of the TestProject.Application and the TestProject.Application.Web projects, with all the fun and games obviously in the TestProject.Application project
However, when I try this in my main solution, the fonts refuse to show in the correct type face (instead showing in the default font). There's no difference in the way the font has been added to project between the test solution and the main solution, and the XAML is identical.
However, there is a solution layout difference. In the main solution, as well as having a MainApp.Application and MainApp.Application.Web project, I also have a MainApp.Application.ViewModel project and a MainApp.Application.Views project, and the problem piece of XAML is the in the MainApp.Application.Views project (not the .Application project like the test solution).
I've tried putting the font into either the .Application or .Application.Views project, tried changing the Build Action to Content, Embedded Resource etc, all to no avail.
So, is there an issue accessing font resources from a child assembly that I don't know about, or has anyone successfully done this?
My long term need will be to have the valid custom fonts being stored as resources in a separate .Application.FontLibrary assembly that will be on-demand downloaded and cached, and the XAML controls in the .Application.Views project will need to reference this FontLibrary assembly to get the valid fonts. I've also tried xcreating this separate font library assembly, and I can't seem to get the fonts from the second assembly.
As some additional information, I've also tried the following font referencing approaches:
<TextBlock Text="Test" FontFamily="/FontName.ttf#Font Name" />
<TextBlock Text="Test" FontFamily="pack:application,,,/FontName.ttf#Font Name" />
<TextBlock Text="Test" FontFamily="pack:application,,,/MainApp.Application.Views;/FontName.ttf#Font Name" />
<TextBlock Text="Test" FontFamily="pack:application,,,/MainApp.Application.Views;component/FontName.ttf#Font Name" />
And a few similar variants with different assembly references/sub directories/random semi colons.
And so far nothing works... anyone struck this (and preferably solved it)?
This code works for me:
... FontFamily="/(DLL);Component/(DIR-optional)/(Font_file)#(Font_name)"/> ...