MvvmCross.Exceptions.MvxException: Failed to create setup instance - c#

I'm upgrading from MvvMCross 5.7 to 6.0.0.
When I try to run the app, it shows the splash screen and just after that, vs2017 gives me the following error:
MvvmCross.Exceptions.MvxException: Failed to create setup instance
The error always is in the same line, no matter which file I set as mainlauncher.
Example:
using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using MvvmCross.Platforms.Android.Views;
namespace ClaveiSGApp.Droid.Views
{
[Activity(Label = "App", MainLauncher = true)]
public class MainView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.MainView);
}
}
}
The error always is in base.OnCreate(bundle);
Do you have any ideas?
(Let me know if you need more info/code about something)

From the error you're getting, it looks like something bad is happening in CreateSetup method in MvxSetupSingleton (GitHub). I'm guessing here a bit, but I would assume that there's something wrong with how the RegisterSetupType<TMvxSetup> is being called (or it's not being called at all) - you can find this method in MvxSetup (GitHub). Tracking down where the registration happens, it gave me two possible places: MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and MvxAndroidApplication<TMvxAndroidSetup, TApplication>.
Going forward with this thinking, and assuming you do use SplashScreen in your app. I would suggest updating your SplashScreen activity to inherit from MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and check if that helps - you would also need to make your SplashScreen is MainLauncher. Your code could look like this:
[Activity(Label = "FirstDemo.Forms.Splash", Theme = "#style/MainTheme", MainLauncher = true, NoHistory = true)]
public class SplashScreen : MvxFormsSplashScreenAppCompatActivity<MvxFormsAndroidSetup<Core.App, App>, Core.App, App>
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
protected override void RunAppStart(Bundle bundle)
{
StartActivity(typeof(MainActivity));
base.RunAppStart(bundle);
}
}
If the above is not clear, check out blog post by Nick Randolph (a contributor to MvvmCross), that writes about setting up a brand new project with MvvmCross v6. I know you're upgrading - so it's not the same, but you can at least check if you have made all the changes that are required to run the app. Here's his GitHub repo, with the sample code that I pasted in

After I few days, searching, seeing gihub files and talking with Nick Randolph as #Ale_lipa suggested.
I noticed that the problem was on the .csproj file under the .Droid project. It was trying to compile files that I manually removed from the project and didn't even exist.
I changed it to match the file that Nick has in his repository.
This is the final look:
<ItemGroup>
<Compile Include="SplashScreen.cs" />
<Compile Include="MainApplication.cs" />
<Compile Include="Resources\Resource.Designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Views\FirstView.cs" />
</ItemGroup>
Now everything works fine.

I followed the exact steps on the blog post series by Nick Randolph referenced in other answers, and received the same problem as the question specifies [Failed to create setup instance] but in the Xamarin.Forms article. This was due to mixing code from a different part of the example. My specific issue was because the ActivityAttribute that declared MainLauncher=true derived from MvxFormsAppCompatActivity<TViewModel> instead of MvxFormsAppCompatActivity<TMvxAndroidSetup, TApplication, TFormsApplication, TViewModel> Looks like the OP #Brugui sample code may have had the same flaw.

Related

Access source generated class property/method in main code MSVS 2022

