Auto dismiss Login page when logged - windows-phone-8

I have the following page navigation in my app:
AnyPage -> Login -> Register
When the user gets registered he is automatically logged to. So I want the Login page to be closed automatically if the user go back to it and is logged.
I tried to add some code to the LoginPage.onNavigatedTo method but it doesn't work.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
if(AccountController.isLogged()){
Frame.GoBack();
}
}
How can I do it?

The OnNavigatedTo and OnNavigatedFrom methods are part of the ongoing navigation operation. When you try to start a new navigation while there is one in progress, navigation methods will stop and return false.
Simple trick is: Make your OnNavigatedTo async and add a delay before navigating back.
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
if(AccountController.isLogged()){
await Task.Delay(1);
Frame.GoBack();
}
}
The reason this works is: Navigation is handled on the UI Thread. As the Event Methods are void returning, they are not awaited and if you return a task inside of them, the current caller finishes his current task. Whatever comes after the await is queued to the Dispatcher and finished once he has time for it (which is immediately after the navigation operation finishes).

Related

How to save video when recording is interrupted by sending the application to background on windows phone 8

I am expermenting with video recording on Windows Phone 8. I want to handle the situation when user is putting my app to background, while it is recording a video. I would like to save the already recorded video before quitting.
I am handling this situation using the code from this example:
https://msdn.microsoft.com/en-us/library/windows/apps/mt243896.aspx
private async Task StopRecordingAsync()
{
try
{
Debug.WriteLine("Stopping recording...");
_isRecording = false;
await _mediaCapture.StopRecordAsync();
Debug.WriteLine("Stopped recording!");
}
catch (Exception ex)
{
Debug.WriteLine("Exception when stopping video recording: {0}", ex.ToString());
}
}
I am calling this method from the:
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
But the video is not being saved. In the debug console I get only the first message: "Stopping recording...", but there is no "Stopped recording!" message logged. It seems like the resources are being destroyed before I can handle them.
When your app is moved to the background you only have a short amount of time to run code.
Instead of having saving be triggered when you navigate from the page, instead look at the Application.Suspending event which allows you to use a deferral to try and run your code for a bit longer so you can finish tidying up before your app loses it's resource allocation.
Something like:
async protected void OnSuspending(object sender, SuspendingEventArgs args)
{
SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
await StopRecordingAsync();
deferral.Complete();
}

Windows Phone, Prism.StoreApps: How to avoid activation of a certain page after suspension or termination?

I do want to ensure that in case an app is navigated to a certain page, the app is on another (in my case the previous) page after it was suspended or terminated. In my case the page is for taking photos. I do not want the user to return to this page after the app was in the background since it has no context information. The context information is on the previuos page.
How could I achieve this with Prism.StoreApps?
Background: If an app was just suspended the state of the app remains after it was resumed, hence the last active page is active again. I have no real idea how to set another page active in this case. If an app was terminated Prim.StoreApps restores the navigation state and navigates to the last active view model (hence to the last active page). I do not know either how to alter the navigation state in this case so that another page is navigated to.
In the meantime I fond a working solution myself. Might not be the best and there might be better solutions, but it works.
For resuming the app I handle the Resuming event:
private void OnResuming(object sender, object o)
{
// Check if the current root frame contains the page we do not want to
// be activated after a resume
var rootFrame = Window.Current.Content as Frame;
if (rootFrame != null && rootFrame.CurrentSourcePageType == typeof (NotToBeResumedOnPage))
{
// In case the page we don't want to be activated after a resume would be activated:
// Go back to the previous page (or optionally to another page)
this.NavigationService.GoBack();
}
}
For the page restore after termination I firstly use a property in the App class:
public bool MustPreventNavigationToPageNotToBeResumedOn { get; set; }
public App()
{
this.InitializeComponent();
// We assume that the app was restored from termination and therefore we must prevent navigation
// to the page that should not be navigated to after suspension and termination.
// In OnLaunchApplicationAsync MustPreventNavigationToPageNotToBeResumedOn is set to false since
// OnLaunchApplicationAsync is not invoked when the app was restored from termination.
this.MustPreventNavigationToPageNotToBeResumedOn = true;
this.Resuming += this.OnResuming;
}
protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
// If the application is launched normally we do not prevent navigation to the
// page that should not be navigated to.
this.MustPreventNavigationToPageNotToBeResumedOn = false;
this.NavigationService.Navigate("Main", null);
return Task.FromResult<object>(null);
}
In OnNavigatedTo of the page I do not want to be activated on a resume I check this property and simply navigate back if it is true (and set the property to false to allow subsequent navigation):
public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode,
Dictionary<string, object> viewModelState)
{
if (((App)Application.Current).MustPreventNavigationToPageNotToBeResumedOn)
{
// If must prevent navigation to this page (that should not be navigated to after
// suspension and termination) we reset the marker and just go back.
((App)Application.Current).MustPreventNavigationToPageNotToBeResumedOn = false;
this.navigationService.GoBack();
}
else
{
base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
}
}

