Example #1
0
 public NotificationBuilder(IServiceProvider?serviceProvider)
 {
     tbc = new ToastContentBuilder();
     this.UseConfigurationFrom <IUwpExtension>(serviceProvider);
     this.UseConfigurationFrom <IPlatformSpecificExtension>(serviceProvider);
     this.serviceProvider = serviceProvider;
 }
        private void handleNotifications(List <DisplayLobby> displayLobbies)
        {
            if (displayLobbies == null)
            {
                return;
            }

            if (notifiedLobbies == null)
            {
                notifiedLobbies = new HashSet <string>();
            }

            List <DisplayLobby> newLobbies = displayLobbies.Where(dL => !string.IsNullOrEmpty(dL.LobbyID) && !string.IsNullOrEmpty(dL.LobbyName) && !notifiedLobbies.Contains(dL.LobbyID)).ToList();

            if (newLobbies.Count == 0)
            {
                return;
            }

            notifiedLobbies.UnionWith((from dL in newLobbies select dL.LobbyID).ToHashSet());

            List <string> newNames = (from dL in newLobbies select dL.LobbyName).ToList();
            string        title    = newNames.Count + " New Lobbies";
            string        lobbies  = string.Join("; ", newNames.Take(lobbyNamesInNotification).ToList());

            ToastContentBuilder tcb = new ToastContentBuilder();

            tcb.AddAppLogoOverride(new Uri(Storage.GetLogoPath())).
            AddText(title).AddText(lobbies).Show();
        }
Example #3
0
        /// <summary>
        /// 期限切れ判定タイマのタイムアウト時コールバック
        /// </summary>
        /// <param name="state">状態</param>
        private static void TermOutTimerCallBack(object state)
        {
            if (Config.Instance.EditableItems.IsNotifyWindowsToast)
            {
                var tasks         = ResourceManager.Instance.GetAllTaskItems().Where(x => Utils.IsOverLimit(x.DateTimeLimit));
                var tmpTasks      = tasks.ToList();
                var today         = DateTime.Today;
                var isNotifyToast = true;
                if (prevTermOutTaskList.SequenceEqual(tmpTasks))
                {
                    var diff = (today - prevNotifedDateTime).Days;
                    if (Config.Instance.EditableItems.NotifyTermOutSpanDay > diff)
                    {
                        // 同一リストかつ再通知期限内の場合は通知しない。
                        isNotifyToast = false;
                    }
                }

                if (isNotifyToast)
                {
                    prevNotifedDateTime = today;
                    prevTermOutTaskList = tmpTasks;
                    if (prevTermOutTaskList.Any())
                    {
                        var toast = new ToastContentBuilder()
                                    .AddText("タスクの期限切れ通知")
                                    .AddText("期限切れのタスクがあります。確認してください");
                        toast.Show();
                    }
                }
            }

            ActionTermOutTimerEventOnCompleted();
        }
Example #4
0
        public void AddButtonTest_WithTextBoxId_ReturnSelfWithButtonAdded()
        {
            // Arrange
            string testInputTextBoxId = Guid.NewGuid().ToString();
            string testButtonContent  = "Test Button Content";
            ToastActivationType testToastActivationType = ToastActivationType.Background;
            string testButtonLaunchArgs = "Test Launch Args";
            Uri    testImageUriSrc      = new Uri("C:/justatesturi.jpg");

            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddButton(testInputTextBoxId, testButtonContent, testToastActivationType, testButtonLaunchArgs, testImageUriSrc);

            // Assert
            Assert.AreSame(builder, anotherReference);

            var button = (builder.Content.Actions as ToastActionsCustom).Buttons.First() as ToastButton;

            Assert.AreEqual(testInputTextBoxId, button.TextBoxId);
            Assert.AreEqual(testButtonContent, button.Content);
            Assert.AreEqual(testToastActivationType, button.ActivationType);
            Assert.AreEqual(testButtonLaunchArgs, button.Arguments);
            Assert.AreEqual(testImageUriSrc.OriginalString, button.ImageUri);
        }
        /// <summary>
        /// Shows the toast notification.
        /// </summary>
        public async Task Show()
        {
            var builder = new ToastContentBuilder();

            if (AppLogoOverride != null)
            {
                var uri = AppLogoOverride.GetSourceUri() ?? await AppLogoOverride.GetFileUriAsync().ConfigureAwait(false);

                builder.AddAppLogoOverride(uri);
            }

            // Title and Message are required.
            builder.AddText(Title, hintMaxLines: 1)
            .AddText(Message);

            builder.SetToastDuration(ToastDuration == ToastDuration.Short ? UwpNot.ToastDuration.Short : UwpNot.ToastDuration.Long);

            _tcs = new TaskCompletionSource <object>();

            builder.Show(t =>
            {
                TypedEventHandler <Windows.UI.Notifications.ToastNotification, ToastDismissedEventArgs> handler = (sender, args) => { };
                handler = (sender, args) =>
                {
                    sender.Dismissed -= handler;
                    _tcs.SetResult(null);
                };
                t.Dismissed += handler;
            });

            await _tcs.Task;
        }
