Getting could not create an native instance of the type 'JumioNetverifyBinding.NetverifyConfiguration' the native class hasn't been loaded exception - objective-c

I am trying to bind Jumio Natverify library in Xamarin iOS project by creating Objective c library project.
I have crated ApiDefination.cs and Struct.cs file data using sharpie tool. But when I am trying on run it I am getting Could not create an native instance of the type 'JumioNetverifyBinding.NetverifyConfiguration': the native class hasn't been loaded. exception.
ApiDefinition class - ApiDefinition.cs
Struct class - Struct.cs
Called NetverifyViewController from iOS Binding project:
using Foundation;
using JumioNetverifyBinding;
using System;
using UIKit;
namespace JumioNetverifyDemo
{
public partial class ViewController : UIViewController
{
NetverifyViewController netverifyViewController;
public ViewController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
StartNetverifyButton.TouchUpInside += startNetverify;
}
public void CreateNetverifyController()
{
NetverifyConfiguration config = new NetverifyConfiguration();
config.ApiToken = "My_token_key";
config.ApiSecret = "Secrate_key";
config.DataCenter = JumioDataCenter.Eu;
config.Delegate = new NetverifyViewControllerDelegateHandler(this);
this.netverifyViewController = new NetverifyViewController(config);
}
public void startNetverify(object sender, EventArgs e)
{
this.CreateNetverifyController();
if (this.netverifyViewController != null)
{
this.PresentViewController(netverifyViewController, true, null);
}
else
{
Console.WriteLine("Netverify Mobile SDK : NetverifyViewController is null");
}
}
public void DisplayAlertAsync(string title = "Alert", string message = "")
{
var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(okAlertController, true, null);
}
public class NetverifyViewControllerDelegateHandler : NetverifyViewControllerDelegate
{
private ViewController _viewController;
public NetverifyViewControllerDelegateHandler(ViewController viewController)
{
_viewController = viewController;
}
public override void DidCancelWithError(NetverifyViewController netverifyViewController, NetverifyError error, string scanReference, string accountId)
{
Console.WriteLine("NetverifyViewController did finish initializing, error:" + error.Message);
_viewController.DisplayAlertAsync("Error : " + error.Message);
}
public override void DidFinishWithDocumentData(NetverifyViewController netverifyViewController, NetverifyDocumentData documentData, string scanReference, string accountId, bool authenticationResult)
{
_viewController.DisplayAlertAsync("Scan Reference : " + scanReference);
}
}
}
}
I am looking for anyway to handle this exception and make this library work, if anyone have idea about this? Any help would be appreciated.

Related

How to create multiple custom renderer with same type?

I wanted to create a page render with ContentPage type. I created so in android and it is working but in IOS there has custom page renderer with same type (ContentPage). It can be removed as this was from nuget package and working on different context.
Here is my code
[assembly: ExportRenderer(typeof(ContentPage), typeof(CustomPageRenderer))]
namespace AlwinInvoiceGenerator.IOS
{
using CoreGraphics;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
public class CustomPageRenderer : PageRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (Element == null || !(Element is ContentPage basePage) || basePage.BindingContext == null ||
!(basePage.BindingContext is BaseViewModel baseViewModel))
{
return;
}
SetCustomBackButton(baseViewModel);
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
OverrideUserInterfaceStyle = UIUserInterfaceStyle.Light;
}
private void SetCustomBackButton(BaseViewModel baseViewModel)
{
var fakeButton = new UIButton {Frame = new CGRect(0, 0, 50, 40), BackgroundColor = UIColor.Clear};
fakeButton.TouchDown += (sender, e) =>
{
baseViewModel.OnBackButtonClicked();
};
NavigationController?.NavigationBar.AddSubview(fakeButton);
}
}
It seems it not registering and that is why not calling.
I have another page renderer that is register in assembly
[assembly: ExportRenderer(typeof(ContentPage), typeof(IOSToolbarExtensions.iOS.Renderers.IOSToolbarExtensionsContentPageRenderer), Priority = short.MaxValue)]
If I removed this line then above code is working but not two in the same time.
Please help
Same type seems not working for multiple renderer.
I have created sub type of my custom renderer and override the methods which needed to. It is working well

