static void ShowModernNotification(string?title, string message, Uri?navigateTo, TimeSpan?duration = null)
        {
            var content = new ToastContent {
                Launch = navigateTo?.ToString(),

                Header = title == null ? null : new ToastHeader(title, title, navigateTo?.ToString()),

                Visual = new ToastVisual {
                    BindingGeneric = new ToastBindingGeneric {
                        Children = { new AdaptiveText {
                                         Text = message
                                     } },
                    }
                }
            };

            var contentXml = new XmlDocument();

            contentXml.LoadXml(content.GetContent());
            var toast = new ToastNotification(contentXml)
            {
                // DTO + null == null
                ExpirationTime = DateTimeOffset.Now + duration,
            };

            try {
                ToastNotificationManagerCompat.CreateToastNotifier().Show(toast);
            } catch (Exception e) {
                WarningsService.Default.ReportAsWarning(e, prefix: $"Notification failed");
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Create content of the toast notification
            var toastContent = new ToastContent()
            {
                Scenario = ToastScenario.Default,
                Visual   = new ToastVisual
                {
                    BindingGeneric = new ToastBindingGeneric
                    {
                        Children =
                        {
                            new AdaptiveText
                            {
                                Text = "New toast notification (BackgroundTaskHelper)."
                            }
                        }
                    }
                }
            };

            // Create & show toast notification
            var toastNotification = new ToastNotification(toastContent.GetXml());

            ToastNotificationManagerCompat.CreateToastNotifier().Show(toastNotification);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            ReunionApp.OnActivated += ReunionApp_OnActivated;

            if (!ReunionApp.WasProcessActivated())
            {
                Console.WriteLine("Hello World!");

                Console.WriteLine("To receive a toast, press enter...");

                Console.ReadLine();

                var content = new ToastContentBuilder()
                              .AddText("Hi! Please enter your name!")
                              .AddInputTextBox("name", "Your name")
                              .AddButton("Submit", ToastActivationType.Foreground, "submit")
                              .AddToastActivationInfo("helloConsoleArgs", ToastActivationType.Foreground)
                              .GetToastContent();

                var notif = new ToastNotification(content.GetXml());

                // Only difference here is calling the Compat API so that works down-level
                ToastNotificationManagerCompat.CreateToastNotifier().Show(notif);

                Console.WriteLine("You should try clicking the toast...");

                Console.ReadLine();
            }
            else
            {
                Console.ReadLine();
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="applicationContext"></param>
        public WindowsNotificationManager(WindowsApplicationContext?applicationContext = null)
        {
            _applicationContext  = applicationContext ?? WindowsApplicationContext.FromCurrentProcess();
            _launchActionPromise = new TaskCompletionSource <string>();

#if !NETSTANDARD
            if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated())
            {
                ToastNotificationManagerCompat.OnActivated += OnAppActivated;

                if (_launchActionPromise.Task.Wait(LaunchNotificationWaitMs))
                {
                    LaunchActionId = _launchActionPromise.Task.Result;
                }
            }
#endif

#if NETSTANDARD
            _toastNotifier = ToastNotificationManager.CreateToastNotifier(_applicationContext.AppUserModelId);
#else
            _toastNotifier = ToastNotificationManagerCompat.CreateToastNotifier();
#endif

            _notifications = new Dictionary <ToastNotification, Notification>();
        }
        private void ButtonSendToast_Click(object sender, RoutedEventArgs e)
        {
            var content = new ToastContentBuilder()
                          .AddText("Hello world!")
                          .AddToastActivationInfo("helloWorldArgs", ToastActivationType.Foreground)
                          .GetToastContent();

            var notif = new ToastNotification(content.GetXml());

            // Only difference here is calling the Compat API so that works down-level
            ToastNotificationManagerCompat.CreateToastNotifier().Show(notif);
        }
Exemple #6
0
        public void ShowNotification(string text, string secondaryText = null)
        {
            var builder = new ToastContentBuilder().AddText(text);

            if (!string.IsNullOrWhiteSpace(secondaryText))
            {
                builder.AddText(secondaryText);
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                var toast = new ToastNotification(builder.GetToastContent().GetXml());
                ToastNotificationManagerCompat.CreateToastNotifier().Show(toast);
            });
        }
        private async void ButtonPopToast_Click(object sender, RoutedEventArgs e)
        {
            if (ToastNotificationManagerCompat.CreateToastNotifier().Setting != NotificationSetting.Enabled)
            {
                MessageBox.Show("Notifications are disabled from the system settings.");
                return;
            }

            string title          = "Andrew sent you a picture";
            string content        = "Check this out, The Enchantments!";
            string image          = "https://picsum.photos/364/202?image=883";
            int    conversationId = 5;

            // Construct the toast content and show it!
            new ToastContentBuilder()

            // Arguments that are returned when the user clicks the toast or a button
            .AddArgument("action", MyToastActions.ViewConversation)
            .AddArgument("conversationId", conversationId)

            // Visual content
            .AddText(title)
            .AddText(content)
            .AddInlineImage(new Uri(await DownloadImageToDisk(image)))
            .AddAppLogoOverride(new Uri(await DownloadImageToDisk("https://unsplash.it/64?image=1005")), ToastGenericAppLogoCrop.Circle)

            // Text box for typing a reply
            .AddInputTextBox("tbReply", "Type a reply")

            // Buttons
            .AddButton(new ToastButton()
                       .SetContent("Reply")
                       .AddArgument("action", MyToastActions.Reply)
                       .SetBackgroundActivation())

            .AddButton(new ToastButton()
                       .SetContent("Like")
                       .AddArgument("action", MyToastActions.Like)
                       .SetBackgroundActivation())

            .AddButton(new ToastButton()
                       .SetContent("View")
                       .AddArgument("action", MyToastActions.ViewImage)
                       .AddArgument("imageUrl", image))

            // And show the toast!
            .Show();
        }
        private void Setup()
        {
            bool encode = this.userSettingService.GetUserSetting <bool>(UserSettingConstants.NotifyOnEncodeDone);
            bool queue  = this.userSettingService.GetUserSetting <bool>(UserSettingConstants.NotifyOnQueueDone);

            if (encode || queue)
            {
                if (isInitialised)
                {
                    return;
                }

                this.notifier = ToastNotificationManagerCompat.CreateToastNotifier();

                isInitialised = true;

                ToastNotificationManagerCompat.OnActivated += toastArgs =>
                {
                    // Obtain the arguments from the notification
                    ToastArguments args = ToastArguments.Parse(toastArgs.Argument);

                    // Remove any notifications that are clicked
                    System.Collections.Generic.KeyValuePair <string, string> tag = args.FirstOrDefault();
                    if (!string.IsNullOrEmpty(tag.Value))
                    {
                        try
                        {
                            ToastNotificationManagerCompat.History.Remove(tag.Value);
                        }
                        catch (Exception exc)
                        {
                            Debug.WriteLine(exc);
                        }
                    }

                    // Need to dispatch to UI thread if performing UI operations
                    Application.Current.Dispatcher.Invoke(delegate
                    {
                        Window w = Application.Current.MainWindow;
                        if (w != null)
                        {
                            w.WindowState = WindowState.Normal;
                            w.BringIntoView();
                        }
                    });
                };
            }
        }
        private async void ButtonProgressToast_Click(object sender, RoutedEventArgs e)
        {
            const string tag = "progressToast";

            new ToastContentBuilder()
            .AddArgument("action", MyToastActions.ViewConversation)
            .AddArgument("conversationId", 423)
            .AddText("Sending image to conversation...")
            .AddVisualChild(new AdaptiveProgressBar()
            {
                Value  = new BindableProgressBarValue("progress"),
                Status = "Sending..."
            })
            .Show(toast =>
            {
                toast.Tag = tag;

                toast.Data = new NotificationData(new Dictionary <string, string>()
                {
                    { "progress", "0" }
                });
            });

            double progress = 0;

            while (progress < 1)
            {
                await Task.Delay(new Random().Next(1000, 3000));

                progress += (new Random().NextDouble() * 0.15) + 0.1;

                ToastNotificationManagerCompat.CreateToastNotifier().Update(
                    new NotificationData(new Dictionary <string, string>()
                {
                    { "progress", progress.ToString() }
                }), tag);
            }

            new ToastContentBuilder()
            .AddArgument("action", MyToastActions.ViewConversation)
            .AddArgument("conversationId", 423)
            .AddText("Sent image to conversation!")
            .Show(toast =>
            {
                toast.Tag = tag;
            });
        }
Exemple #10
0
        public static void UpdateProgressToast(string progressValue, string progressValueString)
        {
            // INFO: Put in actionqueue if exception is thrown

            // Construct a NotificationData object;
            string tag   = "adm_update_in_progress";
            string group = "downloads";

            NotificationData data = new();

            // Assign new values
            // Note that you only need to assign values that changed. In this example
            // we don't assign progressStatus since we don't need to change it
            data.Values["progressValue"]       = progressValue;
            data.Values["progressValueString"] = progressValueString;

            // Update the existing notification's data by using tag/group
            ToastNotificationManagerCompat.CreateToastNotifier().Update(data, tag, group);
        }
Exemple #11
0
        public static void InvokeUpdateInProgressToast(string version, bool downgrade = false)
        {
            string typeVerb = downgrade ? "Downgrading" : "Updating";

            Program.ActionQueue.Add(() =>
            {
                // Define a tag (and optionally a group) to uniquely identify the notification, in order update the notification data later;
                string tag   = "adm_update_in_progress";
                string group = "downloads";

                // Construct the toast content with data bound fields
                ToastContent content = new ToastContentBuilder()
                                       .AddText($"{typeVerb} to {version}")
                                       .AddVisualChild(new AdaptiveProgressBar()
                {
                    Title = "Download in progress",
                    Value = new BindableProgressBarValue("progressValue"),
                    ValueStringOverride = new BindableString("progressValueString"),
                    Status = new BindableString("progressStatus")
                })
                                       .GetToastContent();

                // Generate the toast notification
                ToastNotification toast = new(content.GetXml());

                // Assign the tag and group
                toast.Tag   = tag;
                toast.Group = group;

                // Assign initial NotificationData values
                // Values must be of type string
                toast.Data = new NotificationData();
                toast.Data.Values["progressValue"]       = "0.0";
                toast.Data.Values["progressValueString"] = "0 MB";
                toast.Data.Values["progressStatus"]      = "Downloading...";

                // Provide sequence number to prevent out-of-order updates, or assign 0 to indicate "always update"
                toast.Data.SequenceNumber = 0;
                ToastNotificationManagerCompat.CreateToastNotifier().Show(toast);
                ToastNotificationManagerCompat.History.Remove("adm_update");
            });
        }
Exemple #12
0
 public static void Initialize()
 {
     DefaultNotifier ??= ToastNotificationManagerCompat.CreateToastNotifier();
 }
Exemple #13
0
 public void ShowToastNotification(ToastNotification toastNotification)
 {
     ToastNotificationManagerCompat.CreateToastNotifier().Show(toastNotification);
 }
Exemple #14
0
 private void PopToast()
 {
     ToastNotificationManagerCompat.CreateToastNotifier().Show(new ToastNotification(_toastContent.GetXml()));
 }
 internal static void Init()
 {
     _notifier = ToastNotificationManagerCompat.CreateToastNotifier();
     ToastNotificationManagerCompat.OnActivated += OnToastButtonClicked;
 }
Exemple #16
0
        public void ChangeDevice(List <IAudioDevice> activeDevices, List <AudioDeviceMBState> deviceMBStateList)
        {
            if (deviceMBStateList.Count == 0)
            {
                return;
            }

            // refresh devices on state list
            foreach (var device in deviceMBStateList)
            {
                try
                {
                    device.AudioDevice = activeDevices.Where(x => x.Id == device.Id).First();
                }
                catch
                {
                    Console.WriteLine($"Couldn't find device {device.Name} in active device list");
                }
            }

            // get system default
            var mbDeviceStateQueue           = new Queue <AudioDeviceMBState>(deviceMBStateList.ToArray());
            AudioDeviceMBState mbDeviceState = null;

            do
            {
                mbDeviceState = mbDeviceStateQueue.Dequeue();
                mbDeviceStateQueue.Enqueue(mbDeviceState);
            } while (!mbDeviceState.AudioDevice.IsDefault(Role.Console));

            AudioDeviceMBState deviceToSetDefault = mbDeviceStateQueue.First();

            foreach (var device in mbDeviceStateQueue)
            {
                if (device.InRotation)
                {
                    deviceToSetDefault = device;
                    break;
                }
            }

            deviceToSetDefault.AudioDevice.SetAsDefault(Role.Console);

            try
            {
                ToastAudio toastAudio = new ToastAudio();
                if (PlayChimeOnChange)
                {
                    toastAudio.Src = new Uri("ms-appx:///chime.wav");
                }
                else
                {
                    toastAudio.Silent = true;
                }

                ToastContent toastContent = new ToastContentBuilder()
                                            .AddText($"{(_playDevices == deviceMBStateList ? "Device" : "Input device")} changed: {deviceToSetDefault.AudioDevice.FriendlyName}")
                                            .AddAudio(toastAudio)
                                            .GetToastContent();

                // And create the toast notification
                var toast = new ToastNotification(toastContent.GetXml())
                {
                    Tag            = "ChangedDevice",
                    ExpirationTime = DateTime.Now.AddSeconds(10)
                };

                // And then show it
                ToastNotificationManagerCompat.CreateToastNotifier().Show(toast);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception {e}");
            }
        }