Toast Notification Arguments Open Web Browser - microsoft-metro

I need to send my toast notification arguments and open a web browser. Here is my code:
private void DoNotification()
{
var notifications = serviceClient.GetNotificationsAsync(App.CurrentRestaurantLocation.ID);
foreach (RestaurantNotification note in notifications.Result)
{
IToastNotificationContent toastContent = null;
IToastText02 templateContent = ToastContentFactory.CreateToastText02();
templateContent.TextHeading.Text = note.Title;
templateContent.TextBodyWrap.Text = note.Message;
toastContent = templateContent;
// Create a toast, then create a ToastNotifier object to show
// the toast
ToastNotification toast = toastContent.CreateNotification();
toast.Activated += toast_Activated;
// If you have other applications in your package, you can specify the AppId of
// the app to create a ToastNotifier for that application
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
async void toast_Activated(ToastNotification sender, object args)
{
await Launcher.LaunchUriAsync(new Uri("http://www.google.com"));
}
My activated event happens, however, no web browser opens. That launcher code works without the toast notification.
How do I populate args with a url? My web service returns note.RedirectUrl and I want to feed it in there.

Instead of using the Activated event handler on the ToastNotification, use the OnLaunched handler in the main Application class (which allows launch context to be easily accessed).
For the handler to be invoked, a launch argument needs to be provided in the toast XML. Using the code above, you can add the argument to the the IToastContent object like so:
toastContent.Launch = note.RedirectUrl;
Then in the Application's OnLaunched method, the app can retrieve the launch argument:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (!String.IsNullOrEmpty(args.Argument)) {
var redirectUrl = args.Argument;
}
}
Calling LaunchUriAsync should work as expected when used from OnLaunched.

Related

Navigate to page on start in .NET Maui app

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();
}
}

Why isn't Gtk Filechooser Button selecting any file in my flatpak build?

I have a file chooser button that triggers a change in the titlebar whenever a file is selected with it. And it seems to work fine in my non-flatpak build.
import gtk.Application : Application;
import gtk.ApplicationWindow : ApplicationWindow;
import gio.Application : GioApp = Application;
import gtkc.gtktypes : GApplicationFlags, FileChooserAction;
import gtk.FileChooserButton : FileChooserButton;
const string AppID = `org.github.flatfcbtest`;
int main(string[] args)
{
auto app = new App();
return app.run(args);
}
public class App : Application
{
public:
this(const string appID = AppID, const GApplicationFlags flags = GApplicationFlags.FLAGS_NONE)
{
super(appID, flags);
addOnActivate(delegate void(GioApp _) {
auto pw = new PrimaryWindow(this);
pw.showAll();
});
}
}
class PrimaryWindow : ApplicationWindow
{
this(Application app)
{
super(app);
setSizeRequest(500, 300);
auto fcb = new FileChooserButton(`Select file`, FileChooserAction.OPEN);
fcb.addOnFileSet(delegate void (FileChooserButton _) {
setTitle(`file set!`);
});
add(fcb);
}
}
(GtkD reference)
However in my flatpak builds, the file selected with the chooser button does not select anything and it keeps saying (None). However my titlebar is changes accordingly so I know that the signal was emitted by the file chooser button.
Here is my flatpak permissions list:
finish-args:
- --socket=fallback-x11
- --share=ipc
- --filesystem=host
- --device=all
- --socket=session-bus
What's causing this?
Typically if you're shipping a flatpak, you want to avoid --filesystem=host and just use GtkFileChooserNative instead. This class supports portals, allowing a user to select files the application does not have permission to access by itself.
This is a much better approach than giving the application full filesystem access. GtkFileChooserNative will still work in a non-flatpak application and you shouldn't notice any difference unless you're doing something fancy.
As for your question of why GtkFileChooser is not working with --filesystem=host however, I do not know.

AEM Workflow custom input data

