Example #1
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;
            });
        }
        /// <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 #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
        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 #5
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 #6
0
        private void OnTimerFinished()
        {
            var notification = new ToastContentBuilder()
                               .AddText("Drink some water 💧", hintMaxLines: 1)
                               .AddText("Take O' Break");

            notification.Show();
        }
        public void Send(string title, string content, DateTime dateStart, DateTime dateDismiss)
        {
            ToastContentBuilder toastNotify = new ToastContentBuilder()
                                              .AddText(title)
                                              .AddText(content)
                                              .AddCustomTimeStamp(dateStart);

            toastNotify.Show(toast =>
            {
                toast.Tag            = Utilities.MD5Hash(dateDismiss.ToString());
                toast.Group          = Utilities.MD5Hash(title);
                toast.ExpirationTime = dateDismiss;
            });
        }
Example #8
0
        public static void ShowTextToastNotification(string title, string content, string?logoUri = null, Action <ToastContentBuilder>?contentBuilder = null)
        {
            var builder = new ToastContentBuilder()
                          .AddText(title, AdaptiveTextStyle.Header)
                          .AddText(content, AdaptiveTextStyle.Caption);

            contentBuilder?.Invoke(builder);
            if (logoUri is not null)
            {
                builder.AddAppLogoOverride(logoUri, ToastGenericAppLogoCrop.Default);
            }

            builder.Show();
        }
Example #9
0
        /// <summary>
        /// Show a toast notification by providing the Content, Purpose, and optionally Device IP and MAC (for device blocking handling scenarios).
        /// </summary>
        /// <param name="Content"></param>
        /// <param name="Purpose"></param>
        /// <param name="DeviceId"></param>
        public static void ShowPrompt(string Content, NotificationPurpose Purpose, string DeviceIP = "", string DeviceMAC = "")
        {
            var Toast = new ToastContentBuilder()
                        .AddArgument("Action", Purpose)
                        .AddArgument("DeviceIP", DeviceIP)
                        .AddArgument("DeviceMAC", DeviceMAC)
                        .AddText("NetStalker")
                        .AddText(Content);

            switch (Purpose)
            {
            case NotificationPurpose.NotificationsSuppression:
            {
                Toast.AddButton(new ToastButton()
                                .SetContent("Yes")
                                .AddArgument("Choice", NotificationChoice.Yes))
                .AddButton(new ToastButton()
                           .SetContent("No")
                           .AddArgument("Choice", NotificationChoice.No));

                break;
            }

            case NotificationPurpose.TargetDiscovery:
            {
                Toast.AddButton(new ToastButton()
                                .SetContent("Show")
                                .AddArgument("Choice", NotificationChoice.Show))
                .AddButton(new ToastButton()
                           .SetContent("Block")
                           .AddArgument("Choice", NotificationChoice.Block))
                .AddButton(new ToastButtonDismiss())
                .AddButton(new ToastButton()
                           .SetContent("Suppress Notifications")
                           .AddArgument("Choice", NotificationChoice.Suppress));

                break;
            }

            default:
            {
                Toast = null;
                return;
            }
            }

            Toast.Show();
        }
        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 #11
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 #12
0
        public async Task Send(Notification notification)
        {
            // create the notification to validate it
            if (notification.Id == 0)
            {
                notification.Id = this.services.Settings.IncrementValue("NotificationId");
            }

            var builder = new ToastContentBuilder()
                          .AddText(notification.Title, AdaptiveTextStyle.Title)
                          .AddText(notification.Message, AdaptiveTextStyle.Subtitle)
                          .SetToastDuration(ToastDuration.Short)
                          .AddToastActivationInfo(notification.Id.ToString(), ToastActivationType.Foreground);

            await this.TrySetChannel(notification, builder);

            if (notification.ScheduleDate != null)
            {
                await this.services.Repository.Set(notification.Id.ToString(), notification);

                // TODO: set badge and fire notification fired?
                builder.Schedule(notification.ScheduleDate.Value);
            }
            else
            {
                if (notification.BadgeCount != null)
                {
                    this.Badge = notification.BadgeCount.Value;
                }

                builder.Show(new CustomizeToast(x =>
                {
                    //x.Activated += null;
                    //x.Dismissed += null;
                    x.Tag = notification.Id.ToString();
                    //x.Group = "";
                    //x.Priority
                }));
            }
        }
