Navigate to page on start in .NET Maui app - maui

Seems like a simple question, but I haven't been able to find a simple answer. Essentially I want to choose which page in the app to start on based on some stored state. I added a GoToAsync call in the AppShell constructor, but this didn't work--which makes sense because the AppShell hasn't been fully constructed yet.
I found this answer, but it feels like it kind of skirts around the issue:
Maui AppShell - Navigate on Open
Where is the best place to inject some code that will run once on startup and can successfully navigate a .NET Maui app to a chosen page?

After playing around with overrides, it seems like overriding Application.OnStart works! Shell.Current is set at this point and navigation works.
Here's additional code that allows for asynchronous initialization and uses a Loading Page until the initialization is complete:
using MyApp.Services;
using MyApp.UI;
namespace MyApp;
public partial class App : Application
{
ConfigurationProviderService m_configProvider;
public App(ConfigurationProviderService configProvider)
{
m_configProvider = configProvider;
InitializeComponent();
MainPage = new LoadingPage();
}
protected override void OnStart()
{
var task = InitAsync();
task.ContinueWith((task) =>
{
MainThread.BeginInvokeOnMainThread(() =>
{
MainPage = new AppShell();
// Choose navigation depending on init
Shell.Current.GoToAsync(...);
});
});
base.OnStart();
}
private async Task InitAsync()
{
await m_configProvider.InitAsync();
}
}

Related

Where is good place to register Messenger responsible for showing Windows to ensure MVVM pattern Separation of Concerns and Testability not violated?

Scenario:
MainWindow has a Menu About which relates to AboutWindow.
About Meny is triggered by command:
<MenuItem Header="_About" Command="{Binding OpenAbout}"/>
OpenAbout is property like that:
private RelayCommand _openAbout;
public RelayCommand OpenAbout
{
get
{
return _openAbout ?? (_openAbout = new RelayCommand(() => Messenger.Default.Send(new NotificationMessage("ShowAboutView"))));
}
}
Notification message is registered in App.cs class as follows:
static App()
{
DispatcherHelper.Initialize();
}
public App()
{
RegisterMessenger();
}
public void RegisterMessenger()
{
Messenger.Default.Register<NotificationMessage>(this, ProcessShowAboutView);
}
private void ProcessShowAboutView(NotificationMessage message)
{
AboutWindow view = new AboutWindow();
view.Show();
}
I analysed another questions like that:
How to open a new window using MVVM Light Toolkit
WPF MVVM - How to Show a view from MainWindowViewModel upon Clicking on button
I like Messenger functionality but however I am not sure If above solution is a good one.
I would be thankful for any advise!
As depicted above, Registering messages is done in App Config.
I consider it not be a good place therefore I need to know what place would be better.
Another place to consider would be Locator
I personaly would register the messages in App.xaml.cs in the OnStartup method (WPF) and in the set up method of the unit test (dont forget to unregister everything in the tear down method).

MvvmCross navigation on screen

Our designer created a layout something like the screen above. The main idea was to create an application with only one screen, just the red part of the screen is changing (i.e. 2 textbox instead of 1 textbox) when you tap on a button. This application will be a multiplatform application and I'm using MvvmCross to create it. My question is that how can i achieve this behavior in Mvvm? My first thought was sg. like the code below, but I'm not satisfied with this solution. Do you have any better solution to this problem? Should i somehow overwrite default navigation on ShowViewModel()?
public class MainViewModel : MvxViewModel
{
private MvxViewModel _currentViewModel;
public MvxViewModel CurrentViewModel
{
get { return _currentViewModel; }
set { _currentViewModel = value; RaisePropertyChanged(() => CurrentViewModel); }
}
public MainViewModel()
{
CurrentViewModel = new DefaultViewModel();
}
public void OnButtonClick()
{
CurrentViewModel = new SecondViewModel();
}
}
public partial class MainViewModel : MvxViewController
{
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
FirstViewModel.WeakSubscribe(ViewModelPropertyChanged);
}
private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "CurrentViewModel")
{
if (Model.CurrentViewModel != null)
{
if (Model.CurrentViewModel is SecondViewModel)
{
//remove bindings
//change View
//bind new viewmodel
}
}
}
}
The alternatives for this kind of 'non-page navigation' are similar to those in MvvmCross Dialog:
You can:
Customize the MvxPresenter to allow ShowViewModel to be used
Put a special interface in the Core project and use Inversion of Control to inject the implementation from the UI project to the Core project
Use the MvxMessenger plugin and share messages between the Core and UI project which trigger this type of navigation.
Use a property with a special interface (like IInteractionRequest) on the ViewModel - that property will fire an event when the UI needs to change.
Personally, for your situation, I quite like the first of these options - intercepting ShowViewModel using a presenter.
One other alternative which I might consider is to use some kind of 'Adapter-driven' control which could very easily update it's child contents based on the CurrentViewModel property. On Android, this would be as easy as using an MvxLinearLayout with an adapter. On iOS, however, I think you'd have to write something new to do this - just because iOS doesn't really have a LinearLayout/StackPanel control.

