Xamarin Forms / MvvmCross architecture with ICommand.Execute(Object) pattern? - xamarin

I've started learning some mobile development using Xamarin Forms and MvvmCross.
In its simplest form I have an app that contains a button. When this button is tapped it calls an api via a rest service and returns data via the messaging service.
I'm having issues showing dialogs (ACR) when using the ICommand.Execute(object) pattern. I'm assuming this is because the execute in this pattern is not async and therefore blocks the main ui thread? This is a sample of what I'm doing:
var cmd = Command.Create(CmdType.Login);
cmd.Execute(User);
Please consider the following lines straight from the MvvmCross documentation for async operations.
MyCommand = new MvxCommand(() => MyTaskNotifier = MvxNotifyTask.Create(() => MyMethodAsync(), onException: ex => OnException(ex)));
private async Task MyMethodAsync()
{
await _someService.DoSomethingAsync();
// ...
}
In this case my DoSomething() isn't aysnc - if anything its an async void, or a no no. To get around this I've updated from MvxCommand to MvxAsyncCommand and then have to use a bandaid to get the dialogs to show.
await Task.Delay(300);
or
await Task.Run(() => { command.Execute(User); }).ConfigureAwait(false);
At this point, I'm obviously questioning the use of the command pattern. Am I missing an easy fix or have I chosen an architecture that's not a good fit here? Any guidance is appreciated.

You can use it like this
public ICommand YourCommand => new Command(async () => await YourActionAsync());

Related

Blazor and ContinueWith on page load

I am new to Blazor. I'm working on a Server App (not WASM).
On a page load, I am loading 2 things to a page. Item1 is loaded at the same time as Item2 via API calls. I'd like individual items to show up as soon as they are available. I was thinking something like
protected override async Task OnInitializedAsync()
{
var t1 = _service.GetItem1().ContinueWith(t => {
Item1Loaded = true;
Item2State = t.Result;
await InvokeAsync(StateHasChanged);
});
var t2 = _service.GetItem2().ContinueWith(t => {
Item2Loaded = true;
Item2State = t.Result;
await InvokeAsync(StateHasChanged);
});
}
I have a couple questions about this though:
Do I need to worry about canceling these lines if the user navigates away from the component? (would changing a state variable after the component is removed cause a problem) or does Blazor handle that at the framework level somehow?
Do I need to ensure this gets back to a certain thread with a Synchronization Context? It seems like InvokeAsync just does this for me but want to be sure.
Its hard to find lots of modern examples of ContinueWith. async/await is dominant, but I don't think it allows continuations to execute in the order they complete. Is this a reasonable use of it?
Since you are using Server side you can do this more cleanly (ContinueWith is more or less obsolete since async / await):
protected override async Task OnInitializedAsync()
{
var t1 = Task.Run(async () =>
{ Item1State = await _service.GetItem1();
Item1Loaded = true; // you can probably derive this from Item1State
await InvokeAsync(StateHasChanged);
});
var t2 = Task.Run(async () =>
{ Item2State = await _service.GetItem2();
Item2Loaded = true;
await InvokeAsync(StateHasChanged);
});
await Task.WhenAll(t1, t2);
}
No need to call StateHasChanged() here.
Without the ItemLoaded guards you could do this without Task.Run().
Do I need to worry about canceling these lines if the user navigates away
Most modern DB stuff can be passed a cancellation token. So, use that if you wish to cancel the operation. If It's your own code and the operations are long running, consider using cancellation tokens.
Do I need to ensure this gets back to a certain thread with a Synchronization Context?
Calling await InvokeAsync(StateHasChanged); ensures the UI code is run on the UI thread.
Question 3
Stick with simple await. Yes, it executes in order. And call await InvokeAsync(StateHasChanged) between operations to update the UI if you have more than two await operations.
Note : This will only work if you await real async code, not sync code wrapped in a Task! If there are no yields, the Renderer gets no thread time so the UI doesn't get updated till it gets some.

Nightwatch - How to subscribe to CDP Events?

