Selector invoked from objective-c on a managed object that has been GC'ed, how to avoid viewcontrollers from being GC'd - xamarin.ios

We have an app in the appstore that works without any issues on iPhone 4g/4gs but when I tested it on an iPod I got a surprise because it crashes all the time at "random" places. Looking at the strack traces it seems my viewcontrollers have been GC'ed.
Will the viewcontroller be garbagecollected if I write methods like this:
public void PushShowTeamController (Object a)
{
var teamController = new TeamController (a);
NavigationController.PushViewController (teamController, true);
}
Because the iPod suddently throws an error like this:
Jan 6 18:52:09 unknown MyApp[5197] <Warning>: Received memory warning.
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: Unhandled Exception: System.Exception: Selector invoked from objective-c on a managed object that has been GC'ed ---> System.MissingMethodException: No constructor found for MyApp.TeamController::.ctor(System.IntPtr)
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: at System.Activator.CreateInstance (System.Type type, BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes) [0x00000] in <filename unknown>:0
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: at System.Activator.CreateInstance (System.Type type, System.Object[] args, System.Object[] activationAttributes) [0x00000] in <filename unknown>:0
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: at System.Activator.CreateInstance (System.Type type, System.Object[] args) [0x00000] in <filename unknown>:0
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: at MonoTouch.ObjCRuntime.Runtime.ConstructNSObject (IntPtr ptr, IntPtr klass) [0x00000] in <filename unknown>:0
Jan 6 18:52:10 unknown UIKitApplication:mypackage.app[0x9db2][5197] <Notice>: --- End of inner exception stack trace ---

This will happen when an managed object is disposed (when no reference is left to an instance) and the object is later resurfaced by native code.
You need to ensure that a reference to MyApp.TeamController is kept in managed code as long as it can be required (e.g. accessed) by native code.
In most case MonoTouch will ensure a reference is kept. Your code:
NavigationController.PushViewController (teamController, true);
is correct and UINavigationController will keep a reference to your teamController. However if you call PushViewController on another controller then the first reference will be overwritten and will be collectable by the garbage collector (GC). This situation would lead to the exception you are seeing.
Note: because you can't predict when the GC will collect unreferenced object instance the exception will appear to be thrown randomly.

From my experience this happens when i use a lot of dispose() on managed objects instead of setting them to null and leaving the GC to do its job. Also anonymous delegates combined with dispose() can lead to such problems

Related

ServiceStack.LicenseException with a valid License Key

I am trying to register the license key by the Application_Start method. When I execute Licensing.RegisterLicense("{LicenseKey}"), the method LicenseUtils.ActivatedLicenseFeatures() returns the value "Text". But when I execute new AppHost().Init(), it gives me the following error:
Application Exception
ServiceStack.LicenseException
The free-quota limit on '10 ServiceStack Operations' has been reached. Please see https://servicestack.net to upgrade to a commercial license or visit https://github.com/ServiceStackV3/ServiceStackV3 to revert back to the free ServiceStack v3.
Description: HTTP 500. Error processing request.
Details: Non-web exception. Exception origin (name of application or object): ServiceStack.Text.
Exception stack trace:
at ServiceStack.LicenseUtils.ApprovedUsage (LicenseFeature licenseFeature, LicenseFeature requestedFeature, Int32 allowedUsage, Int32 actualUsage, System.String message) [0x00026] in <filename unknown>:0
at ServiceStack.LicenseUtils.AssertValidUsage (LicenseFeature feature, QuotaType quotaType, Int32 count) [0x00118] in <filename unknown>:0
at ServiceStack.Host.ServiceMetadata.Add (System.Type serviceType, System.Type requestType, System.Type responseType) [0x002c9] in <filename unknown>:0
at ServiceStack.Host.ServiceController.RegisterService (ITypeFactory serviceFactoryFn, System.Type serviceType) [0x00137] in <filename unknown>:0
at ServiceStack.Host.ServiceController.Register (ITypeFactory serviceFactoryFn) [0x0001a] in <filename unknown>:0
at ServiceStack.Host.ServiceController.Init () [0x00016] in <filename unknown>:0
at ServiceStack.ServiceStackHost.Init () [0x00073] in <filename unknown>:0
at API.Global.Application_Start (System.Object sender, System.EventArgs e) [0x00016] in API/Global.asax.cs:163
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in /private/tmp/source-mono-mac-4.2.0-branch-c6sr1/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/mono-4.2.2/mcs/class/corlib/System.Reflection/MonoMethod.cs:295
Version Information: 4.2.2 (explicit/996df3c Wed Jan 20 00:19:48 EST 2016); ASP.NET Version: 4.0.30319.17020
Powered by Mono
I already tried to update the ServiceStack package, with no success.
This is because you're using a ServiceStack.Text License which only covers usage for the ServiceStack.Text NuGet Package with packages from the full ServiceStack framework.