Show AlertDialog from ViewModel using MvvmCross

I am using MvvmCross for creation my Android-app and I faced with the following problem:
When I'm trying to show AlertDialog, that was created in ViewModel, the
"Unhandled Exception: Android.Views.WindowManagerBadTokenException" appears.
public class MyViewModel : MvxViewModel
{
public ICommand ShowAlertCommand { get; private set; }
public AuthorizationViewModel()
{
ShowAlertCommand = new MvxCommand(() =>
{
var adb = new AlertDialog.Builder(Application.Context);
adb.SetTitle("Title here");
adb.SetMessage("Message here");
adb.SetIcon(Resource.Drawable.Icon);
adb.SetPositiveButton("OK", (sender, args) => { /* some logic */});
adb.SetNegativeButton("Cancel", (sender, args) => { /* close alertDialog */});
adb.Create().Show();
});
}
}
When I was researching I have found that it happens because of transmission of the reference to the Context but not on the Activity in the AlertDialog.Builder.
In this topic I found the following decision:
Receive references to the current Activity through the use of GetService(), but I didn't found mvvmcross plugins for work with IMvxServiceConsumer, IMvxAndroidCurrentTopActivity interfaces.
My question is can I show AlertDialog from ViewModel? And how can I get the reference to Activity, but not to the Application.Context?
And what is the correct way to close AlertDialog that the user would stay on the current View?
In general, you should try not to put this type of code into ViewModels
because ViewModels should stay platform independent
because ViewModels should be unit testable - and it's hard to unit test when the code shows a dialog
I'd also recommend you don't put code like this inside a ViewModel Constructor - these constructors are generally called during navigations and displaying a Dialog during a transition is likely to be problematic.
With those things said, if you do want to get hold of the current top Activity within any code, then you can do this using the IMvxAndroidCurrentTopActivity
public interface IMvxAndroidCurrentTopActivity
{
Activity Activity { get; }
}
Using this, any code can get the current Activity using:
var top = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
var act = top.Activity;
if (act == null)
{
// this can happen during transitions
// - you need to be sure that this won't happen for your code
throw new MvxException("Cannot get current top activity");
}
var dlg = new AlertDialog.Builder(act);
//...
dlg.Create().Show();
The use of IMvxAndroidCurrentTopActivity is discussed in MvvmCross: How to pass Android context down to MvxCommand?
The approach taken in that question/answer is also one of the ways I would generally approach showing dialogs from a ViewModel:
I would create an IFooDialog interface
Ideally I would probably make this interface asynchronous - e.g. using async or using an Action<DialogResult> callback parameter
on each platform I would implement that in the UI project
the ViewModels can then use IFooDialog when a dialog is needed and each platform can respond with an appropriate UI action
This 'Dialog Service' type of approach is common in Mvvm - e.g. see articles like http://www.codeproject.com/Articles/36745/Showing-Dialogs-When-Using-the-MVVM-Pattern (although that article is very Windows specific!)
There are also a few other questions on here about MvvmCross and dialogs - although they may contain reference to older v1 or vNext code - e.g. Alerts or Popups in MvvmCross and Unable run ProgressDialog - BadTokenException while showind

MvvmCross: How to navigate to something besides a ViewModel?

