Make app exit in OnBackButtonPressed method for xamarin forms - c#

I have an application in which user logins. Now I want that user can't go back to the menu after he presses the logout button.
This is my logout method
public async void OnLogoutButtonClicked(object sender, EventArgs e)
{
App.AuthenticationClient.UserTokenCache.Clear(Constants.ApplicationID);
await Navigation.PushAsync(new LoginPage());
}
So after logout button is clicked it pushes the user to login page.
I'm able to disable the back button using this in login page
protected override bool OnBackButtonPressed()
{
return false;
}
But it makes my app feel not responsive, instead, I want that when the back button is pressed my app should close the application.
I tried this
protected override bool OnBackButtonPressed()
{
return exit();
//
// exit()
}
but it returns boolean, what should I do to make it work?

When the user logs out, you generally don't want to push a new page on the existing navigation stack. The current navigation stack is not longer applicable, so should be discarded, much like how you clear the UserTokenCache.
So your logout method should be more like:
public async void OnLogoutButtonClicked(object sender, EventArgs e)
{
App.AuthenticationClient.UserTokenCache.Clear(Constants.ApplicationID);
Application.Current.MainPage = new LoginPage();
}
Basically, create the new LoginPage and set up a new MainPage, just as though the app were starting and first presenting the user with a LoginPage.
If you do that, then the back button can't get back to the menu, because that whole navigation stack is gone.

Related

Back button navigation closes my app on Windows 10 Mobile

I have an app and it works as expected on Windows 10. But on Windows 10 Mobile, when user presses back button, application closes. In my back requested event handler I even commented out GoBack() method but app still closes.
private void MobileNavigationService_BackRequested(object sender, BackRequestedEventArgs e)
{
e.Handled = true;
var navigationService = UnityConfiguration.Resolve<IMobileNavigationService>();
if (navigationService.CanGoBack())
{
//navigationService.GoBack();
}
}
I have a feeling that even though I set e.Handled = true it ignores it and acts like there is no handler.
Updated
As an additional information
App has only one page, Shell. it has common things like menu and title bar. It also has frame. In frame I open all the other pages. So going back, for my app, means going back in that frame, not in entire application. I want to override default behavior.
Setting up an event handler for BackRequested and to navigate back in the page stack.
Enabling and disabling the title bar back button based on the app's internal page stack.
You can get this DEMO from Microsoft in GitHub
Back Button Sample
protected override void OnNavigatedTo(NavigationEventArgs e)
{
bool optedIn = false;
if ((bool)e.Parameter)
{
optedIn = true;
}
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack && optedIn)
{
// If we have pages in our in-app backstack and have opted in to showing back, do so
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}
else
{
// Remove the UI from the title bar if there are no pages in our in-app back stack
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}

How to override back button for a page outside of it?

I know how to override back button inside a page:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
//Do your work here
base.OnBackKeyPress(e);
}
But the problem: I use Inneractive ad service. when I call InneractiveAd.DisplayAd() it shows a new page of its own which doesn't support back button. when it navigate to this page its uri is like this:
/Inneractive.Ad;component/InneractiveFullScreenPage.xaml
The question: is it possible to override back button of that page to navigate back when user presses back?
In HandleBackKeyPress you usually intercept BackKeyPress event, so you would set e.Cancel = true to prevent standard BackKey navigation. To simulate standard navigation you would do something like:
void HookUpBackKeyPress(PhoneApplicationPage page)
{
page.BackKeyPress += HandleBackKeyPress;
}
void HandleBackKeyPress(object sender, CancelEventArgs e)
{
page.NavigationService.GoBack();
}
The problem is to get the reference to the navigated page. The following code will work only after you completely Navigated to the new Page and it might not work when immediately after NavigationService.Navigate(..)
var frame = (PhoneApplicationFrame)Application.Current.RootVisual;
page = (PhoneApplicationPage)frame.Content;

Windows Phone 8 Back button to go back in WebBrowser

