Is it possible to navigate from webbrowser NavigationFailed event? - c#

private void webBrowser_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
Debug.WriteLine("Navigation Failed");
if (!Utils.IsNetworkAvailable())
{
MessageBoxResult result = MessageBox.Show("Please go to Settings and enable your network connection.",
"No network connection", MessageBoxButton.OK);
if (result == MessageBoxResult.OK)
{
Dispatcher.BeginInvoke(() =>
NavigationService.Navigate(new Uri("/TutorialPage.xaml", UriKind.Relative))); //TODO: Doesnt work
}
}
}
Is this posible? i want go to previous xaml page not webpage.
Thank you in advance.

I've tried your code and it runs ok. Here is my simple example. You can Navigate in NavigationFailedEvent - the problem is that you never get there.
As I've tried the problem mostly concerns Emulator - probably due to how internet connection is realized. For example:
web.Navigate(new Uri(#"http://nosite.azd", UriKind.Absolute));
this Navigation hadn't failed on my Emulator (I was redirected somewhere), but as I've tested it on the Device - it failed.
So try to test your App on device. But IMO it will be much better to check for the internet connection before Navigating (Loading Webbrowser) rather that waiting Navigation to Fail (it can be an additional check up).
Also you don't need to Navigate via Dispatcher as your code runs on main thread.

Related

Can I know if my app is allowed to pair with unpaired devices in UWP?

I am using BluetoothLEAdvertisementWatcher to watch for Bluetooth low energy beacons.
If user has disabled option "Communicate with unpaired devices" (ms-settings:privacy-customdevices), my app will never get any beacon.
Is it possible to check if this option is enabled, or ask user to enable this option?
I haven't found a way to check directly, but if the user disables this option, calling the Start method of the watcher, it will immediately be aborted with error code DisabledByUser. You can see this in action in the Bluetooth Advertisment sample in UWP samples repo.
You can subscribe to the Stopped event on the watcher and then check the BluetoothLEAdvertisementWatcherStoppedEventArgs.Error to see if the user disabled it:
private async void OnAdvertisementWatcherStopped(
BluetoothLEAdvertisementWatcher watcher,
BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs)
{
if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Aborted)
{
if (eventArgs.Error == BluetoothError.DisabledByUser)
{
// do something - show dialog to open settings, etc.
}
}
}
You can ask the user to enable the app access with a dialog message and redirect them to the Settings app by executing Launch.LaunchUriAsync("ms-settings:privacy-customdevices").

Manual check for updates with WPF ClickOnce

I do not want to used the default behavior of ClickOnce, which presents a dialog window, checking for updates, I want to check for update manually
After search on the internet I found:
try
{
var deploy = ApplicationDeployment.CurrentDeployment;
if (deploy.CheckForUpdate())
MessageBox.Show("There is a new update");
else
MessageBox.Show("You using the latest version");
}
catch (Exception e2)
{
MessageBox.Show(e2.ToString());
}
When I install the application and want to check for update I got the error:
system.deployment.application.trustnotgrantedexception: user has refused to grant required permissions to the application
Could you help please.
Thanks in advance.
Right Click on your project. Select Properties. Then go to publish Tab. Click updates. Then uncheck "The application should check for updates".
I'm not really sure why you are getting that error, but I'm also using the same approach. Checking manually for updates. But my application is deployed on a server. I have this timer that checks for new updates every 15 mins.
Here's how I do it.
private void InstallUpdateSyncWithInfo()
{
if (!isNewUpdateMessageShown)
{
try
{
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);
//ad_UpdateCompleted is a private method which handles what happens after the update is done
UpdateCheckInfo info = ad.CheckForDetailedUpdate();
if (info.UpdateAvailable)
{
//You can create a dialog or message that prompts the user that there's an update. Make sure the user knows that your are updating the application.
ad.UpdateAsync();//Updates the application asynchronously
}
}
}
catch (Exception ex)
{
ex.Log();
}
}
}
void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
//Do something after the update. Maybe restart the application in order for the update to take effect.
}
EDIT
I have updated my answer. You can copy and paste this one and adjust it based on your app needs.
On my previous answer, I'm opening a new window that tells the users that there's an update then have the user choose if he or she wants to update the application.

How to suppress push toast notification only when App in foreground?