What would I put in my MvxCommand to navigate to a simple URL? All mobile platforms have a mechanism to ask the OS for an Activity or ViewController that can display the contents of a URL. How would I do that with MvvmCross? One way that I know of is to put special stuff in the presentationBundle and/or parameterBundle when calling ShowViewModel that the presenter can detect to do the special OpenUrl command. But is that the best way??
There is a plugin which enables this - https://github.com/slodge/MvvmCross/tree/v3/Plugins/Cirrious/WebBrowser
If that plugins is loaded, then a viewmodel can use:
public class MyViewModel : MvxViewModel
{
private readonly IMvxWebBrowserTask _webBrowser;
public MyViewModel(IMvxWebBrowserTask webBrowser)
{
_webBrowser = webBrowse;
}
public ICommand ShowWebPage
{
get { return new MvxCommand(() => _webBrowser.ShowWebPage("https://github.com/slodge/mvvmcross");
}
}
You can see this used in, for example:
https://github.com/slodge/MvvmCross-Tutorials/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.Core/ViewModels/BaseViewModel.cs
https://github.com/slodge/MvvmCross-Tutorials/blob/master/Sample%20-%20CustomerManagement/CustomerManagement/CustomerManagement/ViewModels/DetailsCustomerViewModel.cs
If you ever need to create your own plugins, see https://speakerdeck.com/cirrious/plugins-in-mvvmcross

GWT TestCase: Simulating clicking a button on my page

I'm using GWT 2.4 with JUnit 4.8.1. When writing my class that extends GWTTestCase, I want to simulate clicking on a button on the page. Currently, in my onModuleLoad method, this button is only a local field ...
public void onModuleLoad() {
final Button submitButton = Button.wrap(Document.get().getElementById(SUBMIT_BUTTON_ID));
...
// Add a handler to send the name to the server
GetHtmlHandler handler = new GetHtmlHandler();
submitButton.addClickHandler(handler);
How do I simulate clicking on this button from the GWTTestCase? Do I have to expose this button as a public member accessor is there a more elegant way to access it? Here is what I have in my test case so far ...
public class GetHtmlTest extends GWTTestCase {
// Entry point class of the GWT application being tested.
private Productplus_gwt productPlusModule;
#Override
public String getModuleName() {
return "com.myco.clearing.productplus.Productplus_gwt";
}
#Before
public void prepareTests() {
productPlusModule = new Productplus_gwt();
productPlusModule.onModuleLoad();
} // setUp
#Test
public void testSuccessEvent() {
// TODO: Simulate clicking on button
} // testSuccessEvent
}
Thanks, - Dave
It can be as easy as buttonElement.click() (or ButtonElement.as(buttonWidget.getElement()).click(), or ButtonElement.as(Document.get().getElementById(SUBMIT_BUTTON_ID)).click())
But remember that a GWTTestCase doesn't run in your own HTML host page, but an empty one, so you'll first have to insert your button within the page before simulating your module's load.
gwt-test-utils seems to be the perfect framework to answer your need. Instead of inheriting from GWTTestCase, extend the gwt-test-utils GwtTest class and implement your click test with the Browser class, like shown in the getting starting guide :
#Test
public void checkClickOnSendMoreThan4chars() {
// Arrange
Browser.fillText(app.nameField, "World");
// Act
Browser.click(app.sendButton);
// Assert
assertTrue(app.dialogBox.isShowing());
assertEquals("", app.errorLabel.getText());
assertEquals("Hello, World!", app.serverResponseLabel.getHTML());
assertEquals("Remote Procedure Call", app.dialogBox.getText());
}
If you want to keep your button private, you'd be able to retrieve it by introspection. But my advice is to make you view's widgets package protected and to write your unit test in the same package so it could access them. It's more convinent and refactoring-friendly.
gwt-test-utils provide introspection convinence. For example, to retrieve the "dialogBox" field which could have been private, you could have do this :
DialogBox dialogBox = GwtReflectionUtils.getPrivateFieldValue(app, "dialogBox");
But note that using GwtReflectionUtils is not mandatory. gwt-test-utils allows you to use ANY java classes in GWT client side tests, without restriction :)
You can do it like this:
YourComposite view = new YourComposite();
RootPanel.get().add(view);
view.getSubmitButton.getElement().<ButtonElement>cast().click();