Save and displaying high score with variable across classes unity

I need to get the variable score from my other class and set it as a UserPrefs key. it doesnt seem to be setting as i have a GUI label ingame which shos "None" if there is no UserPrefs key "Highscore".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class Player : MonoBehaviour {
public Vector2 jumpForce = new Vector2(0, 300);
private Rigidbody2D rb2d;
Generator SwagScript;
GameObject generator;
// Use this for initialization
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
generator = GameObject.FindGameObjectWithTag("Generator");
SwagScript = generator.GetComponent<Generator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp("space"))
{
rb2d.velocity = Vector2.zero;
rb2d.AddForce(jumpForce);
}
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die();
}
}
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
void Die()
{
if (PlayerPrefs.HasKey("HighScore"))
{
if (PlayerPrefs.GetInt("Highscore") < SwagScript.score)
{
PlayerPrefs.SetInt("HighScore", SwagScript.score);
}
else
{
PlayerPrefs.SetInt("HighScore", SwagScript.score);
}
}
Application.LoadLevel(Application.loadedLevel);
}
}
Unless you're creating the Highscore playerpref somewhere else, the Die() method won't never create it, since the if (PlayerPrefs.HasKey("HighScore")) will always return false.
Just remove that if.

Ideablade's Cocktail Composition Container for WCF projects

