Example #1
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 #2
0
        public static XmlDocument GetXml(this NotificationContent content)
        {
            var builder = new ToastContentBuilder();

            builder.AddText(content.Title, AdaptiveTextStyle.Title);
            foreach (var l in content.Body)
            {
                builder.AddText(l, AdaptiveTextStyle.Body);
            }
            return(builder.Content.GetXml());
        }
        /// <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 #4
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);
        }
        private void PopToast()
        {
            // Generate the toast notification content
            ToastContentBuilder builder = new ToastContentBuilder();

            // Include launch string so we know what to open when user clicks toast
            builder.AddArgument("action", "viewForecast");
            builder.AddArgument("zip", 98008);

            // We'll always have this summary text on our toast notification
            // (it is required that your toast starts with a text element)
            builder.AddText("Today will be mostly sunny with a high of 63 and a low of 42.");

            // If Adaptive Toast Notifications are supported
            if (IsAdaptiveToastSupported())
            {
                // Use the rich Tile-like visual layout
                builder.AddVisualChild(new AdaptiveGroup()
                {
                    Children =
                    {
                        GenerateSubgroup("Mon", "Mostly Cloudy.png", 63, 42),
                        GenerateSubgroup("Tue", "Cloudy.png",        57, 38),
                        GenerateSubgroup("Wed", "Sunny.png",         59, 43),
                        GenerateSubgroup("Thu", "Sunny.png",         62, 42),
                        GenerateSubgroup("Fri", "Sunny.png",         71, 66)
                    }
                });
            }

            // Otherwise...
            else
            {
                // We'll just add two simple lines of text
                builder
                .AddText("Monday ⛅ 63° / 42°")
                .AddText("Tuesday ☁ 57° / 38°");
            }

            // Set the base URI for the images, so we don't redundantly specify the entire path
            builder.Content.Visual.BaseUri = new Uri("Assets/NotificationAssets/", UriKind.Relative);

            // Show the toast
            builder.Show();
        }
Example #6
0
        public static void Display(IEnumerable <string> messages)
        {
            // Requires Microsoft.Toolkit.Uwp.Notifications NuGet package version 7.0 or greater
            //Toast
            var toast = new ToastContentBuilder();

            toast.AddArgument("action", "viewConversation");
            toast.AddArgument("conversationId", 9813);
            toast.AddText("Illumination problems detected!");
            foreach (var m in messages)
            {
                if (!string.IsNullOrEmpty(m))
                {
                    toast.AddText(m);
                }
            }
            toast.Show(); // Not seeing the Show() method? Make sure you have version 7.0, and if you're using .NET 5, your TFM must be net5.0-windows10.0.17763.0 or greater
        }
Example #7
0
        public void AddTextTest_WithMaxLinesValueLargerThan2_ThrowArgumentOutOfRangeException()
        {
            // Arrange
            string testText1            = "Test Header";
            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            _ = builder.AddText(testText1, hintMaxLines: 3);
        }
Example #8
0
        private async void NotiBootstrap()
        {
            var builder = new ToastContentBuilder();

            try
            {
                var infos = await AppDiagnosticInfo.RequestInfoForAppAsync();

                var   resourceInfos = infos[0].GetResourceGroups();
                await resourceInfos[0].StartSuspendAsync();

                if (UWPAppEnvironment.toastNotifier == null)
                {
                    UWPAppEnvironment.toastNotifier = ToastNotificationManager.CreateToastNotifier();
                }

                var notiUWP = new NotiScheduleUWP();

                notiUWP.CancelAll();
                notiUWP.ScheduleAll();

                builder.AddToastActivationInfo("BootNotiRegister", ToastActivationType.Foreground);
                builder.AddText(AppResources.BootAlarmRegisterSuccess);
            }
            catch (Exception)
            {
                builder.AddText(AppResources.BootAlarmRegisterFail);
            }
            finally
            {
                if (builder != null)
                {
                    UWPAppEnvironment.toastNotifier.AddToSchedule(new ScheduledToastNotification(builder.GetToastContent().GetXml(), DateTime.Now.AddSeconds(3)));
                }

                await Task.Delay(3000);

                Exit();
            }
        }