I created my first source generator (ISourceGenerator) with public property and public method.
Let this class be like this:
public partial class MyClass1 // Manually written code
{
}
public partial class MyClass1 //Source Generated code
{
public string GeneratedProperty { get; set; }
public string GeneratedMethod() => "lala";
}
Both of these classes are located in the same namespace (for example, MyNamespace - it doesn't matter really).
So, I'm trying this:
var myClass = new MyClass1(); // Correct
Console.WriteLine(myClass.GeneratedMethod()); //Wrong, "MyClass1 doesn't contain definition for GeneratedMethod..."
When I say MSVS generate sources as files in the concrete directory, I have the code above working well.
So, I want to have an ability to use generated code "on fly" when I write code without generation source files each time manually. Also earlier manually generated source files are not deleted when I'm generating new source files.
Is it possible?
Thank you.
UPD. I have this message from Visual Studio:
"Warning CS8032 An instance of analyzer Generators.Factory.AbstractFactoryGenerator cannot be created from ...\bin\Debug\netstandard2.0\SourceGeneratorsLibrary.dll: Exception has been thrown by the target of an invocation."
Maybe this significant?
UPD2. https://pastebin.com/qtvrugu3 - this is my Source Generator code. Pls, don't blame me, It's just my first steps.
As far as I know, programming is case sensitive, well at least C# so myClass() is different from MyClass(). also hence you are using the string data type, try casting it as string via
Convert.ToString(MyClass1().GeneratedMethod());
or
MyClass1().GeneratedMethod().ToString();
hope this answers you question.
It seems you have developed your analyzer but not actually referenced it from a project?
To use your analyzer you simply add it as as project reference, but make sure it's marked up as an analyzer in the .csproj file:
<ItemGroup>
<ProjectReference Include="MyGenerator\MyGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
Or something like that, adjusted to your solution.

xamarin C#: 'Resource' does not contain a definition for 'Id'

I recently started working with Xamarin to build Android apps in C#.
There is one issue I have had in particular that makes it very hard for me to make any progress:
error CS0117
I have two identical projects, the issue only shows up in one of them.
It originally occured in both but rebuilding a few times fixed the first one.
The second one seems to be more persistent.
I really need to find a solution to this issue, as referencing is very basic and needed. Not to mention, it happens in every new project.
Here is my code:
NoteMath
using System;
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace NoteMath_v1._0._1
{
[Activity(Label = "noteMath", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Window.RequestFeature(Android.Views.WindowFeatures.NoTitle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
EditText etInput = FindViewById<EditText>(Resource.Id.etInput);
TextView tvConsole = FindViewById<TextView>(Resource.Id.tvConsole);
etInput.KeyPress += (object sender, EditText.KeyEventArgs e) =>
{
e.Handled = false;
if (e.Event.Action == Android.Views.KeyEventActions.Down && e.KeyCode == Android.Views.Keycode.Enter)
{
tvConsole.Append("\n>" + HandleInput.TransferInput(etInput.Text));
etInput.Text = "";
e.Handled = true;
}
};
}
}
}
The code you posted looks good. The error is clearly not coming from there. You´ve got something wrong in any of your resource layout or xml files.
The problem actually is that Visual Studio won´t show up Resource generation errors in the Errors panel, eventhough it should be like that (I think this will be fixed in future versions). At the moment it is just telling you that the class Id doesn´t exists.
Resources.designer.cs is a class generated by Xamarin when you edit any resource file. It containts references to any declaration, id, etc in the xml/axml files. If the resource has an error, Resources.designer.cs generation will fail, but you get a really vague error hint.
The first thing you can try is rebuilding your Android project, forcing all resources to be generated again. Otherwise try the following:
Good news is that you can see generation errors by changing build output verbosity to "detailed":
Now compile your project again and check the output window. It will tell you exactly what the problem is.
After you fix it, Resource.Id class will be generated.
For me, this worked:
Step 1.
Project > Update NugetPackages
Step 2.
Build > Clean All
Step 3.
Build > Build All
I am super new. The only thing that really worked for me was manually running this powershell script in my project root:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
I am not sure why the live view/build output isn't more helpful, or that visual studio isn't cleaning these files correctly in my xamarin project.
Special thanks to this guy:
https://montemagno.com/easily-clean-bin-obj-folders/

Xamarin Android(Mac) persisting error: "Could not load System.Drawing"

First let make clear that this is my first Android project ever that I'm trying to complete, so I'm still very new to all this.
I've been stuck with this extremely annoying problem where I can't compile my project anymore even after removing a lot things. At one point in my project I added the 'System' namespace to use the 'Exception' keyword(to test a DB connection). All was working fine and well right before this point. But after trying to compile I got the error:
/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: error : Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Drawing.dll'
So I just added 'using System.Drawing' on top but later I read that Xamarin Android doesn't support that. So I removed it again and tried to remove whatever I did to try stop getting this Exception. Then this error got stuck forever even if I comment all things out. I can write 'using System.Drawing' without the system giving that line an error, which I thought was weird because it's nowhere to found in the references. I also really don't get it since I don't draw anything and don't think use anything from System.Drawing. Any time I reference the 'System' package I get this error, I can't go without because some android files rely on it. I've now lost hours now without any progress and basically am at the end of my road here.
Here's my MainActivity.cs file as it is now, narrowed down, it's my only .cs file:
using Android.Graphics;
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using MySql.Data.MySqlClient;
using System;
namespace MapApp
{
[Activity(Label = "MapApp", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity, IOnMapReadyCallback
{
GoogleMap GMap;
/// database
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
}
private void SetUpMap()
{
if (GMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap map)
{
GMap = map;
GMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(
new LatLng(51.873176, 4.393930),
new LatLng(51.994576, 4.598036)));
GMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.917879,4.481134),13));
/*MarkerOptions markerOpt1 = new MarkerOptions();
markerOpt1.SetPosition(new LatLng(51.917879, 4.481134));
markerOpt1.SetTitle("Vimy Ridge");
GMap.AddMarker(markerOpt1);*/
CircleOptions dangerZone = new CircleOptions();
dangerZone.InvokeCenter(new LatLng(51.917879, 4.481134));
dangerZone.InvokeRadius(100);
dangerZone.InvokeFillColor(0x7F00FF00);
dangerZone.InvokeStrokeWidth(0);
GMap.AddCircle(dangerZone);
}
}
}
Here is a picture of my references and packages.(a lot of Xamarin packages in there because those were needed to load Google Maps):
Here another picture of my project structure as is, if it may help identify the problem.
I have tried to delete all my packages and clean my Big/Debug folder and rebuild everything but error still proceeds.
Everything worked perfectly and now I just can't build it anymore. I wrote "using System" once, got this error, and then never couldn't get rid of this error anymore.
I really do not want to restart my project for the second time, after getting getting unknown errors every hour so any help would GREATLY be appreciated.
I have found the problem thanks to using Diagnostic logging.
Turns out the 'MySql.Data' package loads 'System.Drawing' which of course is not supported in Xamarin.Android.
Dependency System.Drawing, Version=4.0.0.0, Culture=neutral,
Required by MySql.Data, Version=6.9.9.0, Culture=neutral
Thanks to Lexi Li for giving the one tip I exactly needed!

