Win8 store Application, do some check in the OnNavigatedFrom Method - windows-store-apps

I wanted to do some check, when I click the NavigateButton(Back) to home page.
1.Display the MessageDialog show update the content "yes" or "not"
2.If click yes, update current page.
If click No, do nothing
3.navigate to homepage.
I use below code, but currently it will back to the home page first, and then pop up the message dialog.
how can I let the action that navigate to homepage happened after I clicked the message dialog
protected async override void OnNavigatedFrom(NavigationEventArgs e)
{
MessageDialog md = new MessageDialog("Do you want to save");
md.Commands.Add(new UICommand("Yes", (UICommandInvokedHandler) =>
{
Application.Current.Exit();
//this.UpdateClick();
}));
md.Commands.Add(new UICommand("No"));
var task = md.ShowAsync().AsTask();
await task;
}

OnNavigateFrom is not cancel-able, and happens after the navigation has already occurred.
Rather than having the code, why don't you re-wire the back button to a click handler which pops up the message box? Then when the user clicks a button, you perform the appropriate navigation.
private async void OnBackButtonClick(object sender, RoutedEventArgs routedEventArgs)
{
MessageDialog md = new MessageDialog("Do you want to save");
md.Commands.Add(new UICommand("Yes", uiCommandInvokedHandler =>
{
// Refresh logic
}));
md.Commands.Add(new UICommand("No", uiCommandInvokedHandler =>
{
var rootFrame = (Frame)Window.Current.Content;
rootFrame.Navigate(typeof(MainPage));
}));
await md.ShowAsync();
}

Related

How to run background script of chrome extension on every web page page load?

I have created a background script which runs on short keys and click on the extension icon but, now I want to run it on every web page load.
The background script already loads on every page request. If your looking to update the data between the background script and content script in your background process you need to create two listeners, the second is usefull when multiple tabs are open. Remember data in your popup can be retrieved by simply calling chrome.extension.getBackgroundPage()
background.js
chrome.tabs.onUpdated.addListener(() => {
chrome.tabs.sendMessage(info.tabId, {
message: 'DO_SOMETHING_MESSAGE'
});
})
chrome.tabs.onActivated.addListener(() => {
chrome.tabs.sendMessage(info.tabId, {
message: 'DO_SOMETHING_MESSAGE'
});
})
content.js should function similar to this.
const processContent = () => {
// do whatever here.
let data = {message: UPDATE_BACKGROUND_DATA}
chrome.runtime.sendMessage(data);
}
// run when messages sent from background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'DO_SOMETHING_MESSAGE') {
processContent();
}
});
// run onload
processContent();
And finally, back in your background script create a listener that listens for any updated data.
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.message === UPDATE_BACKGROUND_DATA) {
// update background vars
}
})

How to access Flutter Back button functionality?

I would like to present an AdWords interstitial before the user returns to the previous page. How can I do this when the return button is pressed?
I think you can make use of WillPopScope widget. You can pass a callback function which will be called when the view is about pop. Just do whatever tasks to be completed before pop and then return true.
Example:
Future<bool> _willPopCallback() async {
// await showDialog or Show add banners or whatever
// then
return true; // return true if the route to be popped
}
//then pass the callback to WillPopScope
new WillPopScope(child: new Scaffold(), onWillPop: _willPopCallback)

How to handle user enable location & return to app

My app need to access location service, for that I am asking user to whether to enable location, if user says yes, then I am opening location settings. Upto this is working. But how to detect/handle when user coming from location page to my application page.
Here is my code
private async Task<Geoposition> getCurrentLocation()
{
Geoposition position = null;
Geolocator locator = new Geolocator() { DesiredAccuracyInMeters = 10 };
var flag = true;
try
{
position = await locator.GetGeopositionAsync(TimeSpan.FromHours(1), TimeSpan.FromSeconds(30));
flag = false;
}
catch (Exception uae)
{
}
if (flag)
{
await ShowLocationPage();
}
}
getCurrentLocation method called when page is loaded. If it didnt get user location then ShowLocationPage method get called.
private static async Task ShowLocationPage()
{
ContentDialog cd = new ContentDialog(){
Content = "Application want to access your location. Would you like to turn on Location Services?",
PrimaryButtonText = "Yes",
SecondaryButtonText = "No"
};
var result = await cd.ShowAsync(); if (result == ContentDialogResult.Primary)
{
var x = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
}
}
My problem is how to detect that user return from location page, so I can check for geo-information again.
Best way to get this going is to check if your app get's focus again ( or is resumed ).
With the new wp RT this has changed a bit against wp SL.
A bit to long to explain here in StackO answer, but a very compleet explanation is up here http://www.interact-sw.co.uk/iangblog/2013/07/24/return-xaml-store-app
Some disscussion about it was up on twitter few days back: https://twitter.com/rschu/status/498836593269305344

Message Dialog in Windows Store WITHOUT Async?