I recently upgraded an application I am working on from Cocktail 1.4 to Cocktail 2.6 (Punch). I have adjusted my bootstrapper class for the wpf project which now loads with no issues. However, on my WCF / Web projects, I am receiving a runtime exception with the following error when attempting to call Composition.GetInstance:
"You must first set a valid CompositionProvider by using Composition.SetProvider."
After digging into the issue a bit, it appears the composition container is automatically configured when your bootstrapper inherits from CocktailMefBootstrapper. I currently do not have bootstrapper classes at all for non-wpf projects. Prior to the upgrade, all I had to do was call the configure method on the Composition class to configure the composition container, but it appears that it has been deprecated:
Composition.Configure();
I noticed that you can also call Composition.SetProvider(), however I am a little unsure on how to satisfy the method signature exactly. The DevForce Punch documentation states that the generic type for the bootstrapper class should be a viewmodel, and there are no views / view models in a service project. This leaves me in limbo on what to do as I don't want to rip cocktail out of these WCF projects. Is there still a way to use Cocktail's composition container without a bootstrapper for a project in Cocktail (Punch) 2.6?
UPDATE
I found this on the DevForce forums. So it appears that I ought to learn how to configure a multi threaded ICompositionProvider and call Composition.SetProvider() as mentioned above. Any recommended articles to achieving this?
After digging through Punch's source code and looking at Ideablade's MefCompositionContainer, which implements ICompositionProvider, I created my own thread safe implementation of ICompositionProvider. Below is the code I used. Basically, it's the same code for Ideablade's MefCompositionContainer which can be found here in their repository. The only change is that I am passing a bool flag of true into the CompositionContainer's constructor. MSDN lists the pros and cons of making the container thread safe
internal partial class ThreadSafeCompositionProvider : ICompositionProvider
{
static ThreadSafeCompositionProvider()
{
CompositionHost.IgnorePatterns.Add("Caliburn.Micro*");
CompositionHost.IgnorePatterns.Add("Windows.UI.Interactivity*");
CompositionHost.IgnorePatterns.Add("Cocktail.Utils*");
CompositionHost.IgnorePatterns.Add("Cocktail.Compat*");
CompositionHost.IgnorePatterns.Add("Cocktail.dll");
CompositionHost.IgnorePatterns.Add("Cocktail.SL.dll");
CompositionHost.IgnorePatterns.Add("Cocktail.WinRT.dll");
}
public IEnumerable<Assembly> GetProbeAssemblies()
{
IEnumerable<Assembly> probeAssemblies = CompositionHost.Instance.ProbeAssemblies;
var t = GetType();
// Add Cocktail assembly
probeAssemblies = probeAssemblies.Concat(GetType().GetAssembly());
return probeAssemblies.Distinct(x => x);
}
private List<Assembly> _probeAssemblies;
private AggregateCatalog _defaultCatalog;
private ComposablePartCatalog _catalog;
private CompositionContainer _container;
public ComposablePartCatalog Catalog
{
get { return _catalog ?? DefaultCatalog; }
}
public ComposablePartCatalog DefaultCatalog
{
get
{
if (_defaultCatalog == null)
{
_probeAssemblies = GetProbeAssemblies().ToList();
var mainCatalog = new AggregateCatalog(_probeAssemblies.Select(x => new AssemblyCatalog(x)));
_defaultCatalog = new AggregateCatalog(mainCatalog);
CompositionHost.Recomposed += new EventHandler<RecomposedEventArgs>(OnRecomposed)
.MakeWeak(x => CompositionHost.Recomposed -= x);
}
return _defaultCatalog;
}
}
internal void OnRecomposed(object sender, RecomposedEventArgs args)
{
if (args.HasError) return;
var newAssemblies = GetProbeAssemblies()
.Where(x => !_probeAssemblies.Contains(x))
.ToList();
if (newAssemblies.Any())
{
var catalog = new AggregateCatalog(newAssemblies.Select(x => new AssemblyCatalog(x)));
_defaultCatalog.Catalogs.Add(catalog);
_probeAssemblies.AddRange(newAssemblies);
}
// Notify clients of the recomposition
var handlers = Recomposed;
if (handlers != null)
handlers(sender, args);
}
public CompositionContainer Container
{
get { return _container ?? (_container = new CompositionContainer(Catalog, true)); }
}
public Lazy<T> GetInstance<T>() where T : class
{
var exports = GetExportsCore(typeof(T), null).ToList();
if (!exports.Any())
throw new Exception(string.Format("Could Not Locate Any Instances Of Contract", typeof(T).FullName));
return new Lazy<T>(() => (T)exports.First().Value);
}
public T TryGetInstance<T>() where T : class
{
if (!IsTypeRegistered<T>())
return null;
return GetInstance<T>().Value;
}
public IEnumerable<T> GetInstances<T>() where T : class
{
var exports = GetExportsCore(typeof(T), null);
return exports.Select(x => (T)x.Value);
}
public Lazy<object> GetInstance(Type serviceType, string contractName)
{
var exports = GetExportsCore(serviceType, contractName).ToList();
if (!exports.Any())
throw new Exception(string.Format("Could Not Locate Any Instances Of Contract",
serviceType != null ? serviceType.ToString() : contractName));
return new Lazy<object>(() => exports.First().Value);
}
public object TryGetInstance(Type serviceType, string contractName)
{
var exports = GetExportsCore(serviceType, contractName).ToList();
if (!exports.Any())
return null;
return exports.First().Value;
}
public IEnumerable<object> GetInstances(Type serviceType, string contractName)
{
var exports = GetExportsCore(serviceType, contractName);
return exports.Select(x => x.Value);
}
public ICompositionFactory<T> GetInstanceFactory<T>() where T : class
{
var factory = new ThreadSafeCompositionFactory<T>();
Container.SatisfyImportsOnce(factory);
if (factory.ExportFactory == null)
throw new CompositionException(string.Format("No export found.", typeof(T)));
return factory;
}
public ICompositionFactory<T> TryGetInstanceFactory<T>() where T : class
{
var factory = new ThreadSafeCompositionFactory<T>();
Container.SatisfyImportsOnce(factory);
if (factory.ExportFactory == null)
return null;
return factory;
}
public void BuildUp(object instance)
{
// Skip if in design mode.
if (DesignTime.InDesignMode())
return;
Container.SatisfyImportsOnce(instance);
}
public bool IsRecomposing { get; internal set; }
public event EventHandler<RecomposedEventArgs> Recomposed;
internal bool IsTypeRegistered<T>() where T : class
{
return Container.GetExports<T>().Any();
}
public void Configure(CompositionBatch compositionBatch = null, ComposablePartCatalog catalog = null)
{
_catalog = catalog;
var batch = compositionBatch ?? new CompositionBatch();
if (!IsTypeRegistered<IEventAggregator>())
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
Compose(batch);
}
public void Compose(CompositionBatch compositionBatch)
{
if (compositionBatch == null)
throw new ArgumentNullException("compositionBatch");
Container.Compose(compositionBatch);
}
private IEnumerable<Lazy<object>> GetExportsCore(Type serviceType, string key)
{
return Container.GetExports(serviceType, null, key);
}
}
After setting up that class, I added a configuration during startup to instantiate my new thread safe composition provider and to set it as the provider for Punch's Composition class:
if (createThreadSafeCompositionContainer)
{
var threadSafeContainer = new ThreadSafeCompositionProvider();
Composition.SetProvider(threadSafeContainer);
}
Seems to be working like a charm!