Example #6
0
        private void CreateToastButton_Click(object sender, EventArgs e)
        {
            var actionButton = new ToastButton();

            actionButton.AddArgument("action", "buttonAction");
            actionButton.SetContent("Action Button");

            var dismissButton = new ToastButton();

            dismissButton.SetContent("Dismiss Button");
            dismissButton.SetDismissActivation();

            var toast = new ToastContentBuilder();

            toast.AddAttributionText("Attribute Text");
            toast.AddText("Title");
            toast.AddText("Text 1");
            toast.AddText("Text 2");
            toast.AddButton(actionButton);
            toast.AddButton(dismissButton);
            toast.Show(toast =>
            {
                toast.ExpirationTime = DateTime.Now.AddSeconds(5);
                toast.Priority       = Windows.UI.Notifications.ToastNotificationPriority.High;
            });
        }
Example #7
0
        private void SendActivateToast()
        {
            if (IsInBackgroundMode &&
                (FullTrustProcessController.IsAnyActionExcutingInAllControllers ||
                 GeneralTransformer.IsAnyTransformTaskRunning ||
                 QueueTaskController.IsAnyTaskRunningInController))
            {
                try
                {
                    ToastNotificationManager.History.Remove("EnterBackgroundTips");

                    if (PowerManager.EnergySaverStatus == EnergySaverStatus.On)
                    {
                        ToastContentBuilder Builder = new ToastContentBuilder()
                                                      .SetToastScenario(ToastScenario.Reminder)
                                                      .AddToastActivationInfo("EnterBackgroundTips", ToastActivationType.Foreground)
                                                      .AddText(Globalization.GetString("Toast_EnterBackground_Text_1"))
                                                      .AddText(Globalization.GetString("Toast_EnterBackground_Text_2"))
                                                      .AddText(Globalization.GetString("Toast_EnterBackground_Text_4"))
                                                      .AddButton(new ToastButton(Globalization.GetString("Toast_EnterBackground_ActionButton"), "EnterBackgroundTips"))
                                                      .AddButton(new ToastButtonDismiss(Globalization.GetString("Toast_EnterBackground_Dismiss")));

                        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(Builder.GetToastContent().GetXml())
                        {
                            Tag      = "EnterBackgroundTips",
                            Priority = ToastNotificationPriority.High
                        });
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Toast notification could not be sent");
                }
            }
        }
Example #8
0
        public static void HandlePackageInstallCompletedToast(SuccessMessage m, ToastNotification progressToast)
        {
            if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362))
            {
                return;
            }

            PackageBase package = (PackageBase)m.Context;

            var builder = new ToastContentBuilder().SetToastScenario(ToastScenario.Reminder)
                          .AddToastActivationInfo($"package/{package.Urn}", ToastActivationType.Foreground)
                          .AddText(package.ShortTitle)
                          .AddText(package.Title + " just got installed.");

            try
            {
                if (package.GetAppIcon().Result is SDK.Images.FileImage image && !image.Uri.IsFile)
                {
                    builder.AddAppLogoOverride(image.Uri, addImageQuery: false);
                }
            }
            finally { }

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

            // Hide progress notification
            Hide(progressToast);
            // Show the final notification
            ToastNotificationManager.GetDefault().CreateToastNotifier().Show(notif);
        }