As you may already know, Nightwatch 2 now includes methods for making calls to CDP protocol.
So, I'm trying to capture network responses. I know that the "Network" target has to be enabled and also we have to subscribe a callback to the Network.responseReceived event. I've already done it in another framework tool, but I can't find any related example in the Nightwatch documentation that uses CDP events.
At this point, I don't know which is the method that allows this subscription or where is it, is it in browser.driver or in cdpConnection objects?
This is the code I'm currently trying:
module.exports = {
'#tags': ['njs2-03'],
async myTest (browser) {
await browser.driver.sendAndGetDevToolsCommand('Network.enable')
const cdpConnection = await browser.driver.createCDPConnection('page');
cdpConnection._wsConnection.on('Network.responseReceived', entry => {
console.log('ENTRY >>', entry)
})
await browser.url('https://duckduckgo.com/')
}
}
Any suggestion would be really helpful, Thanks!
I was looking for an answer to a similar problem myself. It appears that it is sometimes much better to analyze the source code of Nightwatch directly. Especially after version 2 was released.
Analysis of the CDP commands eg. the mockNetworkResponse method in the Nightwatch code in the method-mappings.js file give answers.
https://github.com/nightwatchjs/nightwatch/blob/098306cf77d4e380b69ab836231947fe94a12ca0/lib/transport/selenium-webdriver/method-mappings.js
Mind that you are using directly the _wsConnection object. Therefore, that is the message event you are looking for. https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/message_event
Thus, try the following
async myTest (browser) {
await browser.driver.sendAndGetDevToolsCommand('Network.enable')
const cdpConnection = await browser.driver.createCDPConnection('page')
cdpConnection._wsConnection.on('message', message => {
const messageParsed = JSON.parse(message)
if (messageParsed.method === 'Network.responseReceived') {
console.log('DEVTOOLS EVENT PARAMS >>', messageParsed.['params'])
}
})
await browser.url('https://duckduckgo.com/')
}

Xamarin TouchRunner Hangs calling IOS 3rd Party Binding

