How to deal with System.TypeLoadException in the app.xaml.cs in xamarin.forms? - c#

Sorry to bother you, but I've come across a error in my code I don't how to deal with.
Whenever I try to run my app, I get faced with this:
System.TypeLoadException: 'Could not resolve type with token 01000019
from typeref (expected class
'Xamarin.Forms.Xaml.Diagnostics.VisualDiagnostics' in assembly
'Xamarin.Forms.Core, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=null')'
It states it occurs when the InitializeComponent(); is called in the constructor of App.xaml.cs.
Constructor in question:
public App()
{
//Line throwing the error
InitializeComponent();
MainPage = new NavigationPage(new Login.LogonFinal()); //Defines what page the app opens on when starting
}
App.xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace NEA_I_MDL
{
public partial class App : Application
{
static Databases.AccountDatabaseController AccountDatabaseVar;
public App()
{
//Line throwing the error
InitializeComponent();
MainPage = new NavigationPage(new Login.LogonFinal()); //Defines what page the app opens on when starting
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
public static Databases.AccountDatabaseController AccountDatabaseFunc
{
get
{
if(AccountDatabaseVar == null)
{
AccountDatabaseVar = new Databases.AccountDatabaseController();
}
return AccountDatabaseVar;
}
}
}
}
Thank you for reading, any tips/assistance will be a huge help for ineptly written code.

Can I ask that you please
Make sure you dont have different versions of the same Nugets in your solution.
Clean & Rebuild your Project
If That doesn't work for you try delete all your obj and bin folders and rebuild.
This usually happens because of Updates or version conflicts In my case atleast.
And do you mind showing us the LoginFinal Method?
I think you can just call Login
MainPage = new NavigationPage(new Login);

Related

How to fix crash problem when using WebView in SeparateProcess execution mode?

In order to use WebGL in UWP WebView , I looked for this.
How do I enable WebGL in Xamarin.Forms WebView on UWP?
But a new problem comes. When navigating to another page and go back for a few times, the application crashed and gives you no explain. It seems like too many webview instance was created then I tried to use Singleton pattern to solve it.
public static class WebViewSingleton
{
private static WebView instance;
public static WebView GetInstance()
{
if (instance == null)
{
instance = new WebView(WebViewExecutionMode.SeparateProcess)
{
Source = new Uri("https://www.google.com/")
};
}
return instance;
}
}
public HomePage()
{
this.InitializeComponent();
MyWebView = WebViewSingleton.GetInstance();
MyWebView.Navigate(new Uri("https://sketchfab.com/models/a6af6d1ae2744a55820d00599aca71f2/embed?
autostart=1&internal=1&ui_infos=0&ui_snapshots=1&ui_stop=0&ui_watermark=0"));
this.RootGrid.Children.Add(MyWebView);
}
In this way, debugger tells me MyWebView is already a children for another element. I tried every way to disconnect MyWebView with it's parent but failed.
I find it works when adding NavigationCacheMode="Enabled" to my page, but that is not what I want.
add this to page.xmal
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (this.RootGrid.Children.Contains(MyWebView))
{
this.RootGrid.Children.Remove(MyWebView);
}
}

How is Setup class instantiated in MVVMCross in Xamarin?

I'm starting learning MVVM cross, In the android app, I have a splash screen class:
[Activity(MainLauncher = true,
Label = "#string/app_name",
Theme = "#style/Theme.Splash",
NoHistory = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
ScreenOrientation = ScreenOrientation.Portrait)]
public class SplashScreen : MvxSplashScreenActivity
{
public SplashScreen() : base(Resource.Layout.SplashScreen)
{
}
}
and this is the Setup class:
public class Setup : MvxAndroidSetup
{
protected Setup(Context applicationContext) : base(applicationContext)
{
}
protected override IMvxApplication CreateApp()
{
return null;
}
}
the problem is that the debugger doesn't hit the constructor of the Setup Class, instead I get "An unhandled exception" after the constructor of the splash screen
EDIT
I've already defined the App class in the PCL project:
public class App : MvxApplication
{
public override void Initialize()
{
base.Initialize();
}
also defined the AppStart:
public class AppStart : MvxNavigatingObject, IMvxAppStart
{
public async void Start(object hint = null)
{
//hardcoded login for this demo
//var userService = Mvx.Resolve<IUserDataService>();
//await userService.Login("gillcleeren", "123456");
ShowViewModel<MainViewModel>();
}
}
The main reason behind this project is to understand the sequence of code required and executed by MVVM Cross, so I provide the minimum code till it runs successfully without runtime errors.
Update
I have read your code again more thoroughly and I can see the issue now. You defined the constructor of the Setup class as protected, which makes it invisible for activation.
On MvvmCross for Android the magic happens inside MvxAndroidSetupSingleton class (see the source code here) which searches for the Setup type you defined. The FindSetupType method looks for your defined Setup class first and then inside the CreateSetup method Activator.CreateInstance is used to build the Setup instance. The CreateInstance method variant used however searches only for public constructors, which means it doesn't find your protected one. The result is that it cannot build the Setup class and crashes.
Original answer
The reason this happens is that you have no Core libary that would define the MvvmCross App class and would initialize other required setup. I suggest you to start with a simple tutorial or to look into the official sample projects to see what is necessary to make MvvmCross work in a Xamarin.Android app.

Error: No matching constructor found on type

I have a WPF application where I am using multiple forms. There is one main form which gets opened when we start the application which is know as MainWindow.xaml. This form then have multiple forms which gets opened depending on the user option. There is a form StartClassWindow.xaml. Currently I am working on this form so I want it to start directly instead of MainWindow.xaml. So to do this I changed the app.xaml startupuri:
<Application x:Class="Class.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DispatcherUnhandledException="Application_DispatcherUnhandledException"
StartupUri="StartClassWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
But then it started giving error like below:
No matching constructor found on type 'Class.StartClassWindow'. You
can use the Arguments or FactoryMethod directives to construct this
type.' Line number '3' and line position '9'.
Here is the StartClassWindow.xaml.cs:
namespace Class
{
public partial class StartClassWindow : System.Windows.Window
{
public StartClassWindow(string classData)
{
InitializeComponent();
className = classData;
function();
}
//rest of the code.
}
}
You need to add a parameter-less constructor to your StartClassWindow like this:
public StartClassWindow(string classData)
{
InitializeComponent();
className = classData;
function();
}
public StartClassWindow()
{
}
Or if you don't want to have another constructor you can override the OnStartup method in the App.xaml.cs but you should remove the StartupUri="StartClassWindow.xaml" in your App.xaml first. Like below:
protected override void OnStartup(StartupEventArgs e)
{
StartClassWindow st = new StartClassWindow("");
st.Show();
}
"Normally", your constructor must be parameterless:
public Login()
But, since you are using dependency injection, like this:
public Login(IUserService userService)
The constructor isn't parameterless, and the framework cannot instantiate the page if it's not told how to.
For this there are a couple of options:
Remove service from constructor
Just like this, but you'll need to access the userservice differently:
public Login()
pre .net 4.8, 4.7, using Unity (or Prism)
You can use a dependency injection framework like Unity to register the components.
It is described here:
https://www.wpftutorial.net/ReferenceArchitecture.html
public class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IUserService, UserService>();
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}
Manual using Navigation Service
Manually navigate, and do your own construction:
NavigationService.Navigate(new LoginPage(new UserService);
As described here: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/navigation-overview?view=netframeworkdesktop-4.8
.net 5 WPF, using built in DI
If you are using .net 5, here is a tutorial. Make sure to register both the window and the service:
https://executecommands.com/dependency-injection-in-wpf-net-core-csharp/
Here's an example:
private void ConfigureServices(ServiceCollection services)
{
services.AddScoped<IUserService,UserService>();
services.AddSingleton<MainWindow>();
}
private void OnStartup(object sender, StartupEventArgs e)
{
var mainWindow = serviceProvider.GetService<MainWindow>();
mainWindow.Show();
}

MonoTouch.Foundation.MonoTouchException has been thrown Objective-C exception thrown. Name: NSInternalInconsistencyException

I seem to be getting this issue whenever I run my iOS app within Xamarin.
MonoTouch.Foundation.MonoTouchException has been thrown
Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Could not load NIB in bundle: ’NSBundle ... (loaded)' with name ‘RouteMeViewController'
I am trying to replace a GoogleMapsViewController with a RouteMeViewController using the Objective C library and Binder in an app that I was given to work on. My AppDelegate looks like this:
namespace ExampleApp.iOS
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
UIWindow window;
RouteMeViewController viewController;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
viewController = new RouteMeViewController ();
window.RootViewController = viewController;
window.MakeKeyAndVisible ();
return true;
}
}
RouteMeViewController
namespace ExampleApp.iOS
{
public partial class RouteMeViewController : UIViewController
{
RMMapView MapView { get; set; }
public RouteMeViewController () : base ("RouteMeViewController", null)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
MapView = new RMMapView(View.Frame, new RMOpenStreetMapSource().Handle);
MapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
if (UIScreen.MainScreen.Scale > 1.0)
MapView.AdjustTilesForRetinaDisplay = true;
Add (MapView);
}
}
}
Any help or direction is much appreciated, thank you!
It seems you're missing a designer file in the resources of your solution. Even if you programmatically create controls and views, you need a designer file where they need to be drawn in, even if it's just an empty designer file. For IOS, you can use XCode for that. You can create files with the .xib extension. They will be compiled on your device, and the resulting file has the extension .nib. Make sure the target of the .xib file is the correct viewController of your project, else you'll still get the error.
I hope this helps. Good luck!
It is 2023 and this problem still appease for xamarion.IOS
and working fine for xamarion.Android
I'm using the last xamarin forms version 5.0.0.2545
this answer solves my problem
I put a lot of codes after InitializeComponent();
to solve the problem just put MainPage = new MainPage(); directly after InitializeComponent(); in your App.xaml.cs
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
The problem now it will directly go to the page without reading the other codes
so to solve this move your code to another page,empty page or splash screen page and put your code in it like
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MySplashScreenPage());
}