So, I'm porting an app over to Windows Store. At the start of the app, I have some code, that asks a question. I DO NOT WANT THE REST OF MY CODE TO FIRE UNTIL I GET A RESPONSE.
I have this:
string message = "Yadda Yadda Yadda";
MessageDialog msgBox = new MessageDialog(message, "Debug Trial");
msgBox.Commands.Add(new UICommand("OK",
(command) => { curSettings.IsTrial = true; }));
msgBox.Commands.Add(new UICommand("Cancel",
(command) => { curSettings.IsTrial = false; }));
await msgBox.ShowAsync();
//... more code that needs the IsTrial value set BEFORE it can run...
When I run the app, the code after the msgBox.ShowAsync() runs, without the correct value being set. It's only after the method finishes that the user sees the Dialog box.
I would like this to work more like a prompt, where the program WAITS for the user to click BEFORE continuing the method. How do I do that?
MessageDialog does not have a non-asynchronous method for "Show." If you want to wait for the response from the dialog before proceeding, you can simply use the await keyword.
Here also is a quickstart guide for asynchronous programming in Windows Store Apps.
I see that your code sample already uses "await". You must also mark the calling function as "async" in order for it to work properly.
Example:
private async void Button1_Click(object sender, RoutedEventArgs e)
{
MessageDialog md = new MessageDialog("This is a MessageDialog", "Title");
bool? result = null;
md.Commands.Add(
new UICommand("OK", new UICommandInvokedHandler((cmd) => result = true)));
md.Commands.Add(
new UICommand("Cancel", new UICommandInvokedHandler((cmd) => result = false)));
await md.ShowAsync();
if (result == true)
{
// do something
}
}

Update panel not showing errors in ASP.NET 3.5

In Visual Studio 2008 if you create a new "Ajax 1.0 Enabled ASP.NET 2.0 Web Application" and paste the following code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="foo" Text="click me" onclick="foo_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
code behind
protected void foo_Click(object sender, EventArgs e) {
throw new Exception("hello");
}
and then click the button, you'll see a javascript alert that says "hello". If you create a .NET 3.5 Web Application and paste the same code in, no alert shows up anymore. What am I missing?
If you just want to fix the browser javascript error and display the exception message to the user, you just need to add this to your Masterpage somewhere after the form declaration:
<!-- This script must be placed after the form declaration -->
<script type="text/javascript">
Sys.Application.add_load(AppLoad);
function AppLoad() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
}
function EndRequest(sender, args) {
// Check to see if there's an error on this request.
if (args.get_error() != undefined) {
var msg = args.get_error().message.replace("Sys.WebForms.PageRequestManagerServerErrorException: ", "");
// Show the custom error.
// Here you can be creative and do whatever you want
// with the exception (i.e. call a modalpopup and show
// a nicer error window). I will simply use 'alert'
alert(msg);
// Let the framework know that the error is handled,
// so it doesn't throw the JavaScript alert.
args.set_errorHandled(true);
}
}
</script>
You do not need to catch the OnAsyncPostBackError even unless you want to customize the message. Go to my blog post if you want more information about this.
There was definately a change between the default behavior in the ASP.NET AJAX Extensions 1.0 and ASP.NET AJAX 3.5. This can been seen by looking at the default endPostBack event handlers for the Sys.WebForms.PageRequestManager. The former version displays the error using an Alert while the later just rethrows the error.
// ASP.NET AJAX Extensions 1.0
function Sys$WebForms$PageRequestManager$_endPostBack(error, response) {
this._processingRequest = false;
this._request = null;
this._additionalInput = null;
var handler = this._get_eventHandlerList().getHandler("endRequest");
var errorHandled = false;
if (handler) {
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, this._dataItems, response);
handler(this, eventArgs);
errorHandled = eventArgs.get_errorHandled();
}
this._dataItems = null;
if (error && !errorHandled) {
alert(error.message);
}
}
// ASP.NET 3.5
function Sys$WebForms$PageRequestManager$_endPostBack(error, executor, data) {
if (this._request === executor.get_webRequest()) {
this._processingRequest = false;
this._additionalInput = null;
this._request = null;
}
var handler = this._get_eventHandlerList().getHandler("endRequest");
var errorHandled = false;
if (handler) {
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
handler(this, eventArgs);
errorHandled = eventArgs.get_errorHandled();
}
if (error && !errorHandled) {
throw error;
}
}
If you want the Alert to appear in your ASP.NET AJAX 3.5 code, you just need to make some small changes.
First, you need to add an handler for the ScriptManager's AsyncPostBackError event and then set the AsyncPostBackErrorMessage.
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message;
}
Then you need to add a handler for the client-side PageRequestManager's endRequest event. In there, you can get the AsyncPostBackErrorMessage set on the server-side and use an Alert to display the message to the user.
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest);
}
function onEndRequest(sender, args)
{
var msg = args.get_error().message;
alert(msg);
args.set_errorHandled(true);
}
I hope this helps.