Example #13
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 #14
0
        public void checkChanges()
        {
            bool   blPaused       = NotificationsPaused();
            string strDocsChanged = "";

            tmrCheck.Stop();
            log("Checking changes", 5);
            if (credential == null)
            {
                getCredentials();
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // List files.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.Fields = "nextPageToken, files(id, name, lastModifyingUser(displayName), modifiedTime, parents, trashed, webViewLink)";

            var response = listRequest.Execute();
            IList <Google.Apis.Drive.v3.Data.File> files = response.Files;

            Console.WriteLine("Files:");

            //List<ToastContentBuilder> lstToasts = new List<ToastContentBuilder>();
            string strDocChangeKey = "";

            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    FileState fileState = null;
                    if (driveState.FileStates.ContainsKey(file.Id))
                    {
                        fileState = driveState.FileStates[file.Id];
                    }

                    // Determine if we know who last edited the file
                    string lastEditBy = "Unknown";
                    if (file.LastModifyingUser != null && file.LastModifyingUser.DisplayName != null)
                    {
                        lastEditBy = file.LastModifyingUser.DisplayName;
                    }

                    bool blnShowToast = (fileState == null || file.ModifiedTime > fileState.lastEditWhen.AddSeconds(Properties.Settings.Default.CheckSeconds * 5) || fileState.lastEditBy != lastEditBy);
                    updateFileState(file);

                    if (file.ModifiedTime > datLast && !excludedFiles.ContainsKey(file.Id) && Properties.Settings.Default.MyName != lastEditBy)
                    {
                        // If this is a new file or the file hasn't been edited in a while or the file has been edited by someone new then notify
                        if (blnShowToast && !blPaused)
                        {
                            // Build the basic toast config
                            ToastContentBuilder tst = new ToastContentBuilder()
                                                      .AddArgument("action", "viewFile")
                                                      .AddArgument("fileId", file.Id)
                                                      .AddArgument("url", file.WebViewLink)
                                                      .AddText(file.Name);

                            // Set the toast duration based on settings.
                            if (Properties.Settings.Default.LongNotification)
                            {
                                tst = tst.SetToastDuration(ToastDuration.Long);
                            }
                            else
                            {
                                tst = tst.SetToastDuration(ToastDuration.Short);
                            }

                            // Try and set the EditBy and modified time.
                            try
                            {
                                tst = tst.AddCustomTimeStamp((DateTime)file.ModifiedTime);
                                if (file.ModifiedTime.Value.Date == DateTime.Now.Date)
                                {
                                    tst = tst.AddAttributionText(lastEditBy + " @ " + string.Format("{0:HH:mm}", file.ModifiedTime.Value));
                                }
                                else
                                {
                                    tst = tst.AddAttributionText(lastEditBy + " @ " + string.Format("{0:HH:mm dd/MM/yyyy}", file.ModifiedTime.Value));
                                }
                            }
                            catch (Exception)
                            {
                                // We failed so just set the EditBy
                                tst = tst.AddAttributionText(lastEditBy);
                            }

                            // Display the toast
                            tst.Show();
                        }
                        //lstToasts.Add(tst);

                        strDocChangeKey += file.Name + "|" + lastEditBy + "|";
                        if (file.Name.Length > 35)
                        {
                            strDocsChanged += file.Name.Substring(0, 34) + Environment.NewLine;
                        }
                        else
                        {
                            strDocsChanged += file.Name + Environment.NewLine;
                        }
                        setIcon("red");
                    }
                    log(file.Name, 10);
                }
            }
            else
            {
                log("No files found.", 10);
            }
            if (strDocChangeKey != "")
            {
                if (Properties.Settings.Default.WindowsNotifications && strDocChangeKey != strLastTip)
                {
                    strLastTip = strDocChangeKey;
                    //foreach (ToastContentBuilder tst in lstToasts)
                    //{
                    //    tst.Show();
                    //}
                }
                if (strDocsChanged.Length > 64)
                {
                    nfyIcon.Text = strDocsChanged.Substring(0, 63);
                }
                else
                {
                    nfyIcon.Text = strDocsChanged;
                }
            }
            else
            {
                strLastTip   = "";
                nfyIcon.Text = "No changes";
            }
            saveState();
            showFiles();
            tmrCheck.Interval = Properties.Settings.Default.CheckSeconds * 1000;
            tmrCheck.Start();
        }
 public Task ShowNotification(ToastContentBuilder toastContentBuilder, CustomizeToast customizeToast)
 {
     return(dispatcher.InvokeAsync(() => toastContentBuilder.Show(customizeToast)).Task);
 }
 public static void showLearnEndNotification()
 {
     learnEndNotification.Show();
 }
 public static void showBreakEndNotification()
 {
     breakEndNotification.Show();
 }
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();
        }