Example #9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // This task will only run once, after OOBE is completed and user is logged into the desktop.
            // It usually takes around 5-15 minutes for the task to run (and often runs closer to 15 minutes).

            // Schedule the notification to be shown later (in 5 minutes).
            try
            {
                ToastHelper.ScheduleToast();
            }
            catch (Exception ex)
            {
                var errorContent = new ToastContentBuilder().AddText("[Debug] PreinstallTask exception occurred").AddText(ex.ToString(), hintWrap: true).GetToastContent();
                ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(errorContent.GetXml())
                {
                    ExpirationTime = DateTime.Now.AddMinutes(5)
                });
            }

#if VERBOSE
            // When compiled in verbose, show a notification so that we know it ran
            var content = new ToastContentBuilder().AddText("[Debug] PreinstallTask ran").AddText($"Edge toast scheduled for {DateTime.Now.AddMinutes(5).ToShortTimeString()} (5 minutes from now)").GetToastContent();
            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(content.GetXml())
            {
                ExpirationTime = DateTime.Now.AddMinutes(6)
            });
#endif
        }
Example #10
0
        public static async Task SendNotification(string chatId, string?personId, string messageId, string chatName, string contactName, string message)
        {
            var thumbnailUri = await GetPersonId(personId);

            var builder = new ToastContentBuilder()
                          .AddArgument(ActivationHelper.ToastAction, ActivationHelper.ToastActionConversation)
                          .AddArgument(ActivationHelper.ToastActionConversationChat, chatId)
                          .AddHeader(
                chatId,
                chatName,
                $"{ActivationHelper.ToastAction}={ActivationHelper.ToastActionConversation}&" +
                $"{ActivationHelper.ToastActionConversationChat}={chatId}"
                )
                          .AddText(contactName)
                          .AddText(message);

            if (thumbnailUri != null)
            {
                builder.AddAppLogoOverride(thumbnailUri, ToastGenericAppLogoCrop.Circle);
            }

            builder.Show((toast) =>
            {
                toast.Group = chatId;
                toast.Tag   = messageId;
            });
        }
Example #11
0
        private void ShowToast(string copiedText)
        {
            string inputLang = InputLanguageManager.Current.CurrentInputLanguage.Name;
            // Construct the content
            ToastContent content = new ToastContentBuilder()
                                   .AddToastActivationInfo(copiedText + ',' + inputLang, ToastActivationType.Foreground)
                                   .SetBackgroundActivation()
                                   .AddText(copiedText)
                                   .GetToastContent();

            content.Duration = ToastDuration.Short;

            // Create the toast notification
            var toastNotif = new ToastNotification(content.GetXml());

            // And send the notification
            try
            {
                ToastNotificationManager.CreateToastNotifier().Show(toastNotif);
            }
            catch (Exception)
            {
                Settings.Default.ShowToast = false;
                Settings.Default.Save();
            }
        }
Example #12
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();
            }
        }
Example #13
0
        private void ButtonSendToast_Click(object sender, RoutedEventArgs e)
        {
            // In a real app, these would be initialized with actual data
            string title           = "Andrew Bares";
            string content         = "Cannot wait to try your UWP app!";
            var    logoOverrideUri = new Uri("https://picsum.photos/48?image=883");

            // Construct the content21
            var contentBuilder = new ToastContentBuilder()
                                 .AddToastActivationInfo("app-defined-string", ToastActivationType.Foreground)
                                 .AddText(title)
                                 .AddText(content)
                                 // Profile (app logo override) image
                                 .AddAppLogoOverride(logoOverrideUri, ToastGenericAppLogoCrop.Circle);

            // If we're running on Desktop before Version 1511, do NOT include custom audio
            // since it was not supported until Version 1511, and would result in a silent toast.

            var supportsCustomAudio = !(AnalyticsInfo.VersionInfo.DeviceFamily.Equals("Windows.Desktop") &&
                                        !ApiInformation.IsApiContractPresent(
                                            "Windows.Foundation.UniversalApiContract", 2));

            if (supportsCustomAudio)
            {
                contentBuilder.AddAudio(new Uri("ms-appx:///Assets/Audio/CustomToastAudio.m4a"));
            }

            // Send the toast
            contentBuilder.Show();
        }