Example #9
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());
                DesktopNotificationManagerCompat.CreateToastNotifier().Show(toast);
            });
        }
Example #10
0
        private void OnRafflesWon(object sender, RafflesWonArgs e)
        {
            bool enableToast = Properties.UserConfig.Default.ToastNotifications;

            if (enableToast)
            {
                string logo = Files.LogoFile;
                if (!File.Exists(logo))
                {
                    using (var http = new HttpClient())
                    {
                        string url  = string.Format("https://scrap.tf/apple-touch-icon.png?{0}", Guid.NewGuid());
                        byte[] data = http.GetByteArrayAsync(url).Result;
                        File.WriteAllBytes(logo, data);
                    }
                }

                string message    = e.Message;
                var    viewButton = new ToastButton();
                viewButton.AddArgument("action", "viewRafflesWonPage");
                viewButton.SetContent("View Won Raffles");

                var dismissButton = new ToastButton();
                dismissButton.SetContent("Dismiss");
                dismissButton.SetDismissActivation();

                var toast = new ToastContentBuilder();
                toast.AddAppLogoOverride(new Uri(logo), ToastGenericAppLogoCrop.Circle, null, false);
                toast.AddAttributionText(string.Format("Scraps {0}", Common.Constants.Version.Full));
                toast.AddText("Items Need Withdrawing");
                toast.AddText(message);
                toast.AddButton(viewButton);
                toast.AddButton(dismissButton);
                toast.Show();
            }
        }
Example #11
0
        public void AddTextTest_WithSimpleText_ReturnSelfWithTextAdded()
        {
            // Arrange
            string testText             = "Test Text";
            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddText(testText);

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

            Assert.AreEqual(testText, (string)text.Text);
        }
Example #12
0
        public void AddTextTest_WithMoreThan4LinesOfText_ThrowInvalidOperationException()
        {
            // Arrange
            string testText1            = "Test Header";
            string testText2            = "Test Text";
            string testText3            = "Test Text Again";
            string testText4            = "Test Text Again x2";
            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            _ = builder.AddText(testText1)
                .AddText(testText2)
                .AddText(testText3)
                .AddText(testText4);
        }
Example #13
0
        private static XmlDocument GeneratePayload(AccountDataItem account, ViewItemSchedule s)
        {
            var c = s.Class;

            var builder = new ToastContentBuilder()
                          .AddToastActivationInfo(new ViewClassArguments()
            {
                LocalAccountId = account.LocalAccountId,
                ItemId         = c.Identifier,
                LaunchSurface  = LaunchSurface.Toast
            }.SerializeToString(), ToastActivationType.Foreground)
                          .SetToastScenario(ToastScenario.Reminder)
                          .AddText(c.Name)
                          .AddText(string.Format(_timeToTime, _timeFormatter.Format(s.StartTime), _timeFormatter.Format(s.EndTime)));

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

            builder.AddToastInput(new ToastSelectionBox("snoozeTime")
            {
                DefaultSelectionBoxItemId = "5",
                Items =
                {
                    new ToastSelectionBoxItem("5",  PowerPlannerResources.GetXMinutes(5)),
                    new ToastSelectionBoxItem("10", PowerPlannerResources.GetXMinutes(10)),
                    new ToastSelectionBoxItem("15", PowerPlannerResources.GetXMinutes(15)),
                    new ToastSelectionBoxItem("30", PowerPlannerResources.GetXMinutes(30)),
                    new ToastSelectionBoxItem("45", PowerPlannerResources.GetXMinutes(45))
                }
            });

            builder.AddButton(new ToastButtonSnooze()
            {
                SelectionBoxId = "snoozeTime"
            });

            builder.AddButton(new ToastButtonDismiss());

            return(builder.GetToastContent().GetXml());
        }