WinRT 8.1 settings in Caliburn.Micro

I'm trying to open a settings view in a Caliburn.Micro WinRT 8.1 app using VS2013 RC, but I keep getting an unhandled exception when opening it with the following message:
Value cannot be null. Parameter name: Could not parse the VisualElements from the app manifest.
I can reproduce the issues with the following steps:
create a new Windows Store app from VS2013 RC using the Blank app template.
add Caliburn.Micro via NuGet.
in App.xaml, change the base class to caliburn:CaliburnApplication (the namespace is declared as xmlns:caliburn="using:Caliburn.Micro").
in App.xaml.cs, change the class like this (for the CM-based settings I follow http://compiledexperience.com/blog/posts/settings-caliburn)
Code below:
public sealed partial class App
{
private WinRTContainer _container;
public App()
{
InitializeComponent();
}
protected override void Configure()
{
_container = new WinRTContainer();
_container.RegisterWinRTServices();
_container.PerRequest<MainViewModel>();
_container.PerRequest<SettingsViewModel>();
ISettingsService settings = _container.RegisterSettingsService();
settings.RegisterCommand<SettingsViewModel>("Test settings");
}
protected override object GetInstance(Type service, string key)
{
var instance = _container.GetInstance(service, key);
if (instance != null) return instance;
throw new Exception("Could not locate any instances.");
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
protected override void PrepareViewFirst(Frame rootFrame)
{
_container.RegisterNavigationService(rootFrame);
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
DisplayRootView<MainView>();
}
}
Finally, create folders for Views and ViewModels in the solution add add to them the required items: MainViewModel, SettingsViewModel, MainView, SettingsView. The views just include a TextBlock with some text. MainViewModel derives from Screen, while SettingsViewModel derives from PropertyChangedBase. There is no relevant code in any of them.
When launching the app, I can see the main view; then I open the charms bar and click settings, and I find the label leading to my app settings; when I click it, I get the exception quoted above. Any hint?
You can find a full repro solution here: http://sdrv.ms/18GIMvB .
If you aren't ready to move to the alpha version of CM, you can update Callisto to 1.4.0 via NuGet. That fixed the error for me.
It seems that the new CM release (alpha 2) fixed the issue, so I'm adding some more information here to help other newcomers like me. Here is what I'm doing now:
In app's Configure I have some bootstrap code like:
...
ResourceLoader loader = ResourceLoader.GetForViewIndependentUse("Resources");
ISettingsService settings = _container.RegisterSettingsService();
settings.RegisterFlyoutCommand<ContentSettingsViewModel>(loader.GetString("SettingsContent"));
The ContentSettingsViewModel is a viewmodel for filtering some contents. The string got from resources is the label which will appear in the settings flyout (be sure there is an entry for this string, as passing an empty or null string triggers an exception). This VM is derived from CM Screen as I'm overriding OnActivate and OnDeactivate to load and save settings when the user opens or dismisses the settings page.

Categories

Resources