Xamarin Forms error: Java.Lang.NoClassDefFoundError: android.support.graphics.drawable.VectorDrawableCompat

When starting debugging of my project on the Android emulator I receive this error:
Java.Lang.NoClassDefFoundError: android.support.graphics.drawable.VectorDrawableCompat
At this code:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
//SQLitePCL.Batteries.Init();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
string dbPath = FileAccessHelper.GetLocalFilePath("clocker.db3");
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new Clocker.App(dbPath));
}
}
The error occurs on this row:
base.OnCreate(bundle);
I have tried looking online at the other suggestions but the answers seem related to specific Xamarin studio files which are non-existant in my project (i.g. the gradle file).
I have checked the contents of 'bundle' and it seems to be null at the time of the error but I'm unsure if this is causing the error.
I'm using Xamarin forms PCL.
This error may occurs with several class if the project path is too long, because it go through the limit of Operational System character length.
Example of Long path:
C:\Users\Username\Documents\Visual Studio xxxx\Projects\Project Name
Example of Good path:
C:\Projects\ProjectName
EDIT - Added how the packages should look:
The error Java.Lang.NoClassDefFoundError: means that you're missing a class. It tells you which class you're missing as well: android.support.graphics.drawable.VectorDrawableCompat. I've not used Xamarin myself, but their documentation describes how to use Java classes in C# code. Once the package which includes the class android.support.graphics.drawable.VectorDrawableCompat (VectorDrawableCompat.java, which is in android.support.graphics.drawable I think?) is imported, your code should run.
I am not sure if this will help you but look at the way the MainActivity is declared.
Your example has:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
But in my code i have:
public class MainActivity : Xamarin.Forms.Platform.Android.FormsApplicationActivity
See if that makes a difference to the startup.
If you have to use FormsAppCompatActivity then see if changing the Api level to the highest supported level makes a difference.
Do you have any logs from the Output window, Show Xamarin Diagnostics.
I had a similar error. I resolved it to install the latest version of JDK and select the new folder in Visual Studio.

Visual Studio opens my class-file (.cs) in the designer mode

I've created a class that extends DbConnection in a brand new project.
public class FakeDbConnection : DbConnection { ... }
In the Solution Explorer the class looks like this:
And when double-clicking it wants to open it in design mode which won't work. Opening up the .csproj-file reveals the problem
<ItemGroup>
<Compile Include="FakeADO\FakeDbConnection.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
Even if I remove the SubType tag VS2010 immediately re-adds it. Very annoying.
How can I stop VS2010 from opening up my .cs file in designer mode and just open it up as a regular code file?
As described in an answer to this question you can do this:
[System.ComponentModel.DesignerCategory("Code")]
class FakeDbConnection: DbConnection { ... }
Important: The attribute needs to be fully qualified otherwise VS2010 will ignore this.
Important (thanks to jmbpiano): The attribute only applies to the first class in the file.
The inheritance hierarchy indicates that this class (DbConnection) inherits from System.ComponentModel.Component. Try right click the file and View Source instead.
As always you can check MSDN! Here is the documentation for DbConnection.
Thats because DBConnection inherits "Component".
About disabling VS to add "Subtype" in csproj-file - I don't think thats possible.
You can still aceess the code, by right-clicking in designer -> show code (I think "F7" is the shortcut key for that)

Categories