Example #14
0
        public void AddTextTest_WithMultipleTexts_ReturnSelfWithAllTextsAdded()
        {
            // Arrange
            string testText1            = "Test Header";
            string testText2            = "Test Text";
            string testText3            = "Test Text Again";
            ToastContentBuilder builder = new ToastContentBuilder();

            // Act
            ToastContentBuilder anotherReference = builder.AddText(testText1)
                                                   .AddText(testText2)
                                                   .AddText(testText3);

            // Assert
            Assert.AreSame(builder, anotherReference);
            var texts = builder.Content.Visual.BindingGeneric.Children.Take(3).Cast <AdaptiveText>().ToList();

            Assert.AreEqual(testText1, (string)texts[0].Text);
            Assert.AreEqual(testText2, (string)texts[1].Text);
            Assert.AreEqual(testText3, (string)texts[2].Text);
        }
Example #15
0
        public void SendNotification(string header, string content)
        {
            this.id += 1;
            ToastContentBuilder toast = new ToastContentBuilder().AddArgument("tag", this.id.ToString()).AddText(header);

            if (!string.IsNullOrEmpty(content))
            {
                toast.AddText(content);
            }

            ToastNotification notification = new ToastNotification(toast.GetXml());

            notification.ExpirationTime = DateTime.Now.AddDays(1);
            notification.Group          = "HandBrake";
            notification.Tag            = this.id.ToString();

            if (this.notifier != null)
            {
                notifier.Show(notification);
            }
        }
Example #16
0
        private void ShowUpdateNotification()
        {
            if (ApplicationData.Current.LocalSettings.Values["LanguageOverride"] is int LanguageIndex)
            {
                ToastNotificationManager.History.Clear();

                ToastContentBuilder Builder = new ToastContentBuilder()
                                              .SetToastScenario(ToastScenario.Default)
                                              .AddToastActivationInfo("ms-windows-store://pdp/?productid=9N88QBQKF2RS", ToastActivationType.Protocol);
                switch (LanguageIndex)
                {
                case 0:
                {
                    Builder.AddText("针对RX文件管理器的更新已发布!", AdaptiveTextStyle.Title)
                    .AddText("包含最新的功能和改进", AdaptiveTextStyle.Subtitle)
                    .AddText("点击以立即更新", AdaptiveTextStyle.Subtitle);

                    break;
                }

                case 1:
                {
                    Builder.AddText("An update for the RX-Explorer is available!", AdaptiveTextStyle.Title)
                    .AddText("Includes the latest features and improvements", AdaptiveTextStyle.Subtitle)
                    .AddText("Click to update now", AdaptiveTextStyle.Subtitle);

                    break;
                }

                case 2:
                {
                    Builder.AddText("Une mise à jour pour RX Explorer est disponible!", AdaptiveTextStyle.Title)
                    .AddText("Comprend les dernières fonctionnalités et améliorations", AdaptiveTextStyle.Subtitle)
                    .AddText("Cliquez pour mettre à jour maintenant", AdaptiveTextStyle.Subtitle);

                    break;
                }

                case 3:
                {
                    Builder.AddText("RX檔案管家的更新已發布!", AdaptiveTextStyle.Title)
                    .AddText("包括最新功能和改進", AdaptiveTextStyle.Subtitle)
                    .AddText("點擊立即更新", AdaptiveTextStyle.Subtitle);

                    break;
                }

                case 4:
                {
                    Builder.AddText("¡Se ha lanzado una actualización para el administrador de archivos RX!", AdaptiveTextStyle.Title)
                    .AddText("Contiene las últimas funciones y mejoras.", AdaptiveTextStyle.Subtitle)
                    .AddText("Haga clic para actualizar ahora", AdaptiveTextStyle.Subtitle);

                    break;
                }

                case 5:
                {
                    Builder.AddText("Ein Update für den RX-Dateimanager wurde veröffentlicht!", AdaptiveTextStyle.Title)
                    .AddText("Enthält die neuesten Funktionen und Verbesserungen", AdaptiveTextStyle.Subtitle)
                    .AddText("Klicken Sie hier, um jetzt zu aktualisieren", AdaptiveTextStyle.Subtitle);

                    break;
                }
                }

                ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(Builder.GetToastContent().GetXml()));
            }
        }
        private static XmlDocument GenerateXml(Notification notification)
        {
#if NETSTANDARD
            var sw = new StringWriter();
            var xw = XmlWriter.Create(sw, new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Indent             = true
            });

            xw.WriteStartElement("toast");

            xw.WriteStartElement("visual");

            xw.WriteStartElement("binding");

            xw.WriteAttributeString("template", "ToastGeneric");

            xw.WriteStartElement("text");
            xw.WriteString(notification.Title ?? string.Empty);
            xw.WriteEndElement();

            xw.WriteStartElement("text");
            xw.WriteString(notification.Body ?? string.Empty);
            xw.WriteEndElement();

            xw.WriteEndElement();

            xw.WriteEndElement();

            xw.WriteStartElement("actions");

            foreach (var(title, actionId) in notification.Buttons)
            {
                xw.WriteStartElement("action");
                xw.WriteAttributeString("content", title);
                xw.WriteAttributeString("activationType", "foreground");
                xw.WriteAttributeString("arguments", actionId);
                xw.WriteEndElement();
            }

            xw.WriteEndElement();

            xw.WriteEndElement();
            xw.Flush();

            var xmlStr = sw.ToString();
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlStr);

            return(xmlDoc);
