Error when opening solution in second computer - c#

I have a Visual Studio project in Dropbox, I have been working on this project from two different computers (NOT at the same time) but for some reason, it just stopped working on one computer, I can open it in one but when I try to open it from the other computer I see an error.
FYI - One computer is running Windows 7 and the Other one is running Windows 10 but both are running Visual Studio 2015. Also, I'm using MVVM Light in this solution.
Error:
TypeInitializationException was unhandled by user code
An exception of type 'System.TypeInitializationException' occurred in MyApp.exe but was not handled in user code
Additional information: The type initializer for 'MyApp.ViewModel.MainViewModel' threw an exception.
I tried cleaning the solution but nothing, no luck.
Any idea why it would stop working on one computer but not the other if it's the same solution?
EDIT: Added code.
namespace MyApp.ViewModel
{
public class ViewModelLocator
{
private static MainViewModel _main;
public ViewModelLocator()
{
_main = new MainViewModel();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return _main;
}
}
public static void Cleanup()
{
}
}
}
Constructor fo MainViewModel
public MainViewModel()
{
CurrentViewModel = MainViewModel._findrViewModel;
FindrViewCommand = new RelayCommand(() => ExecuteFindrViewCommand());
CalculatorViewCommand = new RelayCommand(() => ExecuteCalculatorViewCommand());
ProductionTimesViewCommand = new RelayCommand(() => ExecuteProductionTimesViewCommand());
}

Related

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

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);

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.

Why are my plugin-types only being registered partially in this case?

I am trying to implement a plugin architecture for our WPF program following the proposed implementation here. I want my plugins to reside in a separate folder from the main program folder. I have gotten it to only partially work. Here is the code:
The plan is for each plugin to provide its own StructureMap registry to override the default StructureMap regstry.
The plugin I am currently working on has the following registry and as you can see, I am overriding the registry for the plugin-type IPrintProgramExecutor to intercept and use AutomationController instead. And it works as expected:
public class PluginRegistry : Registry
{
public PluginRegistry()
{
this.ForConcreteType<AutomationController>()
.Configure
.Ctor<IPrintProgramExecutor>().Is(c=> c.GetInstance<PrintProgramExecutor>())
.Singleton();
this.For<IAutomationController>().Use(c => c.GetInstance<AutomationController>()).Singleton();
this.For<IPrintProgramExecutor>().Use(c => c.GetInstance<IAutomationController>()).Singleton();
//this.ForConcreteType<AutomationPlugin>()
// .Configure
// .Singleton();
this.For<IPluginBase>().Use<AutomationPlugin>();
}
}
AutomationPlugin currently is this stub:
public class AutomationPlugin : IPluginBase
{
public ViewModelBase ViewModel {
get { return viewModel; }
private set { viewModel = value; }
}
public ResourceDictionary View { get; }
private ViewModelBase viewModel { get; set; }
private ResourceDictionary viewDictionary = new ResourceDictionary();
public AutomationPlugin()
{
// do something meaningfull!
}
}
with IPluginBase:
public interface IPluginBase
{
ViewModelBase ViewModel { get; }
ResourceDictionary View { get; }
}
The class to add the registry is this, where pluginPath is the path to the extension folder:
public class PluginRegistryAdder : Registry
{
public PluginRegistryAdder(string pluginPath)
{
Scan( x =>
{
x.AssembliesFromPath(pluginPath);
x.LookForRegistries();
});
}
}
The class to actually tie in the plugin registry using the code above is this:
public static class ExtensionManager
{
public static void RegisterPluginsInDic(string pluginPath, IContainer container)
{
var pluginRegistries = new PluginRegistryAdder(pluginPath);
container.Configure(_ => _.IncludeRegistry(pluginRegistries));
var whatIHave = container.WhatDoIHave(typeof(IPluginBase));
var plugins = container.Model.GetAllPossible<IPluginBase>(); // the IEnumerable plugins is empty although I am registering `AutomationPlugin` for it. Why?!
}
}
Now, as mentioned above, the interception for the plugin-type IPrintProgramExecutor works as expected. But for some reason container.Model.GetAllPossible<IPluginBase>() and container.WhatDoIHave(typeof(IPluginBase)) do not find any registered types for the plugin-type IPluginBase. I have tried calling these methods for IPrintProgramExecutor and surely enough they return the concrete type. I have been looking quite a while for the reason and cannot find it.
Any ideas why? Could it have to do with the fact, that I am calling container.Configure(...) twice and perhaps the fact that I already register something for IPringProgramExecutor the first time I call container.Configure(...)? Help is greatly appreciated!
Updates:
After switching to my laptop, the interception, that previously worked, does not work anymore. Furthermore, I am now getting an exception, that one of the assemblies I am trying to register in PluginRegistry is not found:
StructureMap.StructureMapException: Unable to create an instance for Registry type 'Extensions.Automation.PluginRegistry'. Please check the inner exception for details
---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Automation.Servers.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
at Extensions.Automation.PluginRegistry..ctor()
...
All in all, it seems like a path-problem that I cannot figure out. I suspect, that at run-time the program attempts to load the DLLs in the Plugin-registry from the main path, but the corresponding DLLs/asseblies reside in the Extension-folder. How can I see from where StructureMap attempts to load the assembly Automation.Servers.Interfaces for debugging? Hope somebody can help me out. I am slowly loosing it.
You should be able to see where StructureMap is trying to probe for assemblies with the type scanning diagnostics: http://structuremap.github.io/diagnostics/type-scanning/
You do have the ability to specify the folder instead of relying on the AppDomain/AppContext.