Note: I have only tested this using the emulator, and pushing toasts using the built in functionality. I am assuming this isn't an emulator issue.
I followed this guide in order to intercept push toast notifications while the app is running. However, I only want to suppress the toast notification when the app is in the foreground. It should still display when another app is in the foreground. So I wrote the following handler in App.xaml.cs (and subscribed to the PushNotificationReceived event):
private async void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string msg = "";
if (e.NotificationType == PushNotificationType.Toast)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (Window.Current.Visible)
{
msg += " Toast canceled.";
e.ToastNotification.SuppressPopup = true;
}
});
if (true) // actually determines if it's a certain type of toast
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ConfirmationContentDialog confirmationDialog = new ConfirmationContentDialog();
confirmationDialog.SetMessage("Please confirm that you like turtles." + msg);
await confirmationDialog.ShowAsync();
});
}
}
}
So this works, in the sense that I only see the "toast canceled" message when the app was in the foreground when receiving the push notification. When I'm on the start screen or somewhere else I always get the toast. This is good. However, when the app is in the foreground, sometimes (usually after sending the second push) the toast shows up anyway (even though "Toast canceled" displays). But sometimes it doesn't. It's rather inconsistent.
This is leading me to believe that due to the await, sometimes the toast gets through before the code gets run on the UI thread to check whether the app is visible or not. However, I can't access Window.Current.Visible from here without using the dispatcher. I even tried CoreApplication.MainView.CoreWindow.Visible but that gives me "interface marshalled for different thread etc" exception. Speaking of which, I don't understand how CoreApplication.MainView.CoreWindow.Dispatcher can be called from anywhere but CoreApplication.MainView.CoreWindow.Visible not? How does that even work.
Anyway, how do I fix this? I would like to keep this within App.xaml.cs because I have a number of pages in this app, but this content dialog needs to be shown no matter which page the user is on, and without the user being redirected to a different page. However, I am of course open for new suggestions.
I fixed this as per Kai Brummund's suggestion by using a simple boolean toggle in the App class, and subscribing to the VisibilityChanged event like so:
private bool APP_VISIBLE = true;
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
// Stuff put here by Visual Studio
Window.Current.VisibilityChanged += OnVisibilityChanged;
Window.Current.Activate();
}
private void OnVisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
if (e.Visible)
APP_VISIBLE = true;
else
APP_VISIBLE = false;
}
That way I can use APP_VISIBLE to suppress the popup without having to use the dispatcher and the toast is suppressed immediately.

WP8 custom message box crash

I have made a custom messagebox (discussed here) that shows localized quit prompt.
protected override void OnBackKeyPress(CancelEventArgs e)
{
//some conditions
e.Cancel = true;
string quitText = DeviceWrapper.Localize("QUIT_TEXT");
string quitCaption = DeviceWrapper.Localize("QUIT_CAPTION");
string quitOk = DeviceWrapper.Localize("DISMISS");
string quitCancel = DeviceWrapper.Localize("MESSAGEBOX_CANCEL");
IAsyncResult asyncResult = Guide.BeginShowMessageBox(
quitCaption, quitText, new List<string> { quitOk, quitCancel },
0, MessageBoxIcon.Error, null, null);
asyncResult.AsyncWaitHandle.WaitOne();
int? result = Guide.EndShowMessageBox(asyncResult);
if (result.HasValue && result.Value == 0)
e.Cancel = false;
//some more features
}
It works fine, but it does crash when it's run as stand-alone (without Visual Studio) after few seconds if user doesn't press anything.
I tried reproducing the same crash with phone attached using Release and Debug from Visual Studion, but it's as stable as it can possibly be. It only crashes when app is run from the phone itself.
How do I find the issue? What could be the reason for it? As far as I can tell, I cannot access crash logs on the device.
There should be something with the messagebox logic perhaps?
UPD
Few notes on your suggestion, Neil:
first of all VS warns me "the async method lacks await" stuff.
secondly I am not sure how to return info to "BackKeyPressed" that e.Cancel should equal "false". This should be the safe way to quit an app AFAIK.
And wouldn't we quit the "OnBackKeyPress" method if we run async method from it? That would mean that we can't let it know about our decision (e.Cancel = false).
Or if we don't quit the "OnBackKeyPress" then it could mean this event will stay for too long and the whole purpose is lost - app will be killed, right?
UPD2:
It seems that I am between Scylla and Charybdis: either I show a messagebox and experience crashes in runtime which is discouraged by guidelines, or I don't show a messagebox at all.
I've tried both native MessageBox and my implementation of custom messagebox with localized "Ok" and "Cancel" buttons. They behave the same: either they are synchronous and hang OnBackKeyPress, or they are async and OnBackKeyPress exits before we can let it know about user's decision.
Final decision
Apparently the guidelines state that we shouldn't ask user's confirmation at all.
Since there is no viable way to implement a working quit confirmation messagebox without crashing I've decided to not show it at all.
If you block or delay certain page events for too long, the OS will kill your app as it assumes its crashed...
OnNavigatedTo
OnNavigatedFrom
OnBackKeyPress
In your case, I would recommend putting the custom MessageBox in it's own method, then calling it on the UI thread.
private void customMessageBox()
{
// custom message box code
// use NavigationService.GoBack() if you need to exit
}
protected override void OnBackKeyPress(CancelEventArgs e)
{
e.Cancel = true;
Deployment.Current.Dispatcher.BeginInvoke(() => customMessageBox() );
}
I also found another answer which accomplishes the thing by making the method Async.
Debugger attached (or not)
When the Visual Studio debugger is attached, the OS does not warn you of certain errors such as high memory usage, page init delays, etc - so it is very important to test your app without the Visual Studio debugger attached either on device or in the emulator (Debug or Release)
Windows Phone 8.1
Be aware that the handling of the Back button has changed in WP8.1 XAML/WinRT apps. It might be something to consider if you're upgrading the app project in future.
I implemented this in my project and it worked. Try it!
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
e.Cancel = true;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBoxResult result = MessageBox.Show("Hello", "Msg Box", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//Do something
}
else
{
//Do something
}
});
}