Keyboard overlaps popup in wp8

I am developing a Login screen in which the user needs to introduce their data and then submit them.
Considerations which I had: I have thought about using a Page, but eventually I rejected the idea because if I put Login page before the MainPage, then if I go back from MainPage, then it would go to Login page, which is not what I want. And if Login page were after MainPage, then if I execute for instance the app for first time, without being logged in, if I press back, then it would go to MainPage which I don't want as well.
The problem: I decided finally to use a Popup. At the moment looks perfect, but when I want to use a textbox, the Keyboard overlaps that textbox, and what I want is to move the Popup upwards just like a normal page. I don't know if is that possible, otherwise I am willing to hear some alternatives.
Thank you in advance.
In WMAppManifest.xml remove the property of Navigation Page and in you App.xaml.cs you have something like:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
LoadDefautPage();
}
void LoadDefautPage()
{
if (StartForFirstTime)//tombstone local variable
{
if (!IsLoggedIn)//flag save it in IsolatedStorageSettings
{
RootFrame.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative));
}
else
{
RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
StartForFirstTime = false;
}
}
finally remove Back Entry in MainPage:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
while (this.NavigationService.CanGoBack)
{
this.NavigationService.RemoveBackEntry();
}
}
It's just an idea, let me know how it goes (:

NavigationService remove complete back navigation

Using NavigationService.RemoveBackEntry() I can remove one entry from the navigation stack. Is there a convenient way to remove all back navigation items in my app (scenario: I have a sign-up procedure which consists of multiple pages, and after successful registration I do not want the user to navigate back to the registration steps).
It's not that inconvenient to do that with RemoveBackEntry:
while(NavigationService.CanGoBack)
{
NavigationService.RemoveBackEntry();
}
Or use this, a single line code
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
while (NavigationService.RemoveBackEntry() != null) ;
}

removing mouse events/controls from swing components with glasspane

I have a client-server application and i am using swing in the client side. My swing client has one main window (jframe) and lots of panels, toolbars and menubar in it.
I want to remove all client action/mouse events (or simply grab and do nothing) while client is waiting response from server by means of glasssPane.
Here is the code i wrote:
private final static MouseAdapter mouseAdapter = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
System.out.println("MouseClicked..!");
}
};
private static Cursor WAIT_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
private static Cursor DEFAULT_CURSOR = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
and
public static void startWaitCursor(JComponent comp)
{
MainWindow root = ((MainWindow) comp.getTopLevelAncestor());
root.getGlassPane().setCursor(WAIT_CURSOR);
root.getGlassPane().addMouseListener(mouseAdapter);
root.getGlassPane().setVisible(true);
}
public static void stopWaitCursor(JComponent comp)
{
MainWindow root = ((MainWindow) comp.getTopLevelAncestor());
root.getGlassPane().setCursor(DEFAULT_CURSOR);
root.getGlassPane().setVisible(false);
}
but i am not able to manage the grab mouse events. Changing cursors at the glassPane is working fine but either i am not able to add mouseAdapter or am not able to make glasssPane become to the top level component.
Any idea?
Thanks.
I realized that my code is working but my problem is threading related. My code was something like:
startWaitCursor();
work(); // server request that takes time
stopWaitCursor();
and changed it to:
startWaitCursor();
SwingUtilities.invokeLater(new Runnable() {
poblic void run() {
try
{
work(); // server request
}
finally
{
stopWaitCursor();
}
by doing this modification i could see the settings i made in the startWaitCursor() method while client is waiting response from the server.
But stil there is a small problem. In startWaitCursor() method i desabled key, mouse and focus events for the glass pane but events are still captured by main frame even glassPane is displayed.
addMouseListener(new MouseAdapter() {});
addMouseMotionListener(new MouseMotionAdapter() {});
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
After server response reached to client and stopWaitCursor() method is invoked the events handled in the main frame.
If i disable the main frame of my application while client is waiting than cursor is not being changed to wait_cursor, if i am not disable the main frame then cursor is being changed but the events are queued.
cheers...
After digging swing threads issues couple of days, i finally found the real answer: SwingWorker
Now my final code is something like,
startWaitCursor();
SwingWorker worker = new SwingWorker() {
public Object doInBackground()
{
doWork(); // time consuming server request
return null;
}
public void done()
{
stopWaitCursor();
}
};
worker.execute();
In startWaitCursor() method i set the glasspane visible (with alpha valued background), display a message to warn the user time consuming job is doing, set the cursor to wait_cursor (hourglass) and consume all the key, mouse events. That is it.
And by using SwingWorker my client is actually responsive (it is working as if no server request is made) but since i display the glasspane and consume all key and mouse events it feels like irresponsive.
What a relief.. SwingWorker rocks...
cheers..