Example #14
0
        public void AddTextTest_WithTextAndFullOptions_ReturnSelfWithTextAndAllOptionsAdded()
        {
            // Arrange
            string            testText     = "Test Text";
            AdaptiveTextStyle testStyle    = AdaptiveTextStyle.Header;
            bool testWrapHint              = true;
            int  testHintMaxLine           = 2;
            int  testHintMinLine           = 1;
            AdaptiveTextAlign testAlign    = AdaptiveTextAlign.Auto;
            string            testLanguage = "en-US";

            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddText(testText, testStyle, testWrapHint, testHintMaxLine, testHintMinLine, testAlign, testLanguage);

            // Assert
            Assert.AreSame(builder, anotherReference);
            var text = builder.Content.Visual.BindingGeneric.Children.First() as AdaptiveText;

            Assert.AreEqual(testText, (string)text.Text);
            Assert.AreEqual(testHintMaxLine, text.HintMaxLines);
            Assert.AreEqual(testLanguage, text.Language);

            // These values should still be the default values, since they aren't used for top-level text
            Assert.AreEqual(AdaptiveTextStyle.Default, text.HintStyle);
            Assert.IsNull(text.HintWrap);
            Assert.IsNull(text.HintMinLines);
            Assert.AreEqual(AdaptiveTextAlign.Default, text.HintAlign);
        }
Example #15
0
        public void AddProgressBarTest_WithFixedPropertiesAndDeterminateValue_ReturnSelfWithFixedValueAndPropertiesProgressBarAdded()
        {
            // Arrange
            string testProgressBarTitle    = "Test Progress Bar Title";
            double testProgressBarValue    = 0.25;
            string testValueStringOverride = "Test Value String Override";
            string testProgressBarStatus   = "Test Progress Bar Status";

            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddProgressBar(testProgressBarTitle, testProgressBarValue, false, testValueStringOverride, testProgressBarStatus);

            // Assert
            Assert.AreSame(builder, anotherReference);
            var progressBar = builder.Content.Visual.BindingGeneric.Children.First() as AdaptiveProgressBar;

            Assert.IsNull(progressBar.Title.BindingName);
            Assert.AreEqual(testProgressBarTitle, (string)progressBar.Title);

            Assert.IsNull(progressBar.Value.BindingName);
            Assert.AreEqual(testProgressBarValue, ((AdaptiveProgressBarValue)progressBar.Value).Value);

            Assert.IsNull(progressBar.ValueStringOverride.BindingName);
            Assert.AreEqual(testValueStringOverride, (string)progressBar.ValueStringOverride);

            Assert.IsNull(progressBar.Status.BindingName);
            Assert.AreEqual(testProgressBarStatus, (string)progressBar.Status);
        }
Example #16
0
        public static ToastContentBuilder AddInlineImage(
            this ToastContentBuilder builder,
            string uri,
            string?alternateText       = default,
            bool?addImageQuery         = default,
            AdaptiveImageCrop?hintCrop = default,
            bool?hintRemoveMargin      = default)
        {
            var inlineImage = new AdaptiveImage
            {
                Source = uri
            };

            if (hintCrop != null)
            {
                inlineImage.HintCrop = hintCrop.Value;
            }

            if (alternateText != default)
            {
                inlineImage.AlternateText = alternateText;
            }

            if (addImageQuery != default)
            {
                inlineImage.AddImageQuery = addImageQuery;
            }

            return(builder.AddVisualChild(inlineImage));
        }
Example #17
0
        public void AddComboBoxTest_WithMultipleChoices_ReturnSelfWithComboBoxAndAllChoicesAdded()
        {
            // Arrange
            string testComboBoxId = Guid.NewGuid().ToString();
            var    choice1        = (Guid.NewGuid().ToString(), "Test Choice 1");
            var    choice2        = (Guid.NewGuid().ToString(), "Test Choice 2");
            var    choice3        = (Guid.NewGuid().ToString(), "Test Choice 3");

            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddComboBox(testComboBoxId, choice1, choice2, choice3);

            // Assert
            Assert.AreSame(builder, anotherReference);
            var comboBox = (builder.Content.Actions as ToastActionsCustom).Inputs.First() as ToastSelectionBox;

            Assert.AreEqual(testComboBoxId, comboBox.Id);
            Assert.AreEqual(choice1.Item1, comboBox.Items[0].Id);
            Assert.AreEqual(choice2.Item1, comboBox.Items[1].Id);
            Assert.AreEqual(choice3.Item1, comboBox.Items[2].Id);

            Assert.AreEqual(choice1.Item2, comboBox.Items[0].Content);
            Assert.AreEqual(choice2.Item2, comboBox.Items[1].Content);
            Assert.AreEqual(choice3.Item2, comboBox.Items[2].Content);
        }
