How to configure xUnit Mock for Prism Application? - xamarin.forms

I am new to xUnit and with the help of Prism Template Studio I created new Prism xUnit test project, which by default created one PrismAppMock.cs file as below:
// This should implement your application class -- What does it means?
public class PrismAppMock : PrismApplicationBase
{
public PrismAppMock(IPlatformInitializer initializer)
: base(initializer)
{
}
protected override IContainerExtension CreateContainerExtension()
{
return null;
}
protected override void OnInitialized()
{
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
On running the test it is throwing null exception as container is not resolved.
I tried to use UnityContainerExtension but as it is abstract class I can't use it directly.
protected override IContainerExtension CreateContainerExtension()
{
return new UnityContainerExtension();
}
Can anybody suggest on how to initialise PrismAppMock for unit testing.

Related

Find when a page finished loading in xamarin.forms prism

I am trying to create an optimized Event Tracker for my Xamarin.forms prism application. I would like to know whether there is any method to find out when the page load is finished. If someone could help me, please save my time.
You can implement page loading methods for different platforms through custom renderer.
For iOS, override the viewDidLoad method, ViewDidLoad(Called after the controller's view is loaded into memory.)
[assembly:ExportRenderer (typeof(ContentPage), typeof(MyRenderer))]
namespace Demo.iOS
{
public class MyRenderer : PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
}
}
}
For Android, rewrite the OnAttachedToWindow method, OnAttachedToWindow(This is called when the view is attached to a window.)
[assembly: ExportRenderer(typeof(ContentPage), typeof(MyRenderer))]
namespace Demo.Droid
{
public class MyRenderer : PageRenderer
{
public MyPageRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
}
}
}

Custom MapBox Android Renderer - crash when change tabs

I am trying to create a MapBox Renderer for Android in Xamarin Forms using the naxam library.
The map is displaying well as a content of a view in a tab, however when I change tab several times it crashes on the android emulator. I suppose the problem comes from the renderer but can't figure out where.
Here is a part of my code :
public class MapViewRenderer : ViewRenderer<ContentView, Android.Views.View>,
IOnMapReadyCallback, Com.Mapbox.Mapboxsdk.Maps.Style.IOnStyleLoaded
{
private MapView _mapView = null;
private MapboxMap _mapBox = null;
public MapViewRenderer(Context context) : base(context)
{
Mapbox.GetInstance(Context, "pk.###");
}
public void OnMapReady(MapboxMap p0)
{
_mapBox = p0;
[...]
}
public void OnStyleLoaded(Com.Mapbox.Mapboxsdk.Maps.Style p0)
{
[...]
}
protected override void OnElementChanged(ElementChangedEventArgs<ContentView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
_mapView = new MapView(Context);
_mapView.GetMapAsync(this);
view.Content = _mapView.ToView();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_mapView.Dispose();
}
base.Dispose(disposing);
}
}
All the examples I read on the net are about creating the MapView in the main activity with OnCreate, OnStart, OnResume... I haven't found any about creating a map in a custom render.
Please help.
EDIT :
---------------------------------SOLUTION---------------------------------
The problem was fixed using the code below in the custom renderer. In addition the renderer uses a Mapview instance which has been moved inside the main activity following ToolmakerSteve's remark.
MapViewRenderer.cs :
public class MapViewRenderer : ViewRenderer<ContentView, Android.Views.View>
{
public MapViewRenderer(Context context) : base(context)
{}
protected override void OnElementChanged(ElementChangedEventArgs<ContentView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var view = e.NewElement as Views.Map;
if (Control == null)
{
SetNativeControl(MainActivity.MainActivityInstance.MapView);
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
MainActivity.MainActivityInstance.MapView.RemoveFromParent();
}
base.Dispose(disposing);
}
}
MainActivity.cs :
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IOnMapReadyCallback, Style.IOnStyleLoaded
{
public MapView MapView { get; private set; } = null;
public MapboxMap MapboxMap { get; private set; } = null;
public static MainActivity MainActivityInstance { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
[...]
MainActivityInstance = this;
Mapbox.GetInstance(this, "pk.###");
MapView = new MapView(this);
MapView.GetMapAsync(this);
MapView.OnCreate(savedInstanceState);
}
protected override void OnStart()
{
base.OnStart();
MapView.OnStart();
[...]
}
protected override void OnResume()
{
base.OnResume();
MapView.OnResume();
}
protected override void OnPause()
{
MapView.OnPause();
base.OnPause();
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
MapView.OnSaveInstanceState(outState);
}
protected override void OnStop()
{
base.OnStop();
MapView.OnStop();
}
protected override void OnDestroy()
{
MapView.OnDestroy();
base.OnDestroy();
}
public override void OnLowMemory()
{
base.OnLowMemory();
MapView.OnLowMemory();
}
public void OnMapReady(MapboxMap p0)
{
MapboxMap = p0;
[...]
}
public void OnStyleLoaded(Com.Mapbox.Mapboxsdk.Maps.Style p0)
{
[...]
}
}
Wrap the contents of each method in try-catch, and write to Debug output any exception (hopefully instead of crashing).
You will probably need to find out exactly what causes the crash, for anyone to help you.
Do this by adding Debug.WriteLine statements throughout the custom renderer.
I also recommend verifying that it really is the custom renderer that causes the problem.
Do this by commenting out most of the custom code. So that it displays as an empty view.
You need to add code to the MainActivity methods. This won't fix this crash, but it will avoid crashing later, for example when app goes into background.
Naxam library install guide says:
The MapView contains its own lifecycle methods for managing Android's OpenGL lifecycle, which must be called directly from the containing Activity. In order for your app to correctly call the MapView's lifecycle methods, you must override the following lifecycle methods in the Activity that contains the MapView and call the respective MapView method.
Android code from that link:
// Set this from your custom renderer.
public MapView mapView;
override fun onStart() {
super.onStart()
mapView?.onStart()
}
override fun onStop() {
super.onStop()
mapView?.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView?.onDestroy()
}
Translate that into C# equivalent.
In your custom renderer, set the activities mapView variable:
Xamarin Essentials.Platform.CurrentActivity.mapView = ...;
You should also set that variable to null:
in OnElementChanged / e.newElement == null
in Dispose.
In my experience, on Android, OpenGL views don't like to be hidden - which is what happens when switching to different tab. (MapBox uses an OpenGL view.)
Unfortunately the result is a "hard crash" - won't be caught by try/catch. Won't give useful information about why it crashed.
If this is the cause, none of the above will fix the problem.
You might have to do custom logic that disposes the map when the tab is hidden, recreates it when the tab comes back.
See https://stackoverflow.com/a/52186885/199364, for the event you need to add code to.