How to display a message in Windows Store Apps?

How to display a message box in windows 8 apps using c# like calling MessageBox.Show() in windows phone 7?
MessageDialog msgDialog = new MessageDialog("Your message", "Your title");
//OK Button
UICommand okBtn = new UICommand("OK");
okBtn.Invoked = OkBtnClick;
msgDialog.Commands.Add(okBtn);
//Cancel Button
UICommand cancelBtn = new UICommand("Cancel");
cancelBtn.Invoked = CancelBtnClick;
msgDialog.Commands.Add(cancelBtn);
//Show message
msgDialog.ShowAsync();
And your call backs
private void CancelBtnClick(IUICommand command)
{
}
private void OkBtnClick(IUICommand command)
{
}
P.S. You can follow this tutorial for more.
The MessageDialog class should fit your needs.
My simpler way, for confirmation type message boxes:
var dlg = new MessageDialog("Are you sure?");
dlg.Commands.Add(new UICommand("Yes", null, "YES"));
dlg.Commands.Add(new UICommand("No", null, "NO"));
var op = await dlg.ShowAsync();
if ((string)op.Id == "YES")
{
//Do something
}
For simpler way, Just to display the message text and OK button. Use Windows.UI.Popups namespace. Create a method messagebox() that method should be
using Windows.UI.Popups;
protected async void messageBox(string msg)
{
var msgDlg = new Windows.UI.Popups.MessageDialog(msg);
msgDlg.DefaultCommandIndex = 1;
await msgDlg.ShowAsync();
}
Then call this method in your code like
messageBox("Unexpected error held");
Additional tidbit:
It appears in a modern Windows App a MessageDialog will not show prior to your app making its Window.Current.Active() call, which usually happens in the app class' OnLaunched() method. If you're trying to use MessageDialog to display something like a start-up exception, that's important to keep in mind.
My testing indicates MessageDialog.ShowAsync() may actually await but without the dialog being shown if Window.Current.Active() hasn't been called yet, so from a code execution standpoint it'll look like everything is working but yet no dialog is displayed.
If the goal is to display an exception during start-up, I can think of two options (there may be more).
Capture the exception information and then wait to display it until after Window.Current.Activate(). This can work if the exception is such that the application can recover from it and continue with start-up. For example, if there is an error restoring saved state information the app might want to report that to the user but then continue to start-up as if there was no saved state.
If the situation is such that the app is throwing up its hands and intending to terminate, but wants to let the user know what happened, then another solution might be to have a separate dedicated code block/method that plugs a new clean frame into Windows.Current.Content, activates it using Windows.Current.Activate(), and then invokes MessageDialog.ShowAsync(). I haven't experimented with this approach so I'm not sure if other conditions also need to be met like possibly loading a page into the frame.
use for page like:
private async void AppBarButton_Click(object sender, RoutedEventArgs e)
{
Windows.UI.Popups.MessageDialog a = new Windows.UI.Popups.MessageDialog("hello this is awth");
await a.ShowAsync();
}

Categories

Resources