Example #18
0
        public void AddArgumentTest_Generic_ReturnSelfWithArgumentsAdded()
        {
            // Arrange
            const string userIdKey   = "userId";
            const int    userIdValue = 542;

            // Act
            ToastContentBuilder builder          = new ToastContentBuilder();
            ToastContentBuilder anotherReference = builder
                                                   .AddButton(new ToastButton()
                                                              .SetContent("Accept")
                                                              .AddArgument("action", "accept")
                                                              .SetBackgroundActivation())
                                                   .AddButton(new ToastButtonSnooze())
                                                   .AddButton("View", ToastActivationType.Protocol, "https://msn.com")

                                                   // Add generic arguments halfway through (should be applied to existing buttons and to any subsequent buttons added later)
                                                   .AddArgument(userIdKey, userIdValue)

                                                   .AddButton(new ToastButton()
                                                              .SetContent("Decline")
                                                              .AddArgument("action", "decline")
                                                              .SetBackgroundActivation())
                                                   .AddButton(new ToastButton()
                                                              .SetContent("Report")
                                                              .SetProtocolActivation(new Uri("https://microsoft.com")));

            // Assert
            Assert.AreSame(builder, anotherReference);

            // Top level arguments should be present
            Assert.AreEqual("userId=542", builder.Content.Launch);

            // All foreground/background activation buttons should have received generic arguments. Protocol and system activation buttons shouldn't have had any arguments changed.
            var actions = builder.Content.Actions as ToastActionsCustom;

            var button1 = actions.Buttons[0] as ToastButton;

            Assert.AreEqual("Accept", button1.Content);
            Assert.AreEqual("action=accept;userId=542", button1.Arguments);

            var button2 = actions.Buttons[1];

            Assert.IsInstanceOfType(button2, typeof(ToastButtonSnooze));

            var button3 = actions.Buttons[2] as ToastButton;

            Assert.AreEqual("View", button3.Content);
            Assert.AreEqual("https://msn.com", button3.Arguments);

            var button4 = actions.Buttons[3] as ToastButton;

            Assert.AreEqual("Decline", button4.Content);
            Assert.AreEqual("action=decline;userId=542", button4.Arguments);

            var button5 = actions.Buttons[4] as ToastButton;

            Assert.AreEqual("Report", button5.Content);
            Assert.AreEqual("https://microsoft.com/", button5.Arguments);
        }
Example #19
0
        public static ToastContentBuilder AddAppLogoOverride(
            this ToastContentBuilder builder,
            string uri,
            ToastGenericAppLogoCrop?hintCrop = default,
            string?alternateText             = default,
            bool?addImageQuery = default)
        {
            var appLogoOverrideUri = new ToastGenericAppLogo
            {
                Source = uri
            };

            if (hintCrop is { } crop)
            {
                appLogoOverrideUri.HintCrop = crop;
            }

            if (alternateText is { } alt)
            {
                appLogoOverrideUri.AlternateText = alt;
            }

            if (addImageQuery is { } query)
            {
                appLogoOverrideUri.AddImageQuery = query;
            }

            AppLogoOverrideUriProperty.SetValue(builder, appLogoOverrideUri);

            return(builder);
        }