#else
            var builder = new ToastContentBuilder();

            builder.AddText(notification.Title);
            builder.AddText(notification.Body);

            foreach (var(title, actionId) in notification.Buttons)
            {
                builder.AddButton(title, ToastActivationType.Foreground, actionId);
            }

            return(builder.GetXml());
#endif
        }
Example #18
0
        public void MediatorContext_OnEarthquake(object sender, Client.Peer.EPSPQuakeEventArgs e)
        {
            if (e.InformationType == QuakeInformationType.Unknown)
            {
                return;
            }

            var earthquakeNotification = configuration.EarthquakeNotification;

            if (!earthquakeNotification.Enabled)
            {
                return;
            }
            if (!earthquakeNotification.Notice)
            {
                return;
            }

            // 震源情報は震度 3 以上で発表されるため、震度 3 とみなす
            var scale =
                e.InformationType == QuakeInformationType.Destination ?
                30 :
                ScaleConverter.Str2Int(e.Scale);

            if (scale < earthquakeNotification.MinScale)
            {
                return;
            }

            var builder = new ToastContentBuilder();

            // タイトル行
            var type = e.InformationType switch
            {
                QuakeInformationType.ScalePrompt => "震度速報",
                QuakeInformationType.Destination => "震源情報",
                QuakeInformationType.ScaleAndDestination => "震源・震度情報",
                QuakeInformationType.Detail => "地震情報",
                QuakeInformationType.Foreign => "遠地(海外)地震情報",
                _ => "地震情報",
            };

            if (e.InformationType == QuakeInformationType.Foreign || e.InformationType == QuakeInformationType.Destination)
            {
                builder.AddText($"{type} ({e.OccuredTime})");
            }
            else
            {
                builder.AddText($"{type} ({e.OccuredTime} 震度{e.Scale})");
            }

            if (e.InformationType == QuakeInformationType.ScalePrompt)
            {
                var maxScaleGroup = e.PointList.OrderBy(e => e.ScaleInt).Reverse().GroupBy(e => e.Scale).First();
                builder.AddText($"震度{maxScaleGroup.Key}: {string.Join('、', maxScaleGroup.Select(e => e.Name))}");
            }
            else
            {
                var tsunamiDescription = e.TsunamiType switch
                {
                    DomesticTsunamiType.None => "津波の心配なし",
                    DomesticTsunamiType.Checking => "津波の有無調査中",
                    DomesticTsunamiType.Effective => "津波予報 発表中",
                    _ => "津波の有無不明",
                };
                builder.AddText($"{e.Destination} (深さ{e.Depth}, {e.Magnitude}) {tsunamiDescription}");
            }

            builder.AddArgument("type", "quake").AddArgument("receivedAt", e.ReceivedAt.ToString());
            builder.Show();
        }
Example #19
0
 NotificationBuilder AddTitle(string title)
 {
     tbc.AddText(title, AdaptiveTextStyle.Title);
     return(this);
 }