Can't find method Shiny.IShinyStartup.ConfigureServices with Prism 8

The error I'm getting during app startup is the following:
Parent class vtable failed to initialize, due to: Could not load list of method overrides due to Method not found: void Shiny.IShinyStartup.ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection) assembly:/Users/merickson/Library/Developer/CoreSimulator/Devices/D19E269D-A3E5-46C2-BB9C-94A122EA02DC/data/Containers/Bundle/Application/F9A34529-8F64-4868-8D7F-389C77DB54BC/PrismSizeTest.iOS.app/Shiny.Prism.dll type:PrismStartup member:(null)
I'm not sure if I'm missing a NuGet, maybe wrong version of one or more NuGets, or am I initializing something wrong? Any help is appreciated.
I've been able to replicate this with a bare bones solution which I can provide if necessary. Here are the main files involved:
App.xaml.cs
public partial class App : PrismApplicationBase
{
public App(IPlatformInitializer initializer)
: base(initializer)
{
}
protected override async void OnInitialized()
{
InitializeComponent();
await NavigationService.NavigateAsync("NavigationPage/MainPage");
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
}
protected override IContainerExtension CreateContainerExtension() => ContainerLocator.Current;
}
AppDelegate.cs
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
ShinyHost.Init(new ApplePlatform(), new MyStartup());
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App(new iOSInitializer()));
return base.FinishedLaunching(app, options);
}
}
public class iOSInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
// Register any platform specific implementations
}
}
MyStartup.cs
public class MyStartup : PrismStartup
{
protected override void ConfigureServices(IServiceCollection services)
{
services.UseGps<GpsDelegate>();
}
}
NuGets installed:
There is nothing directly wrong with the code... however the latest versions of Shiny have breaking ABI changes that make Shiny.Prism and Shiny.Core incompatible which is the result of the issue shown here...
For more information you can track the issue at: https://github.com/dansiegel/Prism.Container.Extensions/issues/183

Xamarin Forms:Prism MVVM:Android:Navigate to specific page when click on Push Notification [duplicate]