AspectJ, Intertype Definition

I am receiving this error when I compile
The type XXX must implement the inherited abstract method
I have three files
A default implementation [com.SafeReaderIMPL.java]
public class SafeReaderIMPL implements ISafeReader {
private boolean successfulRead;
public SafeReaderIMPL() {
successfulRead = true;
}
protected void fail() {
successfulRead = false;
}
#Override
public boolean isSuccessfulRead() {
return successfulRead;
}
}
An interface file [com.ISafeReader.java]
public interface ISafeReader {
public boolean isSuccessfulRead();
}
An apsect (using annotations) [com.SafeReaderAspect.java]
#Aspect
public class SafeReaderAspect {
#DeclareParents(value = "com.BadReader", defaultImpl = SafeReaderIMPL.class)
public ISafeReader implementedInterface;
#AfterThrowing(pointcut = "execution(* *.*(..)) && this(m)", throwing = "e")
public void handleBadRead(JoinPoint joinPoint, ISafeReader m, Throwable e) {
((SafeReaderIMPL)m).fail();
}
}
And a Test Class [com.BadReader]
public class BadReader {
public void fail() throws Throwable {
throw new Throwable();
}
}
I compile the first three files in a separate jar using
ajc -source 1.8 -sourceroots . -outjar aspectLib.jar
I then compile the second file using the aspectLib like so
ajc -source 1.8 -sourceroots . -aspectpath ./aspectLib.jar -outjar common.jar
When I go to compile the second jar I get the error. I am using the latest stable version of AspectJ 1.8.3
BadReader.java:10 [error] The type BadReader must implement the
inherited abstract method ISafeReader.isSuccessfulRead() public class
BadReader {
^^^^^^^^
The problem is not two-step compilation as such, but the fact that #DeclareParents in #AspectJ syntax in not 100% compatible with declare parents in native syntax. Actually, #DeclareParents for introducing default interface implementations is superseded by #DeclareMixin (see this bug ticket), but the downside of the mixin approach is that you do not have a real A implements B scenario there, i.e. you cannot cast as you wish in your after-throwing advice, so this is also not a good option in your case.
So what do you do if you want to keep the two-step compilation approach? Just use native syntax:
Interface:
package com;
public interface ISafeReader {
boolean isSuccessfulRead();
}
Default implementation:
package com;
public class SafeReaderIMPL implements ISafeReader {
private boolean successfulRead;
public SafeReaderIMPL() { successfulRead = true; }
public void fail() { successfulRead = false; }
#Override public boolean isSuccessfulRead() { return successfulRead; }
}
ITD aspect:
package com;
public aspect SafeReaderAspect {
declare parents : com.BadReader implements SafeReaderIMPL;
after(ISafeReader safeReader) throwing : execution(* *(..)) && this(safeReader) {
System.out.println(thisJoinPoint + " - calling 'fail()' before rethrowing error");
((SafeReaderIMPL) safeReader).fail();
}
}
ITD target class with sample main method:
package com;
public class BadReader {
public void doSomething() {
throw new RuntimeException("my error");
}
public static void main(String[] args) {
BadReader badReader = new BadReader();
System.out.println("badReader.isSuccessfulRead() = " + badReader.isSuccessfulRead());
try { badReader.doSomething(); }
catch(Throwable t) { System.out.println(t); }
System.out.println("badReader.isSuccessfulRead() = " + badReader.isSuccessfulRead());
}
}
Now you can use the two-stage compilation approach.
Console output:
badReader.isSuccessfulRead() = true
execution(void com.BadReader.doSomething()) - calling 'fail()' before rethrowing error
java.lang.RuntimeException: my error
badReader.isSuccessfulRead() = false
The problem is due to the two-step compilation. During the second step, ajc needs the source code of SafeReaderIMPL to be able to weave BadReader, but it cannot find it into aspectLib.jar
In fact, if you try compiling in a single step (I did), it compiles and runs.
Unfortunately I don't know a way to fix this without providing the source code during the second compile step, which I suppose would render the whole two-step approach a bit pointless.

Application crashes when launching an event only in MonoTouch 4.0.1

I have an application working under MonoTouch 3.2.6;
the same application, under MonoTouch 4.0.1, crashes when launching any touch event.
Reading another question, at source, I understand that the problem lies in an object collected from the GC, but I can't see which one is. The application starts and loads dinamically the TabBar, but clicking on any TabItem crashes the app. The files main.cs and TabDelegate.cs are listed below: Main.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using IPadApp.Classes;
using AggiornamentiCL;
namespace VSViewer
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
public static UITabBar tabmain ;
public static UIViewController ctrMain;
public static Home ctrHome;
public static UIView viewMain;
public static WrapperMenu MenuManager;
public static WrapperValueStories ValueStoriesManager;
public static WrapperBibliography BibliographyManager;
public static WrapperStakeHolder StakeHolderManager;
public static Aggiornamento AggiornamentoManager;
public static string RegionId = "";
public static string RegionName= "";
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// Reperisco il RegionName dai settings
RegionName= NSUserDefaults.StandardUserDefaults.StringForKey("regione");
// Inizializzo le variabili
tabmain = tabMain;
ctrMain = ctrmain;
viewMain = viewContent;
ctrHome = new Home(String.Empty, RegionName);
// Inizializzo i manager
MenuManager= new WrapperMenu();
ValueStoriesManager= new WrapperValueStories(ref viewMain);
BibliographyManager = new WrapperBibliography();
StakeHolderManager = new WrapperStakeHolder();
AggiornamentoManager = new Aggiornamento(ctrMain);
// Imposto i delegati
tabmain.Delegate = new TabDelegate(viewMain,
ctrMain,
MenuManager,
ValueStoriesManager,
BibliographyManager,
StakeHolderManager,
AggiornamentoManager);
// Reperisco il Root Menu
MenuManager.GetRootMenu(ref tabmain);
if(string.IsNullOrEmpty(RegionName) || String.IsNullOrEmpty(Utils.GetRegionIDByName(RegionName)))
MenuManager.SoloRegioni(ref tabmain,false);
else
{
RegionId = Utils.GetRegionIDByName(RegionName);
Utils.LoadSplash(viewMain,"",RegionName);
}
// If you have defined a view, add it here:
window.AddSubview (ctrMain.View);
window.MakeKeyAndVisible ();
Thread tAggiornaDati = new Thread(new ThreadStart( Aggiornamento.AggiornaDati));
tAggiornaDati.Start();
return true;
}
}
}
TabDelegate.cs:
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using IPadApp.Classes;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
namespace VSViewer
{
public class TabDelegate : UITabBarDelegate
{
private WrapperMenu MenuManager;
private WrapperValueStories ValueStoriesManager;
private WrapperBibliography BibliographyManager;
private WrapperStakeHolder StakeHolderManager;
private Aggiornamento AggiornamentoManager;
private UIView viewMain;
//private UIViewController ctrmain;
private NodeAction previousAction ;
private int previousNode=0;
public TabDelegate (UIView pviewMain,
UIViewController pctrMain,
WrapperMenu pMenuManager,
WrapperValueStories pValueStoriesManager,
WrapperBibliography pBibliographyManager,
WrapperStakeHolder pStakeHolderManager,
Aggiornamento pAggiornamento)
{
viewMain = pviewMain;
MenuManager = pMenuManager;
ValueStoriesManager = pValueStoriesManager;
BibliographyManager= pBibliographyManager;
StakeHolderManager = pStakeHolderManager;
AggiornamentoManager = pAggiornamento;
}
private int GetSelectedTabBarIndex (UITabBar tabbar, UITabBarItem item)
{
for (int i = 0; i < tabbar.Items.Count (); i++) {
if (item == tabbar.Items[i])
return i;
}
return -1;
}
public override void ItemSelected (UITabBar tabbar, UITabBarItem item)
{
int itemSelectedIndex = GetSelectedTabBarIndex (tabbar, item);
MerqurioMenuNode currentNode = MenuManager.GetCurrentNodeByPos (itemSelectedIndex);
if (!(previousAction==currentNode.Action && previousNode == currentNode.MenuID) ||
currentNode.Action== NodeAction.OpenSubMenu)
{
// Rimuovo tutte le immagini della VS che sto abbandonando
if (previousAction== NodeAction.OpenValueStory) ValueStoriesManager.RemoveAllSlides();
// Detacho la View dell'azione precedente
foreach (UIView subView in this.viewMain.Subviews)
{
subView.RemoveFromSuperview ();
subView.Dispose();
}
// Mostro la view corretta
switch (currentNode.Action) {
case NodeAction.OpenSubMenu:
MenuManager.GetMenuByNodeId (ref tabbar, itemSelectedIndex);
// Imposto la breadcrumb
if (currentNode.ParentMenuID==0 && currentNode.Direction== NodeDirection.Forward) Breadcrumb.SetMolecola(currentNode.ViewLabel);
else if (currentNode.ParentMenuID==0 &&currentNode.Direction== NodeDirection.Backward) Breadcrumb.SetMolecola("");
Breadcrumb.UpdateBreadcrumb(currentNode.ViewLabel, AppDelegate.RegionName);
// Mostro la Splash
Utils.LoadSplash(viewMain,currentNode.ViewLabel,AppDelegate.RegionName);
break;
case NodeAction.OpenValueStory:
ValueStoriesManager.ShowValueStory (currentNode, AppDelegate.RegionId);
break;
case NodeAction.OpenBibliography:
BibliographyManager.ShowBibliography(viewMain,currentNode.FileName);
break;
case NodeAction.OpenStakeHolder:
StakeHolderManager.ShowStakeHolder(viewMain);
break;
case NodeAction.OpenRegion:
Regioni ctrRegioni = new Regioni();
this.viewMain.AddSubview(ctrRegioni.View);
break;
case NodeAction.OpenSimulator1:
Simulator_1 ctrSimulator1 = new Simulator_1();
this.viewMain.AddSubview(ctrSimulator1.View);
break;
case NodeAction.OpenSimulator2:
Simulator_2 ctrSimulator2 = new Simulator_2();
this.viewMain.AddSubview(ctrSimulator2.View);
break;
case NodeAction.OpenAggiornamento:
this.viewMain.AddSubview(AggiornamentoManager.View);
break;
default:
break;
}
}
// Aggiorno i contatori
previousAction = currentNode.Action;
previousNode = currentNode.MenuID;
}
}
}
Please help.. I can't found either the old file for MonoTouch 3.2.6...
When I look at your Main.cs file you have a pattern, except one of the things is reversed.
**tabmain = tabMain**;
ctrMain = ctrmain;
viewMain = viewContent;
I think you probably meant tabMain = tabmain;