Example #20
0
        private void ShowNewContactToast(Contact contact)
        {
            string serializedContact = JsonConvert.SerializeObject(contact);
            var    content           = new ToastContentBuilder()
                                       .AddToastActivationInfo("NewContact", ToastActivationType.Foreground)
                                       .AddText($"{contact.Email}")
                                       .AddText($"{contact.Email} has added you to their contact list")
                                       .AddButton("Add to your list", ToastActivationType.Background, new QueryString()
            {
                { "action", "acceptContact" },
                { "contact", serializedContact }
            }.ToString())
                                       .AddButton("Dismiss", ToastActivationType.Background, new QueryString()
            {
                { "action", "Dismiss" }
            }.ToString())
                                       .GetToastContent();

            try
            {
                var notif = new ToastNotification(content.GetXml())
                {
                    Group = "newContacts"
                };
                ToastNotificationManager.CreateToastNotifier().Show(notif);
            }
            catch (ArgumentException) { }
        }
        public static void ShowPairedBleDeviceAddedToast(string name, string deviceId)
        {
            // Show Popup
            var content = new ToastContentBuilder()
                          .AddText("Your Paired Earbuds Device is Near", hintMaxLines: 1)
                          //.AddButton("Pair", ToastActivationType.Foreground, deviceId)
                          .AddButton(new ToastButton()
                                     .SetContent("Connect")
                                     .AddArgument("opcode", "device")
                                     .AddArgument("action", "connect")
                                     .AddArgument("deviceid", deviceId))
                          .AddText($"Connect to {name}")
                          .AddText($"DeviceId: {deviceId}")
                          .SetBackgroundActivation()
                          .AddAudio(new ToastAudio()
            {
                Silent = true
            })                                                // FIXME: For test Audio Manager
                          .SetToastDuration(ToastDuration.Short)
                          .GetToastContent();

            // Create the notification
            var notif = new ToastNotification(content.GetXml());

            // And show it!
            ToastNotificationManager.CreateToastNotifier().Show(notif);
        }
Example #22
0
        private void OnTimerFinished()
        {
            var notification = new ToastContentBuilder()
                               .AddText("Drink some water 💧", hintMaxLines: 1)
                               .AddText("Take O' Break");

            notification.Show();
        }
Example #23
0
        private void btn_Click(object sender, RoutedEventArgs e)
        {
            //Constructing the content
            var content = new ToastContentBuilder()
                          .AddToastActivationInfo("wtf", ToastActivationType.Foreground)
                          .AddText("First text")
                          .AddText("Second text")
                          .GetToastContent();

            //Create the notification
            var notif = new ToastNotification(content.GetXml());//for some reason it uses xml

            //Showing it
            //ToastNotificationManager.CreateToastNotifier().Show(notif);

            int strangeID = 384928;

            var content2 = new ToastContentBuilder()

                                                                     //Arguments returned when user taps body of notification
                           .AddToastActivationInfo(new QueryString() //Using QueryString.NET
            {
                { "action", "viewConversation" },
                { "conversationId", strangeID.ToString() }
            }.ToString(), ToastActivationType.Foreground)
                           .AddText("First Text")
                           .AddText("Second Text")
                           .AddText("Third Text")
                           .GetToastContent();

            var notif2 = new ToastNotification(content2.GetXml());

            //ToastNotificationManager.CreateToastNotifier().Show(notif2);

            //int conversationId = 384928;

            var contentImage = new ToastContentBuilder()

                               .AddToastActivationInfo(new QueryString() //Using QueryString.NET
            {
                { "action", "viewConversation" },
                { "conversationId", strangeID.ToString() }
            }.ToString(), ToastActivationType.Foreground)
                               .AddToastActivationInfo("bon _ver", ToastActivationType.Foreground)
                               .AddText("Sup")
                               .AddText("Some other information")
                               .AddInlineImage(new Uri("C:\\Users\\Maksym\\Pictures\\Saved Pictures\\20200121155057fed9ef42de.jpg"))
                               //Profile
                               .AddAppLogoOverride(new Uri("C:\\Users\\Maksym\\Pictures\\Saved Pictures\\weeknd.jpg"))
                               //Text box for replying
                               .AddInputTextBox("tbReply", placeHolderContent: "Type a response")
                               .GetToastContent();
            var notif3 = new ToastNotification(contentImage.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(notif3);

            //SendNotificationWithoutHistory(notif3);
        }
Example #24
0
        /// <summary>
        /// Handle background task completion.
        /// </summary>
        /// <param name="task">The task that is reporting completion.</param>
        /// <param name="e">Arguments of the completion report.</param>
        private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs eventArgs)
        {
            // We get the advertisement(s) processed by the background task
            if (ApplicationData.Current.LocalSettings.Values.Keys.Contains(taskName))
            {
                string backgroundMessage = (string)ApplicationData.Current.LocalSettings.Values[taskName];
                List <BLEAdvertisementInfo> advertisements = JsonConvert.DeserializeObject <List <BLEAdvertisementInfo> >(backgroundMessage);

                BluetoothAdapter defaultBtAdapter = await BluetoothAdapter.GetDefaultAsync();

                string localBtAddress = string.Join(":",
                                                    BitConverter.GetBytes(defaultBtAdapter.BluetoothAddress).Reverse().Select(b => b.ToString("X2"))).Substring(6).ToLower();

                foreach (var advertisement in advertisements)
                {
                    // Display these information on the list
                    advertisement.DeviceInformation = await GetDeviceInfo(localBtAddress, advertisement.ToBtAddressString());
                }

                // Serialize UI update to the main UI thread
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    ReceivedAdvertisementListBox.Items.Add(backgroundMessage);
                    foreach (var advertisement in advertisements)
                    {
                        // Display these information on the list
                        ReceivedAdvertisementListBox.Items.Add(getAdvertisementInfo(advertisement));
                    }


                    // Watcher may have stopped while we were waiting for our chance to run.
                    DeviceInformationDisplay devInfoDisplay = new DeviceInformationDisplay(advertisements[0].DeviceInformation);
                    int devInfoDisplayIndex = resultCollection.IndexOf(devInfoDisplay);
                    if (devInfoDisplayIndex == -1)
                    {
                        resultCollection.Add(devInfoDisplay);

                        // Show Popup
                        var content = new ToastContentBuilder()
                                      .AddToastActivationInfo("picOfHappyCanyon", ToastActivationType.Foreground)
                                      .AddButton("Connect", ToastActivationType.Foreground, devInfoDisplay.DeviceInformation.Id /*$"action=connect&deviceid={devInfoDisplay.DeviceInformation.Id}"*/)
                                      .AddText($"Connect to {devInfoDisplay.DeviceInformation.Id}")
                                      .AddText("Check this out, Happy Canyon in Utah!")
                                      .GetToastContent();

                        // Create the notification
                        var notif = new ToastNotification(content.GetXml());

                        // And show it!
                        ToastNotificationManager.CreateToastNotifier().Show(notif);
                    }
                    else
                    {
                        // Ignore
                    }
                });
            }
        }
        public static ToastNotification GetNotification(this ToastContentBuilder builder)
        {
            if (builder is null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            return(new ToastNotification(builder.GetToastXml()).SetToastHideOnDismiss());
        }
Example #26
0
        /// <summary>
        /// Method which sends a toast notification.
        /// </summary>
        /// <param name="text">The text of the notification</param>
        public static void SendToastNotification(string text)
        {
            ToastContentBuilder builder = new ToastContentBuilder().SetToastScenario(ToastScenario.Default)
                                          .AddToastActivationInfo("", ToastActivationType.Background)
                                          .AddHeader(NOTIFICATION_GROUP_ID, "", "")
                                          .AddText(text);

            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(builder.Content.GetXml()));
        }