I'm new to Xamarin and Prism, so forgive me if I'm missing something obvious. I am following the example of this project in GitHub. However, I am getting the following error when running my Android project.
System.InvalidOperationException: The current type, MyApp.Abstractions.IFacebookManager, is an interface and cannot be constructed. Are you missing a type mapping?
The error is occurring in EntryPage.xaml.g.cs in the LoadFromXaml() method.
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("Views\\EntryPage.xaml")]
public partial class EntryPage : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
// Exception thrown here!
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(EntryPage));
}
}
This leads me to believe that I'm not using the IoC container properly, but I can't see what I'm doing differently from the example. The EntryPageViewModel's constructor takes IFacebookManager as a parameter and I understand that Unity should take care of this. I have a breakpoint on the constructor, but it's not being hit. This is a .NET Standard Xamarin solution. I would appreciate any help and guidance. Thank you!
Here's my App.xaml.cs
using MyApp.Abstractions;
using MyApp.Helpers;
using MyApp.Services;
using MyApp.ViewModels;
using MyApp.Views;
using Prism;
using Prism.Ioc;
using Prism.Unity;
using Xamarin.Forms;
namespace MyApp
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
ServiceResolver.Instance.Add<ICloudService, AzureCloudService>();
NavigationService.NavigateAsync("NavigationPage/EntryPage");
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<EntryPage, EntryPageViewModel>();
}
}
}
Here's my MainActivity.cs
using Android.App;
using Android.Content.PM;
using Android.OS;
using MyApp.Droid.Services;
using MyApp.Abstractions;
using Android.Content;
using Xamarin.Facebook;
using Xamarin.Forms;
using Prism;
using Prism.Ioc;
namespace MyApp.Droid
{
[Activity(Label = "MyApp", Icon = "#drawable/icon", Theme = "#style/MainTheme", Name = "com.mydomain.myapp.MainActivity", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
ICallbackManager fbCallbackManager;
AndroidLoginProvider loginProvider;
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
global::Xamarin.Forms.Forms.Init(this, bundle);
DependencyService.Register<IFacebookManager, FacebookManager>();
LoadApplication(new App(new AndroidInitializer()));
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
var manager = DependencyService.Get<IFacebookManager>();
if (manager != null)
{
(manager as FacebookManager)._callbackManager.OnActivityResult(requestCode, (int)resultCode, data);
}
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
You are mixing the Xamarin Forms Dependency Service with the one provided with Prism.Unity
Instead of calling DependencyService.Register<IFacebookManager, FacebookManager>();
You need to register it with the AndroidInitializer .
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry container)
{
container.RegisterSingleton<IFacebookManager, FacebookManager>();
}
}
You can then always resolve a dependency manually by calling App.Container.Resolve inside OnActivityResult.
To complete the previous answer that helped me a lot to fix a similar issue:
with prism 7, you need to resolve a dependency via IContainerProvider as follow:
var container = (App.Current as Prism.Unity.PrismApplication).Container;
var manager = container.Resolve<IFacebookManager>();
In this case, Unity is used as the IoC "container"

Unity injection into asp.net web api controllers and filters

I have WebForms project, and there I have WebApi controller.
How I can inject to controller constructor and to action filter constructor?
I have implemented IDependencyResolver and use it in Global.asax (GlobalConfiguration.Configuration.DependencyResolver), but it doesn't help:
on request controller says that there is no default constructor and filter on application start says that it does not contain a constructor that takes 0 arguments.
Moreover, i need singletone injection to action filter.
Thanks.
UPD
public class ScopeContainer : IDependencyScope
{
protected readonly IUnityContainer _container;
public ScopeContainer(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.IsRegistered(serviceType) ? _container.ResolveAll(serviceType) : new List<object>();
}
public void Dispose()
{
_container.Dispose();
}
}
public class IoCContainer : ScopeContainer, IDependencyResolver
{
public IoCContainer(IUnityContainer container) : base(container)
{
}
public IDependencyScope BeginScope()
{
var child = _container.CreateChildContainer();
return new ScopeContainer(child);
}
}
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
ConfigureApi(GlobalConfiguration.Configuration);
}
void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterInstance<ILogger>(new Logger());
unity.RegisterType<IRepository, DbRepository>();
config.DependencyResolver = new IoCContainer(unity);
}
private static void RegisterRoutes()
{
RouteTable.Routes.MapHttpRoute("ServiceApi", "api/{controller}/{action}");
}
}
I think this may be the way you are registering your routes.
WebApi routes are registered in the default project examples via the GlobalConfiguration.Routes rather than the RouteTable.Routes which is used by MVC controllers. If the ApiController is being incorrectly loaded by the MVC routing method it won't find your dependency resolver.
Try modifying your code to this:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(GlobalConfiguration.Configuration);
ConfigureApi(GlobalConfiguration.Configuration);
}
void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterInstance<ILogger>(new Logger());
unity.RegisterType<IRepository, DbRepository>();
config.DependencyResolver = new IoCContainer(unity);
}
private static void RegisterRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute("ServiceApi", "api/{controller}/{action}");
}
}
I was having the same issue, I was working on a project trying to help modernize an old web forms project by converting page by page to Web API / Angular and getting the plumbing just right to use Unity was key.
When I was tracing I noticed unity was trying to resolve the controller classes but not the types to inject into their constructors, so I registered my controllers and it all worked. See my example below
Config setup, register controller and dependency
void ConfigureApi(HttpConfiguration config)
{
var container = UnitySingleton.UnityContainer;
container.RegisterType<IDashboardManager, ExampleStuff>();
container.RegisterType<DashboardController>(new InjectionConstructor(container.Resolve<IDashboardManager>()));
config.DependencyResolver = new UnityIoCContainer(container);
}
And my controller example:
public class DashboardController : ApiController
{
private readonly IDashboardManager _dashboardManager;
public DashboardController(IDashboardManager dashboardManager)
{
_dashboardManager = dashboardManager;
}
public async Task<IEnumerable<string>> Get()
{
return await _dashboardManager.GetDatas();
}
}
This is how I got mine working. It was a little different than the article above.

Resources