I'm currently working on a winforms app which after certain action sends a notification to user, when activated(clicked) it opens a link. So I can send the notification, I can open the link with toast.Activated but when banner disappear and gets in to the action center when I click on the notification it doesn't activate. So, I have searched a lot but couldn't find a way to activate the notification on action center.
Here is the code I'm currently using to send notification.
{
public void Toasty()
{
// Get a toast XML template
Windows.Data.Xml.Dom.XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText04);
// Fill in the text elements
Windows.Data.Xml.Dom.XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("Header"));
stringElements[1].AppendChild(toastXml.CreateTextNode("Message"));
stringElements[2].AppendChild(toastXml.CreateTextNode("From"));
ToastNotification toast = new ToastNotification(toastXml);
toast.Activated += toast_Activated;
//toast.SuppressPopup = true;
ToastNotificationManager.CreateToastNotifier("App").Show(toast);
}
async void toast_Activated(ToastNotification sender, object args)
{
await Launcher.LaunchUriAsync(new Uri("http://www.google.com"));
}
}
You don't need raw xml for this, get this nuget package :
Microsoft.Toolkit.Uwp.Notifications, then use the ToastContentBuilder to build a toast notification, it's easier and cleaner:
// Construct the visuals of the toast (using Notifications library)
ToastContent toastContent = new ToastContentBuilder()
.AddToastActivationInfo("action=viewConversation&conversationId=5", ToastActivationType.Foreground)
.AddText("Hello world!")
.GetToastContent();
// And create the toast notification
var toast = new ToastNotification(toastContent.GetXml());
// And then show it
DesktopNotificationManagerCompat.CreateToastNotifier().Show(toast);
Now for the activation part:
//Another way of creating a notification
public void CreateAndShowPrompt(string message)
{
ToastContent toastContent = new ToastContent()
{
Launch = "bodyTapped",
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = message
},
}
}
},
Actions = new ToastActionsCustom()
{
Buttons = { new ToastButton("Yes", "Yes"), new ToastButton("No", "No") }
},
Header = new ToastHeader("header", "App", "header")
};
var doc = new XmlDocument();
doc.LoadXml(toastContent.GetContent());
var promptNotification = new ToastNotification(doc);
promptNotification.Activated += PromptNotificationOnActivated;
DesktopNotificationManagerCompat.CreateToastNotifier().Show(promptNotification);
}
Event handler :
private void PromptNotificationOnActivated(ToastNotification sender, object args)
{
ToastActivatedEventArgs strArgs = args as ToastActivatedEventArgs;
switch (strArgs.Arguments)
{
case "Yes":
//stuff
break;
case "No":
//stuff
break;
case "bodyTapped":
//stuff
break;
}
}
This works in all cases, even when the toast is pushed back to the action center.
You can see it in action in an app that i made: NetStalker
Related
I've created a toast-message in WPF, with a button.
public void ShowToast(string message)
{
var toastButton = new ToastButton();
toastButton.ActivationType = ToastActivationType.Foreground;
toastButton.SetContent("Reconnect");
toastButton.AddArgument("action", "like");
var toast = new ToastContentBuilder()
.AddText("VPN Notifications")
.AddText(message)
.AddButton(toastButton).SetBackgroundActivation();
toast.Show();
}
How can I get the button callback in my C# dotnet 6 app?
I have a background task that is supposed to open a toast message, à la: ToastNotificationManager.CreateToastNotifier().Show(toast);. My code executes fine, no errors are thrown, nothing hangs -- but also, no toast message appears.
I checked the Event Viewer logs, and they say this:
An instance of the background task with entry point
BG.ToastBackgroundTask running for user [me] in session [sesh]
returned with error code 0x0.
I have looked all over to see what this error code might mean but found nothing.
Here's my code:
public sealed class ToastBackgroundTask : IBackgroundTask
{
private BackgroundTaskDeferral _deferral;
public async void Run(IBackgroundTaskInstance taskInstance)
{
var cancelToken = new System.Threading.CancellationTokenSource();
taskInstance.Canceled += (s, e) =>
{
cancelToken.Cancel();
cancelToken.Dispose();
};
taskInstance.Task.Completed += Task_Completed;
_deferral = taskInstance.GetDeferral();
try
{
await SendNotificationAsync();
}
finally { _deferral.Complete(); }
}
public static async void Register()
{
var isRegistered = BackgroundTaskRegistration.AllTasks.Values.Any(x => x.Name == nameof(ToastBackgroundTask));
if (isRegistered) return;
var accessStatus = await BackgroundExecutionManager.RequestAccessAsync();
if (accessStatus == BackgroundAccessStatus.DeniedByUser || accessStatus == BackgroundAccessStatus.DeniedBySystemPolicy) return;
var builder = new BackgroundTaskBuilder
{
Name = nameof(ToastBackgroundTask),
TaskEntryPoint = $"{nameof(MyNameSpace)}.{nameof(BG)}.{nameof(ToastBackgroundTask)}"
};
builder.SetTrigger(new TimeTrigger(120, false));
var task = builder.Register();
}
private static void Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
try
{
args.CheckResult();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private Task SendNotificationAsync()
{
var service = new ToastService();
service.CreateToast(new ToastViewModel { Title = "Title", Text = "Text", ImagePath = "", Id = 3 });
return Task.CompletedTask;
}
}
If I run CheckResult() on the completed task, no errors are thrown. Argh! Does anyone know (a) what this Event Viewer log error means, or (b) why my toast isn't showing up?
Here's my Toast code too in case it helps:
public class ToastService
{
public void CreateToast(ToastViewModel model)
{
var visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText() { Text = model.Title },
new AdaptiveText() { Text = model.Text }
},
Attribution = new ToastGenericAttributionText() { Text = "Via Me" }
}
};
var tContent = new ToastContent()
{
Visual = visual,
ActivationType = ToastActivationType.Background,
Scenario = ToastScenario.Reminder
};
var toast = new ToastNotification(tContent.GetXml())
{
ExpirationTime = DateTime.Now.AddDays(model.Expiration)
};
toast.Failed += (o, args) => {
var message = args.ErrorCode;
};
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
Does anyone know (a) what this Event Viewer log error means, or (b) why my toast isn't showing up?
The above event log showed on my side is information level, not error level. The reason for the toast isn't showing up should be that you setting the ExpirationTime property for the ToastNotification. This property is for:
Gets or sets the time after which a toast notification should not be displayed.
So that if the model.Expiration equals to 0, the toast will not show from now. Ensure the expiration time later than now should work.
var toast = new ToastNotification(tContentxml)
{
ExpirationTime = DateTime.Now.AddDays(1)
};
Otherwise your code snippet can work will on my side. If you still have issues, you can provide a minimal reproduced project to let us have a testing.
I create and post a Toast as follows:
public async Task Handle(Alert a) {
var tst = String.Format(#"<toast><visual><binding template='ToastGeneric'><text>Alert</text><text>{0}</text></binding></visual></toast>", a.Msg);
var xml = new XmlDocument();
xml.LoadXml(tst);
var tn = new ToastNotification(xml);
var t = new TaskCompletionSource<bool>();
tn.Dismissed += (s, e) => {
t.TrySetResult(true);
PersistLog.i(TAG, "Handle:Toast Dismissed:" + e.Reason);
};
tn.Failed += (s, e) => {
t.TrySetResult(false);
PersistLog.i(TAG, "Handle:Toast Failed");
};
*/
ToastNotificationManager.CreateToastNotifier().Show(tn);
var how = await t.Task;
}
The Toast Never displays. If Does call the Dismissed CB ... and the Reason is UserCancelled. Why ??? It does show up in the Windows 10 (Anniversary) Action Center.
I have tried calling this from a UI thread as well from the App's OnBackgroundActivated event. The latter is where I really want to call this from ... I want to display a Toast when my App is activated as a Background task from an WNS event.
Hi i want my app to navigate to a page when i receive a push toast notification. My code is as follows:-
ParsePush.ToastNotificationReceived += OnPushNotification;
This is to handle the event of push
private async void OnPushNotification(object sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs e)
{
var AdFrame = Window.Current.Content as Frame;
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey("Suspended"))
{
String value = localSettings.Values["Suspended"].ToString();
if (value != null)
{
if (value == "false")
{
AdFrame.Navigate(typeof(Ad));
}
}
}
}
I get a Null Reference Error at var AdFrame = Window.Current.Content as Frame;
I have added this code in App.xaml.cs .I just want to navigate to the Ad Page from current page , whatever page maybe active. I am pretty new to windows , any help will be appreciated.
You will need to display a toast notification instead:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements.Item(0).AppendChild(toastXml.CreateTextNode("Hello world!"));
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
XmlAttribute launchAttribute = toastXml.CreateAttribute("launch");
launchAttribute.Value = "pass data here"; // TODO: pass data here
toastNode.Attributes.SetNamedItem(launchAttribute);
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
When user clicks on the toast notification, you can handle the App launch event and then read the data.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// ...
MainPage page = rootFrame.Content as MainPage;
page.ParseData(e.Arguments);
}
Hey guys i have been trying to print my Webview using the tutorial Jerry Nixon gave on How do I print WebView content in a Windows Store App? and the tutorial from "windows 8 apps with xaml and c#" by Adam Nathan, i have attached the code below from his example:
using System;
using Windows.Graphics.Printing;
using Windows.Graphics.Printing.OptionDetails;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Printing;
namespace Chapter19
{
public sealed partial class MainPage : Page
{
// Supports printing pages, where each page is a UIElement
PrintDocument doc = new PrintDocument();
public MainPage()
{
InitializeComponent();
// Attach handlers to relevant events
doc.GetPreviewPage += OnGetPreviewPage;
doc.AddPages += OnAddPages;
PrintManager printManager = PrintManager.GetForCurrentView();
printManager.PrintTaskRequested += OnPrintTaskRequested;
}
// Prepare the print preview pages
void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
this.doc.SetPreviewPageCount(2, PreviewPageCountType.Final);
if (e.PageNumber == 1)
{
this.doc.SetPreviewPage(1, new Viewbox
{
Child = new Button
{
Content = "PAGE 1!",
Background = new SolidColorBrush(Colors.Red)
}
});
}
else
{
this.doc.SetPreviewPage(2, new Viewbox
{
Child = new Button
{
Content = "PAGE 2!",
Background = new SolidColorBrush(Colors.Red)
}
});
}
}
// Prepare the real pages
void OnAddPages(object sender, AddPagesEventArgs e)
{
this.doc.AddPage(new Viewbox
{
Child = new Button
{
Content = "PAGE 1!",
Background = new SolidColorBrush(Colors.Red)
}
});
this.doc.AddPage(new Viewbox
{
Child = new Button
{
Content = "PAGE 2!",
Background = new SolidColorBrush(Colors.Red)
}
});
this.doc.AddPagesComplete();
}
// Prepare and perform the printing
void OnPrintTaskRequested(PrintManager sender,
PrintTaskRequestedEventArgs args)
{
// This gets invoked as soon as the Devices pane is shown
PrintTask task = args.Request.CreatePrintTask("Document Title",
async (taskArgs) =>
{
// This is invoked on a background thread when the Print
// button is clicked
var deferral = taskArgs.GetDeferral();
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// This must run on the main thread
taskArgs.SetSource(doc.DocumentSource);
deferral.Complete();
});
});
// Show custom options
PrintTaskOptionDetails details =
PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options);
details.DisplayedOptions.Clear();
details.DisplayedOptions.Add(StandardPrintTaskOptions.MediaSize);
// A custom text option
PrintCustomTextOptionDetails option1 = details.CreateTextOption(
"CustomId1", "Header");
details.DisplayedOptions.Add("CustomId1");
// A custom list option
PrintCustomItemListOptionDetails option2 = details.CreateItemListOption(
"CustomId2", "Contents");
option2.AddItem("customItemId1", "As Seen on Screen");
option2.AddItem("customItemId2", "Summary View");
option2.AddItem("customItemId3", "Full Details");
option2.AddItem("customItemId4", "Multiple Columns");
details.DisplayedOptions.Add("CustomId2");
// Handle options changes
details.OptionChanged += OnOptionChanged;
}
void OnOptionChanged(PrintTaskOptionDetails sender, PrintTaskOptionChangedEventArgs args)
{
// TODO: Handle custom options
}
}
}
the problem i am having is that i am struggling to get "MywebviewPages" that jerry generated onto the
"this.doc.SetPreviewPage"
and
"this.doc.AddPage"
from Nathans example. Due to lack of PDF api's on winRT i am forced to use webview since its the only way to have tables. please help