Template10 NavigationService is null

This is my App.xaml.cs
[Bindable]
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
SplashFactory = (e) => new Views.Splash(e);
var _settings = SettingsService.Instance;
RequestedTheme = _settings.AppTheme;
CacheMaxDuration = _settings.CacheMaxDuration;
ShowShellBackButton = _settings.UseShellBackButton;
}
public override async Task OnInitializeAsync(IActivatedEventArgs args)
{
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
var statusBar = StatusBar.GetForCurrentView();
await statusBar.HideAsync();
}
await Task.CompletedTask;
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage)); // Exception here
await Task.CompletedTask;
}
}
Every time i launch the app i get this exception:
System.NullReferenceException verificata
HResult=-2147467261
Message=Object reference not set to an instance of an object.
NavigationService is always null.
How can I solve this?
I had the same issue when I updated the Target min version of the project to Fall Creators Update (see project properties).
After reading this thread I fixed the issue by updating the Newtonsoft.Json Nuget dependency from version 11.x.x to 10.0.3.
So just to be clear I downgraded the version of the Newtonsoft.Json Nuget dependency.
I have had similar issue, but inside of ViewModel not in App.xaml.cs.
So NavigationService was null when I defined and initialized my ViewModel as property in code behind of view.
Solution is to define ViewModel in xaml (<Page.DataContext>) then everything works like a charm.
For anyone coming back to this, I run across issue and realized that if I kept the minimum version of the project 10586 the problem goes away.

StructureMap working locally, but not on production server

I developing a MVC5 application, where I am using StructureMap as my DI framework. The application works fine, when I run it locally from Visual Studio. However when I publish to our production server, I get the "No parameterless constructor..." error. I've Googled a solution and found a suggestion to add the code below to an empty constructor in the controller, in order to get a more detailed exception:
public class HomeController : Controller
{
public HomeController()
{
_bll = StructureMap.ObjectFactory.GetInstance<IAgentStatsBll>();
}
private IAgentStatsBll _bll;
public HomeController(IAgentStatsBll bll)
{
_bll = bll;
}
public ActionResult Index()
{
HomeViewModel model = new HomeViewModel {Authors = _bll.GetAuthorsWithCommentsOnDate(DateTime.Now.AddDays(-60))};
return View(model);
}
}
When I run this code on the production server, I get an error saying:
No default Instance is registered and cannot be automatically determined for type 'ZendeskAgentStats.BLL.IAgentStatsBll'.
There is no configuration specified for ZendeskAgentStats.BLL.IAgentStatsBll
If I understand the error correct, it says that SM cannot figure out which concrete type it should use for the IAgentStatsBll interface. However this is configured in the DefaultRegistry.cs:
public class DefaultRegistry : Registry {
#region Constructors and Destructors
public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
scan.AssemblyContainingType<IAgentStatsBll>();
scan.AssemblyContainingType<IAgentStatsDal>();
scan.AssemblyContainingType<IAgentStatsContext>();
scan.AssemblyContainingType<ZendeskAPIMethods>();
scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});
For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>));
}
#endregion
}
Can anyone figure out why it is working locally but not on the server?

Categories

Resources