Delete Dialog Navigation Prism Forms - xamarin.forms

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.

Related

Xamarin Forms Shell Navigation Failure with System.NullReferenceException

This is a sample application attempting the Xamarin Forms navigation capability.
We have an event handler with this simple logic:
async void Button_Clicked(System.Object sender, System.EventArgs e)
{
await Shell.Current.GoToAsync(nameof(SchoolList));
}
We also have the route registered in App.xaml.cs as follows:
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
Routing.RegisterRoute(nameof(SchoolList), typeof(SchoolList));
}
However, when the corresponding button is clicked, we get the error below:
System.NullReferenceException: Object reference not set to an instance of an object.
at cross_app1.MainPage.Button_Clicked (System.Object sender, System.EventArgs e) [0x0000f] in /Users/klaus.nji/Projects/cross-app1/cross-app1/MainPage.xaml.cs:18
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:36
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:36
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-30/mcw/Java.Lang.IRunnable.cs:84
at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.39(intptr,intptr)
The system is Mac Catalina v10.15.7, IDE is Visual Studio 2019 for Mac and I have the Andriod SDK installed and able to see other aspects of the app.
It looks like you don’t have a Shell, so Shell.Current is null.
What Shell example did you follow?
MainPage = new MainPage(); means your app is pointing to a page of type MainPage. To use Shell (Route) navigation, it needs to be pointing to a Shell.
I would expect to see MainPage = new AppShell();.
There may be other details missing, so be sure to follow a working example, such as Xaminals.
The new AppShell line can be seen in https://github.com/xamarin/xamarin-forms-samples/blob/main/UserInterface/Xaminals/Xaminals/App.xaml.cs.
Note: Its possible to navigate in Xamarin Forms without having Shell, nor defining routes. (Personally, I dislike the Shell, so I don’t use it.) You can define MainPage as a NavigationPage (see its doc). Or you can simply set App.MainPage to different pages, to move between them, without a navigation stack.

Crashed when back to MainPage because of using SKGLView

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

SignalR notification using SqlScaleoutConfiguration gives random exception for Rebus.Transport.TransactionContext not serializable

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

Akavache or Sqlite is crashing When Calling in OnStart method

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

BizTalk The part 'part' of message '<MessageName>' contains zero bytes of data

I'm receiving this error in a Message Assignment shape within my orchestration. Within this assignment shape, I'm trying to execute an XPath query to extract a base64 encoded string from a message received by WCF. I'm then trying to load an XmlDocument variable with a Stream generated by a helper class that I've written. The base64 string will be the contents of either a PDF or Excel file (note: this is not XML). I've read that this can be done.
Here is the expression used in my Message Assignment:
messageCreator = new IAS.Integration.Services.Helpers.MessageCreator();
System.Diagnostics.EventLog.WriteEntry("IAS.Integration.Services.Orchestration", "MessageCreator Object created");
base64 = xpath(PerformTransformationResponse, "string(/*[local-name()='PerformTransformationResponseWrapper' and namespace-uri()='http://www.iasreo.com/integration/servicetypes']/*[local-name()='TransformedPayload'])");
//System.Diagnostics.EventLog.WriteEntry("IAS.Integration.Services.Orchestration", System.String.Format("Base64 from xpath: {0}", base64));
Output = new System.Xml.XmlDocument();
System.Diagnostics.EventLog.WriteEntry("IAS.Integration.Services.Orchestration", "Output instantiated as XmlDocument");
messageCreator.CreateMyMessage(Output, base64);
System.Diagnostics.EventLog.WriteEntry("IAS.Integration.Services.Orchestration", "messageCreator.CreateMyMessage(Output, base64)");
Here are the helper classes I've written to support this expression:
[Serializable]
public class MessageCreator
{
public void CreateMyMessage(XLANGMessage outMessage, string binaryStringMessage)
{
outMessage[0].LoadFrom(new StreamFactory(binaryStringMessage));
}
}
[Serializable]
public class StreamFactory : IStreamFactory
{
private string messageContent;
public StreamFactory(string inMessageContent)
{
messageContent = inMessageContent;
}
public Stream CreateStream()
{
byte[] messageBytes = Convert.FromBase64String(messageContent);
return new MemoryStream(messageBytes, 0, messageBytes.Length, true, true);
}
}
Finally, this is the error I receive in the Event Viewer:
xlang/s engine event log entry: Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'IAS.Integration.Services.Orchestrations.MainOrchestration(fcad6d68-ce54-bfa2-d035-56608b99ef52)'.
The service instance will remain suspended until administratively resumed or terminated.
If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
InstanceId: c398fd2a-b654-4981-be13-94146d640375
Shape name: Send_StreamedDocument
ShapeId: bc7a463b-eed2-4222-b2f7-3fdb1e44a3c5
Exception thrown from: segment 1, progress 25
Inner exception: The part 'part' of message 'Output' contains zero bytes of data.
Exception type: EmptyPartException
Source: Microsoft.XLANGs.Engine
Target Site: System.IO.Stream Persist(System.String ByRef, Boolean)
The following is a stack trace that identifies the location where the exception occured
at Microsoft.XLANGs.Core.Part.Persist(String& encoding, Boolean wantEncoding)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXXlangStore.StagePartData(Part part)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXXlangStore.PrepareMessage(XLANGMessage msg, IList promoteProps, IList toPromote)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXXlangStore.WriteMessageState(IBTPEPInfoLookup pepLookup, Guid portId, XLANGMessage msg, Segment seg, String opname, String url, IList promoteProps, Boolean track, IList toPromote)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXLogicalPortBinding.SendMessage(XLANGMessage msg, XlangStore store, Segment seg, OperationInfo op, IList additionalProps, IList toPromote, Boolean ignoreRoutingFailure)
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBase.SendMessage(Int32 iOperation, XLANGMessage msg, Correlation[] initCorrelations, Correlation[] followCorrelations, Context cxt, Segment seg, ActivityFlags flags)
at IAS.Integration.Services.Orchestrations.MainOrchestration.segment1(StopConditions stopOn)
at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)**
I can see it is happening when you are serializing the message as part of persisting state just before sending it. "Shape name: Send_StreamedDocument"
Is your OutPut message defined as a simple message or a multipart message?
Have you tried making the OutPut message a string instead of XMLDocument?
Edit: Actually the XMLDocument is not itself serializable. I didn't know that - I guess I have always managed to type my messages to something schema based before sending them out.
See here: http://talentedmonkeys.wordpress.com/2010/02/15/xmldocument-serialization-in-biztalk-2009-not/
And here: http://extremelytalentedmonkeys.blogspot.com/2009/12/xmldocument-serialization-not.html
You could wrap your message assignment and send shape in an atomic transaction so you avoid trying to persist something that is not serializable. Or you could use something else than an XMLDocument?

Resources