When I use the code below in my xamarin.forms project to check if User object exist in akavache cache, I am getting the exception below. the same code or any akavache query works somewhere else but crashes in onStart method only. I believe that I am initializing akavache in constructor already. I tried exact same code using mobile center to query locally (local sqlite) user data and I get the same exception. I think that this should be something to do with the sqlite as both akavache and mobile center uses similar sqlite libraries. Does anybody know why it doesnt work in OnStart method?
public App()
{
Microsoft.Azure.Mobile.MobileCenter.Start("android=key" +
"uwp=key",
typeof(Microsoft.Azure.Mobile.Analytics.Analytics), typeof(Microsoft.Azure.Mobile.Crashes.Crashes));
Akavache.BlobCache.ApplicationName = "myApp";
Akavache.BlobCache.EnsureInitialized();
ServiceLocator.Add<ICloudService, AzureCloudService>();
InitializeComponent();
}
protected async override void OnStart()
{
try
{
var User= await BlobCache.UserAccount.GetObject<User>("User");
if (User != null)
Helpers.Settings.IsLoggedIn = true;
else
Helpers.Settings.IsLoggedIn = false;
}
catch (Exception)
{
Helpers.Settings.IsLoggedIn = false;
}
ShowMainPageOrLoginPage();
}
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): Unhandled Exception:
11-13 02:08:14.761 E/MobileCenterCrashes( 6308):
System.NullReferenceException: Object reference not set to an instance
of an object. 11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.AppCompat.Platform.LayoutRootPage
(Xamarin.Forms.Page page, System.Int32 width, System.Int32 height)
[0x0000c] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:291
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.AppCompat.Platform.Xamarin.Forms.Platform.Android.IPlatformLayout.OnLayout
(System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
r, System.Int32 b) [0x00003] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\Platform.cs:199
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Xamarin.Forms.Platform.Android.PlatformRenderer.OnLayout
(System.Boolean changed, System.Int32 l, System.Int32 t, System.Int32
r, System.Int32 b) [0x0000e] in
D:\agent_work\1\s\Xamarin.Forms.Platform.Android\PlatformRenderer.cs:73
11-13 02:08:14.761 E/MobileCenterCrashes( 6308): at
Android.Views.ViewGroup.n_OnLayout_ZIIII (System.IntPtr jnienv,
System.IntPtr native__this, System.Boolean changed, System.Int32 l,
System.Int32 t, System.Int32 r, System.Int32 b) [0x00008] in
:0
EDIT:
This issue is definetly caused by akavache. Message is really strange. it looks like that akavache has some relation with LayoutRootPage.
See my code above, I get User object from akavache cache and user object defines if I should show Login Page or Main Page. If I move ShowMainPageOrLoginPage();function above akavache call, it works just fine. So it seems that you cant make any query with akavache before the rootlayoutpage - Main page is set or loaded.
I had the same problem once before, for some reason if you initialize using the static method it doesn't work all the time.
Doesn't work
IBlobCache _cache = BlobCache.LocalMachine;
Does Work
IBlobCache _cache = new SQLitePersistentBlobCache(systemPath + "/CacheUtils.db");
If you want to find the systemPath you can use this in either your Android or iOS
systemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
Related
SIGABRT: Cannot access a disposed object. Object name: 'SKGLView'.
We are using SKGLView in MainPage, sometimes back from another view, this error will show and app crash. I have no idea, and here is the log from App Center.
NSObject.get_SuperHandle ()
/Users/builder/azdo/_work/1/s/xamarin-macios/src/Foundation/NSObject2.cs:471
GLKView.Display ()
/Users/builder/azdo/_work/1/s/xamarin-macios/src/build/ios/native/GLKit/GLKView.g.cs:152
SKGLViewRenderer+<>c__DisplayClass4_0.b__1 ()
NSAsyncActionDispatcher.Apply ()
/Users/builder/azdo/_work/1/s/xamarin-macios/src/Foundation/NSAction.cs:152
(wrapper managed-to-native)
UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
UIApplication.Main (System.String[] args, System.IntPtr principal,
System.IntPtr delegate)
/Users/builder/azdo/_work/1/s/xamarin-macios/src/UIKit/UIApplication.cs:86
Application.Main (System.String[] args)
Finally, we solve it just by setting HasRenderLoop property for SKGLView using code, not in Xaml.
Reference link: https://github.com/mono/SkiaSharp/issues/870
I want to redirect opened URLs to an external browser in my WebView, so I hooked its Navigated event:
webView.Navigating += (s, e) =>
{
if (IsExternalUrl(e.Url))
{
try
{
var uri = new Uri(e.Url);
Device.OpenUri(uri); // show external links in external browser
}
catch (Exception)
{
}
e.Cancel = true; // <- not having any effects on Android
}
};
Under Android, this leads to the URL being opened on Chrome and in the WebView at the same time. On iOS e.Cancel = true does work as expected.
I searched extensively on the web but found nothing that helped me, including this Xamarin forum thread: https://forums.xamarin.com/discussion/144314/using-webviewrenderer-and-webviewclient-causes-cancel-navigation-not-working
I now have a workaround, using the back navigation:
XAML:
<local:HybridWebView x:Name="webView" CanGoBack="True" WidthRequest="1000" HeightRequest="1000" />
Code behind:
webView.Navigated += (s, e) =>
{
if (e.Result == WebNavigationResult.Success)
{
if (Device.RuntimePlatform == Device.Android) // on Android, prohibit webview from mirroring urls
if (IsExternalUrl(e.Url)) // that are shown on external browser
webView.GoBack(); // this is necessary because e.Cancel = true doesn't
} // work in webView.Navigating() event
};
Note: Initially, the Navigated event wasn't firing, so I pimped my HybridWebView with a WebViewClient featuring this override:
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
RaisePageFinishedEvent(url, view.Title);
...
...
var source = new UrlWebViewSource { Url = url };
var args = new WebNavigatedEventArgs(WebNavigationEvent.NewPage, source, url, WebNavigationResult.Success);
_renderer.ElementController.SendNavigated(args);
}
I'm currently using Xamarin.Forms 4.5.
Pressing the back button programmatically is a really crude workaround. So a solution where the url open event is actually canceled is much appreciated.
Update:
I had to remove CanGoBack="True" in the XAML and hard-code the property in OnElementChanged of my WebViewRenderer:
(Element as IWebViewController).CanGoBack = true;
Setting the CanGoBack property in XAML worked fine while the VS 2019 debugger was running attached but if running stand-alone, the app shut down immediately. Can be reproduced on a simple WebView without custom renderer:
ApplyPropertiesVisitor.SetPropertyValue (System.Object xamlelement, Xamarin.Forms.Xaml.XmlName propertyName, System.Object value, System.Object rootElement, Xamarin.Forms.Xaml.INode node, Xamarin.Forms.Xaml.HydrationContext context, System.Xml.IXmlLineInfo lineInfo)
ApplyPropertiesVisitor.Visit (Xamarin.Forms.Xaml.ValueNode node, Xamarin.Forms.Xaml.INode parentNode)
ValueNode.Accept (Xamarin.Forms.Xaml.IXamlNodeVisitor visitor, Xamarin.Forms.Xaml.INode parentNode)
ElementNode.Accept (Xamarin.Forms.Xaml.IXamlNodeVisitor visitor, Xamarin.Forms.Xaml.INode parentNode)
ElementNode.Accept (Xamarin.Forms.Xaml.IXamlNodeVisitor visitor, Xamarin.Forms.Xaml.INode parentNode)
RootNode.Accept (Xamarin.Forms.Xaml.IXamlNodeVisitor visitor, Xamarin.Forms.Xaml.INode parentNode)
XamlLoader.Visit (Xamarin.Forms.Xaml.RootNode rootnode, Xamarin.Forms.Xaml.HydrationContext visitorContext, System.Boolean useDesignProperties)
XamlLoader.Load (System.Object view, System.String xaml, System.Reflection.Assembly rootAssembly, System.Boolean useDesignProperties)
XamlLoader.Load (System.Object view, System.String xaml, System.Boolean useDesignProperties)
XamlLoader.Load (System.Object view, System.Type callingType)
Extensions.LoadFromXaml[TXaml] (TXaml view, System.Type callingType)
WebPageCollabora.InitializeComponent ()
CloudplanMobileClient.WebPageCollabora..ctor (System.String url) [0x00031] in <6b79d357cd4641c5bd9a69278958d871>:0
WebPage+<>c__DisplayClass9_0.<OpenNewPage>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.27(intptr,intptr)
I was wondering why the bug obviously has been fixed in 2020 and still I was experiencing the problem. I then noticed that the fix was applied only to FormsWebViewClient but not to the native Xamarin.Android class WebViewClient. I solved the issue just by deriving my web client used in my HybridWebViewRenderer from FormsWebViewClient instead of WebViewClient and modified the constructor a bit:
using Xamarin.Forms.Platform.Android;
...
namespace MyApp.Droid
{
// note: class was derived from 'WebViewClient' before
public class JavascriptWebViewClient : FormsWebViewClient
{
HybridWebViewRenderer _renderer;
string _javascript;
// note: now also calling base class constructor with renderer as parameter
public JavascriptWebViewClient(string javascript, HybridWebViewRenderer renderer) : base(renderer)
{
_javascript = javascript;
_renderer = renderer ?? throw new ArgumentNullException("renderer");
}
...
}
}
So I have a Confirm Delete Dialog and the expected behavior is that when they confirm, it navigates to the previous page. However, I keep getting a Null Object Reference Error on the Navigation Service or Parameters (I'm not sure which).
Code
var p = new NavigationParameters();
p.Add(PageConstants.UserId, UserId);
if (!SalesLoad)
{
await _purchaseRepository.RemoveAsync(await _purchaseRepository.GetById(LoadId)).ConfigureAwait(true);
await NavigationService.NavigateAsync(PageConstants.MyAppPageNav, p, useModalNavigation: false);
}
Error
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
10-17 07:08:58.542 E/mono-rt (10291): at Prism.Navigation.INavigationServiceExtensions.NavigateAsync (Prism.Navigation.INavigationService navigationService, System.String name, Prism.Navigation.INavigationParameters parameters, System.Nullable`1[T] useModalNavigation, System.Boolean animated) [0x00000] in d:\a\1\s\Source\Xamarin\Prism.Forms\Navigation\INavigationServiceExtensions.cs:47
10-17 07:08:58.542 E/mono-rt (10291): at MyApp.ViewModels.DeleteLoadViewModel.DeleteLoad () [0x00199] in D:\My-App\MyApp\MyApp\ViewModels\Shared\DeleteLoadViewModel.cs:119
10-17 07:08:58.542 E/mono-rt (10291): at MyApp.ViewModels.DeleteLoadViewModel.<.ctor>b__29_0 () [0x0001f] in D:\My-App\MyApp\MyApp\ViewModels\Shared\DeleteLoadViewModel.cs:92
The Navigation Parameters aren't null when I get the the Navigate line and neither is the object. I Set a break point in the VM that it's supposed to navigate to but it's never reached.
I use:
SignalR 2.2.2 in SqlScaleoutConfiguration
Rebus 3.0.1
Some events stored in Rebus are handled by a notification hub and pushed to the clients using signalR.
Everything works fine, but this morning, after having published a new version, none of the clients received the "new version" message probably because of the following exception:
10:39:04.586| |ERROR| |ProcessId=8196| |ThreadId=5| |SignalR.SqlMessageBus| |Stream 0 : Error starting SQL notification listener: System.Runtime.Serialization.SerializationException: Type 'Rebus.Transport.TransactionContext' in Assembly 'Rebus, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
Server stack trace:
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeMessageParts(ArrayList argsToSerialize)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage..ctor(IMethodCallMessage mcm)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.SmuggleIfPossible(IMessage msg)
at System.Runtime.Remoting.Channels.CrossAppDomainSink.SyncProcessMessage(IMessage reqMsg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System._AppDomain.CreateInstance(String assemblyName, String typeName)
at System.Data.SqlClient.SqlDependency.CreateProcessDispatcher(_AppDomain masterDomain)
at System.Data.SqlClient.SqlDependency.ObtainProcessDispatcher()
at System.Data.SqlClient.SqlDependency.Start(String connectionString, String queue, Boolean useDefaults)
at Microsoft.AspNet.SignalR.SqlServer.ObservableDbOperation.StartSqlDependencyListener()
The message in Rebus queue results as correctly handled.
The handler is this:
public async Task Handle(ApplicationVersionEvent message)
{
await
Clients.All.CheckApplicationVersion(new ApplicationCurrentVersionNotification
{
CurrentVersion = message.CurrentVersion
});
}
It was resolved by a restart, but I need to understand what happened.
I similar issues are:
https://github.com/SignalR/SignalR/issues/3401
https://github.com/SignalR/SignalR/issues/3404
SQL Query Notifications do not always work in scaleout setup (SQL Server)
https://github.com/rebus-org/Rebus/issues/493
Rebus, exception when creating AppDomain / Instance from async Handler
but I think this is not the same case.
It is really hard for me to tell you what's going on here besides what you have already discovered: SignalR for some weird reason seems to want to serialize the values stashed in the current execution context, and one of those values is Rebus' current transaction context.
As explained in the links you included, Rebus stores an "ambient transaction" this way when handling a message, allowing all of its own operations to be enlisted in the same unit of work.
You could use the approach explained here, where the transaction context is temporarily removed in a safe way like this
public async Task Handle(SomeMessage message)
{
var transactionContext = AmbientTransactionContext.Current;
AmbientTransactionContext.Current = null;
try
{
JuggleWithAppDomainsInHere();
}
finally
{
AmbientTransactionContext.Current = transactionContext;
}
}
possibly moving relevant bits to the constructor/Dispose method respectively in a class that implements IDisposable, making for a smoother API:
using(new DismantleAmbientRebusStuff())
{
JuggleWithAppDomainsInHere();
}
I think someone who knows a lot about SignalR would need to chime in if we were to find out what really happened.
I forgot this issue, but I solved it by a workaround a little later on.
The clue is that SqlMessageBus serializes the context when it is initialized and this happens the first time it is retrieved invoking GetHubContext, so I forced its initialization before executing any command.
app.MapSignalR();
var context = new OwinContext(app.Properties);
var token = context.Get<CancellationToken>("host.OnAppDisposing");
if (token != CancellationToken.None)
{
token.Register(() =>
{
log.Info("host.OnAppDisposing");
// code to run when server shuts down
BackendMessageBusConfig.DisposeContainers();
});
}
// this code brings forward SignalR SqlMessageBus initialization
var forceInit = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
BackendMessageBusConfig.Register();
I recently followed Xamarin's SQLite tutorial to install SQLite-net PCL. Everything works perfectly on the simulator in Debug mode but I'm getting crashes on startup in Release mode.
The exception is as follows:
exception:
System.MissingMethodException
message:
Default constructor not found for type MyApp.iOS.FileHelper
stack trace:
at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain
(int,string[],intptr,intptr) at UIKit.UIApplication.Main
(System.String[] args, System.IntPtr principal, System.IntPtr
delegate) [0x00005] in
/Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String
principalClassName, System.String delegateClassName) [0x00038] in
/Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at MyApp.iOS.Application.Main (System.String[] args) [0x00008] in
/Users/{FilePath}/iOS/Main.cs:13
What I've found
So this MyApp.iOS.FileHelper is Xamarin's code that fetches the documents directory. The implementation goes like this:
In the Forms application we just have a contract:
public interface IFileHelper
{
string GetLocalFilePath(string filename);
}
In the MyApp.iOS project we define a dependency:
[assembly: Dependency(typeof(FileHelper))]
namespace MyApp.iOS
{
public class FileHelper : IFileHelper
{
public FileHelper() { }
public string GetLocalFilePath(string filename)
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return Path.Combine(libFolder, filename);
}
}
}
Here's how I am using it:
DependencyService.Get<IFileHelper>().GetLocalFilePath("MyAppDatabase.db3")
The application works as expected in Debug mode. So either the Dependency Service is behaving differently in Release or the Documents Directory is different in Release.
My Question
How can avoid this exception in release mode?
Dependency Info:
Xamarin Forms 2.3.3.193
Sqlite-net-pcl 1.2.1
update:
What I've tried:
Added a default constructor, yields no change
Tried different linker possibilities, yields no change
From Introduction to DependencyService
Note that every implementation must have a default (parameterless)
constructor in order for DependencyService to be able to instantiate
it. Parameterless constructors cannot be defined by the interface.
You need to add an empty constructor to your FileHelper class.
public FileHelper() {
}
Please note: I tried voting to close this question as a duplicate. It clearly
failed to be closed as such.
Based on comments point to this post from SushiHangover, this is what resolved my issue:
I needed to add decorate my FileHelper class in my iOS project with:
[Preserve(AllMembers = true)]
again, please go check out his original post here:
https://stackoverflow.com/a/41932246/1664443