I have a 3rd party API IOS Binding which I am trying to test (more like an integration test) using TouchRunner.
An example API Method is this -
_client.AuthenticateWithUsername(username, token,
() => { // Success Callback },
() => { // NoConnection Callback },
(obj) => { // Other Error Callback });
The API when called goes off and does some work in the background then eventually makes one of the callbacks above, I would like to control the flow of the unit test using something like -
How can I unit test async methods on the UI Thread with Xamarin iOS TouchRunner
Unfortunately, when I insert the AutoResetEvent code, TouchRunner just hangs and never returns to the GUI.
I have also tried to use a TaskCompletionSource as follows -
public async Task<AuthResponse> AuthenticateUserAsync(string username, string password)
{
TaskCompletionSource<AuthResponse> tcs = new TaskCompletionSource<AuthResponse>();
AuthResponse response = new AuthResponse { Success = false };
LoginResponse loginResponse = await LoginUser(username, password);
_client.AuthenticateWithUsername(username, loginResponse.token,
() =>
{
response.Success = true;
Console.WriteLine("Auth");
tcs.SetResult(response);
},
() => { tcs.SetResult(response); },
obj => { tcs.SetResult(response); },
obj => { tcs.SetResult(response); });
return await tcs.Task;
}
[Test]
public async void AuthenticateUserAsyncTest()
{
var auth = await AuthenticateUserAsync(_username, _password);
Assert.IsTrue(auth.Success);
}
The debugger stepped through fine until the return await tcs.Task, but then results in a similar HUNG runner.
How can I work out why the hang is happening?
As this was not working, I then resorted to code like this -
_client.AuthenticateWithUsername(_username, loginResponse.token,
() =>
{
Assert.Pass("This crashes the runner");
Assert.True(true); // This DOES NOT!
},
() =>
{
// This will crash runner also
Assert.Fail("NoConnection");
},
(InvalidTokenError obj) =>
{
Assert.Fail("InvalidToken" + obj.Description);
},
(ClientError obj) =>
{
Assert.Fail("ClientError" + obj.Description);
});
As you can see, the flow ends up (understandably), run test, runs client call, end of test method completes which shows test as success, then the callback returns and the asserts get called, which crash the app, which we assume is because the runner has already completed the test, why one assert works and other crashes I do not know.
So,
Am I approaching this the right way?
Could something be happening in the 3rd Party API that will cause these approaches to hang? and how would I debug that?
Thanks #Nkosi, that is a good suggestion, I forgot to add that during my original testing that when I ran the code with async Task rather than void I got an immediate block from TouchRunner without even adding any other code other than the API call! This was a red flag I suppose, but using async void "seemed" to allow "standard" async testing, so I progressed and then ended up in the loop above.
As TouchRunner has not been updated in a very long time I have just spent time re-creating the test project using XUnit after various suggestions to try it in the forums and on stack.
https://github.com/xunit/devices.xunit - runners for Xamarin IOS + Android
https://xunit.github.io/docs/comparisons - to port NUnit syntax
Some other useful links are -
https://xunit.github.io/docs/getting-started-devices.html
https://gregshackles.com/testing-xamarin-apps-getting-started-with-xunit/
https://oren.codes/2014/07/10/getting-started-with-xunit-for-xamarin/
RESULT: I am very pleased to say all the above code now works for both the TaskCompletionSource and the AutoResetTask scenarios
I can now safely test my event based API :)
I just wanted to ensure other users are aware of this.
Thanks for your help.
One observation is that the test should be async Task and not async void ie
public async Task AuthenticateUserAsyncTest() {
//...code removed for brevity.
}
async void is a fire and forget so any exceptions thrown wont happen in the current context so they wont be caught.
Reference Async/Await - Best Practices in Asynchronous Programming

Can't create handler inside thread which has not called Looper.prepare() [xamarin]

So i don't actually have a question because i've already solved it, but in case someone else runs into this issue it's always nice to have a neat solution.
And while there is a plentitude of "Can't create handler inside thread which has not called Looper.prepare()" - questions there is none tagged with xamarin. (so theirs is all java and i had 0 matches for "Can't create handler inside thread which has not called Looper.prepare() [xamarin]")
The issue is generated because You tried to do work on UI from other thread. If you want to change UI, Must call UI changes from UI thread.
Xamarin Android:
activity.RunOnUiThread(() =>
{
// Write your code here
});
Xamarin IOS:
nsObject.BeginInvokeOnMainThread(() =>
{
// Write your code here
});
Xamarin Forms:
Device.BeginInvokeOnMainThread(() =>
{
// Write your code here
});
public static class PageExtensions
{
public static Task<bool> DisplayAlertOnUi(this Page source, string title, string message, string accept, string cancel)
{
TaskCompletionSource<bool> doneSource = new TaskCompletionSource<bool>();
Device.BeginInvokeOnMainThread(async () =>
{
try
{
var result = await source.DisplayAlert(title, message, accept, cancel);
doneSource.SetResult(result);
}
catch (Exception ex)
{
doneSource.SetException(ex);
}
});
return doneSource.Task;
}
}
Finally i had a case for using TaskCompletionSource to solve an issue.
Very similar actually happend to me. Previous evening I was developing and testing my app. Next morning, from other computer I got the exception you described. I was remembered from a official Xamarin.Forms documentation that sometimes a bin and obj folder removal solves lot of issues.
I did exactly the same, removed my bin and obj folder from my shared Xamarin.Forms library and also from Xamarin.Android library.
The strange exception disappeared.

Can I pass an async delegate to IMvxMessenger.SubscribeOnMainThread()?

I'm using Xamarin and Mvvmcross to write an Android app. I have a situation where I'm using an IMvxMessenger message to kick off some work. The work involves some async tasks which I'm "await"ing. Is this ok? Example is like the code below.
Mvx.Resolve<IMvxMessenger>().SubscribeOnMainThread<AndroidEmailServiceStartedMessage>
(
async msg =>
{
await DoDownloadRequests(CurrentRequests);
}
);

Resources