System.ExecutionEngineException: Attempting to JIT compile method 'System.Linq.Enumerable:<ToLookup`2>

here is my Code
public int GetUsersSqlCount()
{
// Here i get the Error
return this.GetUsersSql().Count();
}
public IEnumerable<CsUser> GetUsersSql()
{
return (from x in this._storage.CsUsers
join y in this._storage.CeMitarbs on x.MitNr equals y.MitNr
select x).OrderBy(x => x.KurzZch);
}
I get the following Error:
Unhandled Exception: System.ExecutionEngineException: Attempting to JIT compile method 'System.Linq.Enumerable:<ToLookup`2>m__5A<Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CeMitarb, System.Nullable`1<int>> (Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CeMitarb)' while running with --aot-only.
at System.Linq.Enumerable.ToLookup[CeMitarb,Nullable`1,CeMitarb] (IEnumerable`1 source, System.Func`2 keySelector, System.Func`2 elementSelector, IEqualityComparer`1 comparer) [0x00079] in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:2966
at System.Linq.Enumerable.ToLookup[CeMitarb,Nullable`1] (IEnumerable`1 source, System.Func`2 keySelector, IEqualityComparer`1 comparer) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:2934
at System.Linq.Enumerable+<CreateJoinIterator>c__Iterator18`4[Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser,Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CeMitarb,System.Nullable`1[System.Int32],Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser].MoveNext () [0x00023] in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:1157
at System.Collections.Generic.List`1[Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1[Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser]..ctor (IEnumerable`1 collection) [0x00000] in <filename unknown>:0
at System.Linq.Enumerable.ToArray[CsUser] (IEnumerable`1 source) [0x00000] in <filename unknown>:0
at System.Linq.QuickSort`1[Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser]..ctor (IEnumerable`1 source, System.Linq.SortContext`1 context) [0x00000] in <filename unknown>:0
at System.Linq.QuickSort`1+<Sort>c__Iterator2F[Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CsUser].MoveNext () [0x00000] in <filename unknown>:0
at System.Linq.Enumerable.Count[CsUser] (IEnumerable`1 source) [0x00000] in <filename unknown>:0
at CSMobile.Logic.Forms.Login_Dal.GetUsersSqlCount () [0x00000] in /Volumes/Mobile2011/Mobile 2011/trunk/WinCE/CSMobile/CSMobile.Logic/Forms/Login.Dal.cs:38
at CSMobile.Logic.Forms.Login_Logic.GetUsers () [0x0001f] in /Volumes/Mobile2011/Mobile 2011/trunk/WinCE/CSMobile/CSMobile.Logic/Forms/Login.Logic.cs:198
at CSMobile.Logic.Forms.Login_Logic.Anmelden2 (Int32 selectedProduct) [0x00050] in /Volumes/Mobile2011/Mobile 2011/trunk/WinCE/CSMobile/CSMobile.Logic/Forms/Login.Logic.cs:416
at CSMobile.UI.Login.Logic_LoginStepCompleted (Login_StepResult result) [0x0003e] in /Volumes/Mobile2011/Mobile 2011/trunk/IOS/CSMobile/CSMobile.UI/Forms/Login.cs:325
at CSMobile.Logic.Forms.Login_Logic.Anmelden1 () [0x00084] in /Volumes/Mobile2011/Mobile 2011/trunk/WinCE/CSMobile/CSMobile.Logic/Forms/Login.Logic.cs:364
at CSMobile.UI.Login.StartLogin () [0x00000] in /Volumes/Mobile2011/Mobile 2011/trunk/IOS/CSMobile/CSMobile.UI/Forms/Login.cs:75
at CSMobile.UI.Login.Pad_Start_TouchUpInside (MonoTouch.Foundation.NSObject sender) [0x00000] in /Volumes/Mobile2011/Mobile 2011/trunk/IOS/CSMobile/CSMobile.UI/Forms/Login.cs:235
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
at MonoTouch.UIKit.UIApplication.Main (System.String[] args) [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:34
at CSMobile.UI.Application.Main (System.String[] args) [0x0000a] in /Volumes/Mobile2011/Mobile 2011/trunk/IOS/CSMobile/CSMobile.UI/Main.cs:18
[ERROR] FATAL UNHANDLED EXCEPTION: System.ExecutionEngineException: Attempting to JIT compile method 'System.Linq.Enumerable:<ToLookup`2>m__5A<Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CeMitarb, System.Nullable`1<int>> (Genesis.DataAccess.Schema.Mobile.V1.Wrapper.CeMitarb)' while running with --aot-only.
I think this limitation here is actually due to Generic Virtual Methods - http://docs.xamarin.com/ios/about/limitations#Generic_Virtual_Methods
There's a discussion of a very similar problem on the mailing list:
http://monotouch.2284126.n4.nabble.com/LINQ-JIT-error-again-td3800970.html;cid=1338984263803-35#a3800169
It didn't sound like that thread found a solution
It might be worth contacting Xamarin support directly on this one. http://bugzilla.xamarin.com/
Generics are a bit weird on MonoTouch due to AOT compilation. A true runtime / JIT is disallowed in iOS, so it must compile everything ahead-of-time.
In this particular case, your method which returns IEnumerable<CsUser> is most likely the culprit. Generic interfaces cause problems. Try changing your return type to a List<CsUser> or any other concrete class that implements IEnumerable<CsUser>.
OrderBy is known to fail in this scenario. This appears to be fixed in MonoTouch version 2.10 but unfortunately if you're using an engine like Unity, that only ships with 2.6 currently (as of 4.3.x).
https://bugzilla.xamarin.com/show_bug.cgi?id=2155#c11
I don't know a convenient solution for Xamarin at the moment.
However there is such a solution for Unity 3D.
You can try LINQ to iOS. It's a custom implementation of LINQ to Objects extension methods that works on iOS without JIT-compile errors. If you're using Xamarin you may try to take .dll from LINQ to iOS and use it in your project. After all, Xamarin and Unity both use Mono compiler.

How to add CoreData Model File .momd into MonoTouch project

The MonoTouch solution includes two projects.
MonoTouch Binding Project: API Contract interfaces for linked native
ObjC library
Test Client Application
The native ObjC library requires to include Core Data Model file (.momd). I have added it to the project of Test App.
But app crashes with the following error:
Unhandled Exception: MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: Cannot create an NSPersistentStoreCoordinator with a nil model
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSendSuper_IntPtr_bool (intptr,intptr,intptr,bool)
at MonoTouch.UIKit.UIViewController.PresentModalViewController (MonoTouch.UIKit.UIViewController modalViewController, Boolean animated) [0x00038] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIViewController.g.cs:261
at CombinedControllerApp.MainController.<ViewDidLoad>m__2 (System.Object , System.EventArgs ) [0x0003d] in /Users/mahmood1/Documents/Projects/TouchNote-Prototype/CombinedControllerApp/MainController.cs:96
at MonoTouch.UIKit.UIControlEventProxy.Activated () [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIControl.cs:30
at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
at CombinedControllerApp.Application.Main (System.String[] args) [0x00000] in /Users/mahmood1/Documents/Projects/TouchNote-Prototype/CombinedControllerApp/Main.cs:17
[ERROR] FATAL UNHANDLED EXCEPTION: MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: Cannot create an NSPersistentStoreCoordinator with a nil model
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSendSuper_IntPtr_bool (intptr,intptr,intptr,bool)
at MonoTouch.UIKit.UIViewController.PresentModalViewController (MonoTouch.UIKit.UIViewController modalViewController, Boolean animated) [0x00038] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIViewController.g.cs:261
at CombinedControllerApp.MainController.<ViewDidLoad>m__2 (System.Object , System.EventArgs ) [0x0003d] in /Users/mahmood1/Documents/Projects/TouchNote-Prototype/CombinedControllerApp/MainController.cs:96
at MonoTouch.UIKit.UIControlEventProxy.Activated () [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIControl.cs:30
at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
at CombinedControllerApp.Application.Main (System.String[] args) [0x00000] in /Users/mahmood1/Documents/Projects/TouchNote-Prototype/CombinedControllerApp/Main.cs:17
How to add this needed CoreData Model File into Test Application that it will be visible for the native library?
Thanks!
(Sources are here : http://www.axifile.com/en/71EC96914A)
Per my comment:
Adding most files like this to your project with Build Action of Content will solve the issue.

No constructor found for ViewController::.ctor(System.IntPtr)

I'm having an issue where my Monotouch application sometimes crashes just after receiving a memory warning. Please see that stack trace below.
Received memory warning. Level=2
DTMobileIS[2299] : _memoryNotification : {
OSMemoryNotificationLevel = 2;
timestamp = "2011-04-11 14:29:09 +0000";
}
Toplevel exception: System.MissingMethodException: No constructor found for Myapp.UI.BoardController::.ctor(System.IntPtr)
at System.Activator.CreateInstance (System.Type type, BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes) [0x00000] in :0
at System.Activator.CreateInstance (System.Type type, System.Object[] args, System.Object[] activationAttributes) [0x00000] in :0
at System.Activator.CreateInstance (System.Type type, System.Object[] args) [0x00000] in :0
at MonoTouch.ObjCRuntime.Runtime.ConstructNSObject (IntPtr ptr, IntPtr klass) [0x00000] in :0
at MonoTouch.ObjCRuntime.Runtime.GetNSObject (IntPtr ptr) [0x00000] in :0
at MonoTouch.ObjCRuntime.Runtime.GetNSObjectWrapped (IntPtr ptr) [0x00000] in :0
at (wrapper native-to-managed) MonoTouch.ObjCRuntime.Runtime:GetNSObjectWrapped (intptr)
at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00000] in :0
at Myapp.Free.Application.Main (System.String[] args) [0x00000] in /Users/haakon/Code/Myapp-work/iOS/Myapp.Free/Myapp.Free/Main.cs:12
The stack trace is correct in that the indicated class (BoardController, which is a UIViewController subclass) lacks a constructor taking a IntPtr parameter. But this is intentional as I don't use Interface Builder at all in my application. So why does this happen?
I did find a similar question that seemed to suggest that this can happen if you allow your views (or possibly view controllers) to become garbage collected. But I don't see how this can happen here. Some background: My application delegate holds a strong reference to a navigation controller, which in turn holds a strong reference to the root view controller in the navigation stack. This root view controller also holds a strong reference to the BoardController instance. So I don't understand how it's possible that BoardController gets garbage collected.
Any ideas?
The IntPtr constructor is used when a native object needs to be surfaced to a managed object. In this particular case, you could be creating, like this:
var foo = new Foo ();
SomeObject.Property = foo;
This assigns the Foo object to the property, but if the Property is an Objective-C object, if you do not keep a reference to "foo", then Mono's GC will go ahead and dispose the linkage between the managed Foo and the unmanaged Foo.
Then, later on, you try to retrieve it:
var bar = SomeObject.Property;
Here, MonoTouch will know that there is no managed object anymore than maps to it, so it has to construct a new one, but all it has is the IntPtr to the Objective-C code. This is why you need the constructor.
You might be tempted to just add the native constructor, and this is fine in many cases, but it is a problem if your object has its own state stored in the managed world, for example:
public class Foo : UIView {
string Name;
public Foo () { Name= "Hello"; }
public Foo (IntPtr ptr) : base (ptr) {}
}
In this case, the IntPtr constructor can not completely reconstruct the managed object and its state merely from the IntPtr. So the likely source of your problem is that you are not keeping a reference to your object.
So the real fix in short is: keep a reference to your BoardController in your managed code to prevent the object from being collected when you are still going to use it later on.

EMGU library OPENCV problem with native memroy management - does really work with mono?

we are working in a project involving the use of EMGU and in particoular the SVM functions of OpenCV and we have a problem using Mono on a Ubuntu platform and we don't have this problem on windows. The problem appears when we call the Emgu.CV.ML.SVM.Train method. All the parameters are correct and we canno't debug the wrapped code...
We have tried to increase the Shared Memory and other tricks but it doesn't work.
Do you have any idea?
Thank you
Angelo
Unhandled Exception: Emgu.CV.CvException: OpenCV: requested size is negative or too big
at Emgu.CV.CvInvoke.CvErrorHandler (Int32 status, System.String funcName, System.String errMsg, System.String fileName, Int32 line, IntPtr userData) [0x00000]
at (wrapper native-to-managed) Emgu.CV.CvInvoke:CvErrorHandler (int,intptr,intptr,intptr,int,intptr)
at (wrapper managed-to-native) Emgu.CV.ML.MlInvoke:CvSVMTrain (intptr,intptr,intptr,intptr,intptr,Emgu.CV.ML.Structure.MCvSVMParams)
at Emgu.CV.ML.SVM.Train (Emgu.CV.Matrix`1 trainData, Emgu.CV.Matrix`1 responses, Emgu.CV.Matrix`1 varIdx, Emgu.CV.Matrix`1 sampleIdx, Emgu.CV.ML.SVMParams parameters) [0x00000]
at Segmentation.ImageFeatures.LeafHog.TrainModel (IDictionary`2 dicInOutImage) [0x00000]
at Segmentation.ImageSegmentators.Composite.TrainModel (IDictionary`2 dicInOutImage) [0x00000]
at Segmentation.ImageSegmentators.CompositionMlpRprop.TrainModel (IDictionary`2 dicInOutImage) [0x00000]
at Segmentation.GeneticConfig.ChromoCreator.GetASegmentation (IConfigChromosome configChromosome, IDictionary`2 dicInOutImageTrain) [0x00000]
at Segmentation.GeneticConfig.ConfigChromoProvider.AddChromosomeIfNew (IConfigChromosome chromo) [0x00000]
at Segmentation.GeneticConfig.ConfigChromosome.Generate () [0x00000]
at Segmentation.GeneticConfig.ConfigChromosome..ctor (Int32 chromoLength, IConfigChromoProvider cProvider) [0x00000]
at Segmentation.GeneticConfig.ConfigChromosome.CreateNew () [0x00000]
at AForge.Genetic.Population..ctor (Int32 size, IChromosome ancestor, IFitnessFunction fitnessFunction, ISelectionMethod selectionMethod) [0x00000]
at SegmentationCLI.Program.Main (System.String[] args) [0x00000]

Resources