Example #27
0
        public void AddTextTest_WithMaxLinesValueLargerThan2_ThrowArgumentOutOfRangeException()
        {
            // Arrange
            string testText1            = "Test Header";
            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            _ = builder.AddText(testText1, hintMaxLines: 3);
        }
Example #28
0
        public static void MakeToast(string text)
        {
            var content = new ToastContentBuilder()
                          .AddText(text)
                          .SetToastDuration(ToastDuration.Short)
                          .GetToastContent();
            var notification = new ToastNotification(content.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(notification);
        }
Example #29
0
        public static void ShowVideoCompleteNotice(IBiliDownload download)
        {
            var content = new ToastContentBuilder().AddToastActivationInfo("downloadCompleted", ToastActivationType.Foreground)
                          .AddText("下载完成")
                          .AddText($"{download.Title} - {download.DownloadName}")
                          .AddButton("播放", ToastActivationType.Foreground, $"video\n{download.OutputPath}")
                          .GetToastContent();

            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(content.GetXml()));
        }
Example #30
0
        public void AddArgumentTest_Escaping_ReturnSelfWithArgumentsAdded()
        {
            // Act
            ToastContentBuilder builder          = new ToastContentBuilder();
            ToastContentBuilder anotherReference = builder
                                                   .AddArgument("user;Id", "andrew=leader%26bares");

            // Assert
            Assert.AreSame(builder, anotherReference);
            Assert.AreEqual("user%3BId=andrew%3Dleader%2526bares", builder.Content.Launch);
        }