I made a WebBrowser and it works except the back button after pressing the back button the app closes and does not go back one in history. How can I solve the problem? I found solutions in the internet but they don't seem to work.
public MainPage()
{
this.InitializeComponent();
this.webBrowser.Navigate(new Uri("http://www.google.com", UriKind.Absolute));
this.webBrowser.LoadCompleted += webBrowser_LoadCompleted;
this.webBrowser.NavigationFailed += webBrowser_NavigationFailed;
this.webBrowser.IsScriptEnabled = true;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
webBrowser.InvokeScript("eval", "history.go(-1)" );
}
P. S.:that is not the whole script but i think the rest is unneccesary if not tell me :)
P. P. S.:I'm new to Windows Phone programing.
Web browser is just a control inside the page and pressing the device back button navigates back to the previous page or exits the app if it has only one page. So, you would need to stop page navigation on back key press something like this.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel=true;
}
This prevents a backnavigation
Now rest is to go to the previous page which can be done by
webBrowser.InvokeScript("eval", "history.go(-1)" );
so the event becomes
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel=true;
webBrowser.InvokeScript("eval", "history.go(-1)" );
}
Try to do:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
WB1.InvokeScript("eval", "history.go(-1)");
e.Cancel = true;
}
When you override OnBackKeyPress, and you don't perform e.Cancel = true; it will do your code, but will also do what normal BackButton does - NavigateBack, Exit App and so on. But you must remember to leave the User an ability to exit your App or Navigate Back, so it will be more suitable to check some conditions (e.g. your webbrowser history is not null) and then do e.Canel, otherwise Exit the App.
To exit the app when you are in the root (so you can approve the cerfitication requirements), and also go back in navigation until you are in the root, try with this
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (MiniBrowser.CanGoBack){
e.Cancel = true;
MiniBrowser.InvokeScript("eval", "history.go(-1)");
}
}

Silverlight callback mystery behavior

I am writting this method to track if changes occured on a page so the user can trigger a reload of a dependent system. So this as you can see triggers when the user is trying to navigate away from the page. If the e.Cancel is not there the behavior seems fine the async web-service call happen as expected but I am not sure what is really happening in the back.
The reload button click method triggers a chain of event that usually update the display but since the user has navigated away from the page the components are no longer visible. Can this cause problems to the application? Should I be forcing the user to remain on the same page just to prevent possible callback problems?
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (hasDataBeenModified)
{
if (System.Windows.Browser.HtmlPage.Window.Confirm("You have not reloaded the policies\nDo you want to do it now?"))
{
//e.Cancel = true;
ReloadButton_Click(null, null);
}
}
}
Instead of using OnNavigatingFrom, use OnBackKeyPress
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (hasDataBeenModified)
{
if (System.Windows.Browser.HtmlPage.Window.Confirm("You have not reloaded the policies\nDo you want to do it now?"))
{
e.Cancel = true;
ReloadButton_Click(null, null);
}
}
}

ASP.net page_load doesn't detect session

I have a problem with using session variable in the page_load. I have a page (members.aspx) which is a members area.
If the user isn't logged in, it will display a form asking them to login. The form submits their details, checks if ok then sets session variables if OK. It then reloads the page.
So if the user has authenticated correctly, it sets Session["memberLoggedIn"] = true.
My page_load function then looks like this
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) {
Response.Write("OK");
}
}
There is more code, but essentially, the "OK" should be written. However, it doesn't appear. Even though the session IS set. If I go to the page directly it will then show. It's just for the reloading of the members page from the initial login which stops it.
any ideas?!
======================
the code to set the session is
if (logindetails.Count > 0) {
System.Data.DataRow details = logindetails[0];
Session["memberLoggedIn"] = true;
}
I then just check if (Convert.ToBoolean(Session["memberLoggedIn"]) == true) on all my pages. To be honest it doesn't seem that reliable and I Think sometimes I need to understand the order in which pages are loaded as when I destroy the session on the log out page, some parts still show the logged in features! (but that's another story....)
try this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var user = HttpContext.Current.User;
if(user.Identity.IsAuthenticated)
{
Session["memberLoggedIn"] = true;
Print();
}
}
}
public void Print()
{
if (Convert.ToBoolean(Session["memberLoggedIn"]) == true)
{
Response.Write("ok");
}
}
This sounds like when you log in you are choosing whether to write "OK" before you have processed the login. In terms of the page's pipeline page_load is before your event handler that you are likely processing the login.
You have various options, the simplest of which could be to move this particular logic to Page_PreRender (if it makes sense to) as at this point your session variable will have been set.

Categories

Resources