I need to create a workflow in AEM that for a page (specified as payload) finds all the assets used on the page and uploads a list of them to an external service. So far I have most of the code ready, but business process requires me to use a special code for each of the pages (different for each run of the workflow), so that the list is uploaded to correct place.
That is when I have a question - Can you somehow add more input values for an AEM workflow? Maybe by extending the starting dialog, or adding some special step that takes user input? I need to be able to somehow specify the code when launching the workflow or during its runtime.
I have read a lot of documentation but as this is my first time using workflows, I might be missing something really obvious. I will be grateful for any piece of advice, including a link to a relevant piece of docs.
Yes, that is possible. You need to implement a dialog step in your workflow: https://docs.adobe.com/content/help/en/experience-manager-64/developing/extending-aem/extending-workflows/workflows-step-ref.html#dialog-participant-step
You could:
Create a custom menu entry somewhere in AEM (e.g. Page Editor, /apps/wcm/core/content/editor/_jcr_content/content/items/content/header/items/headerbar/items/pageinfopopover/items/list/items/<my-action>, see under libs for examples)
Create a client-library with the categories="[cq.authoring.editor]". So it is loaded as part of the page editor (and not inside the iframe with your page)
Create a JS-Listener, that opens a dialog if the menu-entry was clicked (see code). You can either use plain Coral UI dialogs, or my example misused a Granite page dialog (Granite reads the data-structure in cq:dialog, and creates a Coral UI component edit-dialog out of it - while Coral is the plain JS UI-framework)
Create a Java-Servlet, that catches your request, and creates the workflow. You could theoretically use the AEM servlet. But I often have to write my own, because it lacks some features.
Here is the JS Listener:
/*global Granite,jQuery,document,window */
(function ($, ns, channel, window) {
"use strict";
var START_WORKFLOW_ACTIVATOR_SELECTOR = ".js-editor-myexample-activator";
function onSuccess() {
ns.ui.helpers.notify({
heading: "Example Workflow",
content: "successfully started",
type: ns.ui.helpers.NOTIFICATION_TYPES.SUCCESS
});
}
function onSubmitFail(event, jqXHR) {
var errorMsg = Granite.I18n.getVar($(jqXHR.responseText).find("#Message").html());
ns.ui.helpers.notify({
heading: "Example Workflow",
content: errorMsg,
type: ns.ui.helpers.NOTIFICATION_TYPES.ERROR
});
}
function onReady() {
// add selector for special servlet to form action-url
var $form = ns.DialogFrame.currentFloatingDialog.find("form");
var action = $form.attr("action");
if (action) {
$form.attr("action", action + ".myexample-selector.html");
}
// register dialog-fail event, to show a relevant error message
$(document).on("dialog-fail", onSubmitFail);
// init your dialog here ...
}
function onClose() {
$(document).off("dialog-fail", onSubmitFail);
}
// Listen for the tap on the 'myexample' activator
channel.on("click", START_WORKFLOW_ACTIVATOR_SELECTOR, function () {
var activator = $(this);
// this is a dirty trick, to use a Granite dialog directly (point to data-structure like in cq:dialog)
var dialogUrl = Granite.HTTP.externalize("/apps/...." + Granite.author.ContentFrame.getContentPath());
var dlg = new ns.ui.Dialog({
getConfig: function () {
return {
src: dialogUrl,
loadingMode: "auto",
layout: "auto"
}
},
getRequestData: function () {
return {};
},
"onSuccess": onSuccess,
"onReady": onReady,
"onClose": onClose
});
ns.DialogFrame.openDialog(dlg);
});
}(jQuery, Granite.author, jQuery(document), window));
And here is the servlet
#Component(service = Servlet.class,
property = {
SLING_SERVLET_RESOURCE_TYPES + "=cq:Page",
SLING_SERVLET_SELECTORS + "=myexample-selector",
SLING_SERVLET_METHODS + "=POST",
SLING_SERVLET_EXTENSIONS + "=html"
})
public class RequestExampleWorkflowServlet extends SlingAllMethodsServlet {
#Override
protected void doPost(#Nonnull SlingHttpServletRequest request, #Nonnull SlingHttpServletResponse response) throws IOException {
final Page page = request.getResource().adaptTo(Page.class);
if (page != null) {
Map<String, Object> wfMetaData = new HashMap<>();
wfMetaData.put("workflowTitle", "Request Translation for " + page.getTitle());
wfMetaData.put("something", "Hello World");
try {
WorkflowSession wfSession = request.getResourceResolver().adaptTo(WorkflowSession.class);
if (wfSession != null) {
WorkflowModel wfModel = wfSession.getModel("/var/workflow/models/example-workflow");
WorkflowData wfData = wfSession.newWorkflowData(PayloadInfo.PAYLOAD_TYPE.JCR_PATH.name(), page.getPath());
wfSession.startWorkflow(wfModel, wfData, wfMetaData);
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_OK, "Triggered Example Workflow");
} else {
throw new WorkflowException("Cannot retrieve WorkflowSession");
}
} catch (WorkflowException e) {
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} else {
MyServletUtil.respondSlingStyleHtml(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error - cannot get page");
}
}
}

button back to my app in the background and when you resume it starts again

I am developing an app in Xamarin.Forms, before I was trying to make a master detail page to become my MainPage when I logged in to my app, this I have already achieved. Now I have the problem that when I use the button behind the phone my app is miimiza and goes to the background which is the behavior I hope, but when I return to my app does not continue showing my master detail page, but returns to my LginPage.
It is as if my app was running twice or at least there were two instances of LoginPage existing at the same time, this is because in my LoginPage I trigger some DisplayAlert according to some messages that my page is listening through the MessaginCenter and they are they shoot twice.
Can someone tell me how I can return the same to my app on the master detail page and not restart in the strange way described?
LoginView.xaml.cs:
public partial class LogonView : ContentPage
{
LogonViewModel contexto = new LogonViewModel();
public LogonView ()
{
InitializeComponent ();
BindingContext = contexto;
MessagingCenter.Subscribe<LogonViewModel>(this, "ErrorCredentials", async (sender) =>
{
await DisplayAlert("Error", "Email or password is incorrect.", "Ok");
}
);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<LogonViewModel>(this, "ErrorCredentials");
}
}
Part of my ViewModel:
if (Loged)
{
App.token = token;
Application.Current.MainPage = new RootView();
}
else
{
MessagingCenter.Send(this, "ErrorCredentials");
}
Thanks.
I hope this is in Android. All you can do is, you can override the backbuttonpressed method in MainActivity for not closing on back button pressed of the entry page. like below, you can add some conditions as well.
public override void OnBackPressed()
{
Page currentPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentPage != null)
{
if (currentPage.GetType().Name == "HomePage" || currentPage.GetType().Name == "LoginPage")
{
return;
}
}
base.OnBackPressed();
}
When you press the Home button, the application is paused and the
current state is saved, and finally the application is frozen in
whatever state it is. After this, when you start the app, it is
resumed from the last point it was saved with.
However, when you use the Back button, you keep traversing back in
the activity stack, closing one activity after another. in the end,
when you close the first activity that you opened, your application
exits. This is why whenever you close your application like this, it
gets restarted when you open it again.
Answer taken from this answer. The original question asks about the native Android platform, but it still applies here.
It means you have to Use Setting Plugin or save data in Application properties.
You have to add below code in App.xaml.cs file:
if (SettingClass.UserName == null)
MainPage = new LoginPage();
else
MainPage = new MasterDetailPage();
For Setting Plugin you can refer this link.

WP: What callback to be used when page is loaded from app launching

Inside MainpPage.xaml.cs, what callback can be used so that I know it is coming from launching the App but not coming from other page? I know that there is Application_Launching in App.xaml.cs. But if I place below code there, exception is thrown somewhere. If I put in Loaded callback, I can't distinguish if it is called from App launching from navigated from other page.
if (MediaPlayer.State == MediaState.Playing)
{
MediaPlayer.Pause();
}
I would like to stop any existing playing music after entering my app.
Thanks
In you App.xaml:
public void TryStopAllMusic()
{
if (MediaPlayer!=null && MediaPlayer.GameHasControl)
{
MediaPlayer.Stop(); //stop to clear any existing music
}
}
In the constructor, under InitializeComponent() of your MainPage.xaml.cs:
public MainPage()
{
InitializeComponent();
(Application.Current as App).TryStopAllMusic();
}
That's all.