private async void OnReminderButtonClicked(object sender, RoutedEventArgs e)
        {
            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();

            if (notifier.Setting != NotificationSetting.Enabled)
            {
                var dialog = new MessageDialog("Notifications are currently disabled");
                await dialog.ShowAsync();

                return;
            }

            ToastTemplateType toastTemplate     = ToastTemplateType.ToastText01;
            XmlDocument       toastXml          = ToastNotificationManager.GetTemplateContent(toastTemplate);
            XmlNodeList       toastTextElements = toastXml.GetElementsByTagName("text");

            toastTextElements[0].AppendChild(toastXml.CreateTextNode("Reminder! Check Friends With Paws"));
            var date = DateTimeOffset.Now.AddSeconds(15);
            var stnA = new ScheduledToastNotification(toastXml, date);

            notifier.AddToSchedule(stnA);

            ToastTemplateType toastTemplateB     = ToastTemplateType.ToastText01;
            XmlDocument       toastXmlB          = ToastNotificationManager.GetTemplateContent(toastTemplateB);
            XmlNodeList       toastTextElementsB = toastXmlB.GetElementsByTagName("text");

            toastTextElementsB[0].AppendChild(toastXmlB.CreateTextNode("Please check what's new with Friends With Paws"));
            var      dateB      = DateTimeOffset.Now.AddSeconds(60);
            IXmlNode toastNodeB = toastXmlB.SelectSingleNode("/toast");

            ((XmlElement)toastNodeB).SetAttribute("duration", "long");
            var stnB = new ScheduledToastNotification(toastXmlB, dateB);

            notifier.AddToSchedule(stnB);
        }
Exemple #2
0
        /// <summary>
        /// Creates a scheduled toast notification with the passed <paramref name="alarmToSchedule"/>'s information to be displayed by the user at the alarm's activate date and time
        /// </summary>
        /// <param name="alarmToSchedule"></param>
        public static void ScheduleAlarm(Alarm alarmToSchedule)
        {
            var toast = new ScheduledToastNotification(CreateAlarmToast(alarmToSchedule).GetXml(), alarmToSchedule.ActivateDateAndTime);

            toast.Id    = GetAlarmNotificationID(alarmToSchedule);
            toast.Group = TOAST_GROUP;
            toast.Tag   = toast.Id;
            toastNotifier.AddToSchedule(toast);
        }
        /// <summary>
        /// Notifies the specified notification.
        /// </summary>
        /// <param name="notification">The notification.</param>
        public object Notify(LocalNotification notification)
        {
            //https://docs.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/send-local-toast

            string id = (staticId++).ToString();

            if (notification.Parameter == null)
            {
                toastXml.DocumentElement.RemoveAttribute("launch");
            }
            else
            {
                toastXml.DocumentElement.SetAttribute("launch", notification.Parameter);
            }

            titleElem.InnerText   = notification.Title;
            contentElem.InnerText = notification.Text;

            notifier.AddToSchedule(new ScheduledToastNotification(toastXml, notification.NotifyTime)
            {
                Id = id,
            });

            return(id);
        }
Exemple #4
0
        public static void wyswietlNotyfikacje()
        {
            XmlNodeList toastTextAttributes = toastXml.GetElementsByTagName("text");

            String napis;

            //losowanie
            Random r = new Random();
            int    x = r.Next(0, i);

            try
            {
                napis = dane[x];
            }
            catch (Exception) {
                napis = "Pusty słownik.";
            };


            toastTextAttributes[0].InnerText = napis;

            //okreslenie kiedy ma sie pojawic:
            Int16    odstepSek = 1;
            DateTime dueTime   = DateTime.Now.AddSeconds(odstepSek);

            ScheduledToastNotification scheduledToast = new ScheduledToastNotification(toastXml, dueTime);
            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.AddToSchedule(scheduledToast);
        }
Exemple #5
0
        // 添加指定的 ScheduledToastNotification 到计划列表中
        private void btnAddScheduledToast_Click(object sender, RoutedEventArgs e)
        {
            string toastXml = $@"
                <toast activationType='foreground' launch='Notification-Toast-Schedule-Arguments'>
                    <visual>
                        <binding template='ToastGeneric'>
                            <text>toast - title</text>
                            <text>toast - content {DateTime.Now.ToString("mm:ss")}</text>
                        </binding>
                    </visual>
                </toast>";

            // 将 xml 字符串转换为 Windows.Data.Xml.Dom.XmlDocument 对象
            XmlDocument toastDoc = new XmlDocument();

            toastDoc.LoadXml(toastXml);

            // 实例化 ScheduledToastNotification 对象(15 秒后显示此 Toast 通知,然后每隔 60 秒再显示一次 Toast,循环显示 5 次)
            // 但是经测试,只会显示一次,无法循环显示,不知道为什么
            // ScheduledToastNotification toastNotification = new ScheduledToastNotification(toastDoc, DateTime.Now.AddSeconds(15), TimeSpan.FromSeconds(60), 5);

            // 实例化 ScheduledToastNotification 对象(15 秒后显示此 Toast 通知)
            ScheduledToastNotification toastNotification = new ScheduledToastNotification(toastDoc, DateTime.Now.AddSeconds(15));

            toastNotification.Id  = new Random().Next(100000, 1000000).ToString();
            toastNotification.Tag = toastDoc.GetElementsByTagName("text")[1].InnerText;

            // 将指定的 ScheduledToastNotification 添加进计划列表
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();

            toastNotifier.AddToSchedule(toastNotification);

            ShowScheduledToasts();
        }
Exemple #6
0
        public static void ScheduleToast(DateTime timeToAppearAt)
        {
            // If in the past or within 5 seconds, don't schedule
            if (timeToAppearAt <= DateTime.Now.AddSeconds(5))
            {
                throw new ArgumentException("timeToAppearAt must be at least 5 seconds in the future.");
            }

            // Generate a RemoteId for the specified time
            string remoteId = GetRemoteId(timeToAppearAt);

            // If this notification is already scheduled
            if (IsScheduled(timeToAppearAt))
            {
                // Do nothing
                return;
            }

            // Create the notification's content
            XmlDocument toastContent = CreateToastContent(timeToAppearAt, remoteId);

            ScheduledToastNotification notif = new ScheduledToastNotification(toastContent, timeToAppearAt)
            {
                RemoteId = remoteId
            };

            // And schedule the toast
            _toastNotifier.AddToSchedule(notif);
        }
Exemple #7
0
        /// <summary>
        /// Event Handler for the Expiration Reminder Slider when user changes the value
        /// Enables alarm
        /// </summary>
        /// <param name="sender"> Object which indicates where the event occured </param>
        /// <param name="e"> An object that contains information about the event </param>
        void ExpirationReminderSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            ExpirationReminderSlider.Value = Math.Round(ExpirationReminderSlider.Value, 0);



            if (ExpirationReminderSlider.Value == 1)
            {
                customAlarmScheduledToast = new ScheduledToastNotification(toastXml,
                                                                           new DateTime(MainSettings.GetValueOrDefault("TimeReminderKeyName", DateTime.Now.Ticks + 20000000)));
                toastNotifier.AddToSchedule(customAlarmScheduledToast);

                ExpirationTimeLabel.Foreground = (SolidColorBrush)App.Current.Resources["PhoneAccentBrush"];

                return;
            }
            else
            {
                //if(toastNotifier.GetScheduledToastNotifications[0].equals(customAlarmScheduledToast))
                {
                    toastNotifier.RemoveFromSchedule(customAlarmScheduledToast);
                }
            }
            if ((Visibility)App.Current.RequestedTheme == Windows.UI.Xaml.Visibility.Collapsed)
            {
                ExpirationTimeLabel.Foreground = new SolidColorBrush(Colors.WhiteSmoke);
            }
            else
            {
                ExpirationTimeLabel.Foreground = new SolidColorBrush(Colors.DarkGray);
            }
        }
Exemple #8
0
        public ScheduledToastCancellation(ScheduledToastNotification toastNotification)
        {
            this.toastNotifier     = ToastNotificationManager.CreateToastNotifier();
            this.toastNotification = toastNotification;
            ToastId = ToastId.FromNotification(toastNotification);

            toastNotifier.AddToSchedule(toastNotification);
        }
        /// <summary>
        /// Adds a ScheduledToastNotification for later display by Windows.
        /// </summary>
        /// <param name="scheduledToast">The scheduled toast notification, which includes its content and timing instructions.</param>
        public void AddToSchedule(ScheduledToastNotification scheduledToast)
        {
#if WIN32
            ToastNotificationManagerCompat.PreRegisterIdentityLessApp();

            PreprocessScheduledToast(scheduledToast);
#endif

            _notifier.AddToSchedule(scheduledToast);
        }
        public static string ScheduleNotification(XmlDocument toastXml, DateTimeOffset date)
        {
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();

            Debug.WriteLine("Date " + date);
            ScheduledToastNotification customAlarmScheduledToast = new ScheduledToastNotification(toastXml, date);

            toastNotifier.AddToSchedule(customAlarmScheduledToast);
            return(customAlarmScheduledToast.Id);
        }
        private static string ScheduleToastNotification(string text, DateTimeOffset notificationTime, string notificationId, ToastNotifier toastNotifier)
        {
            var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

            toastXml.GetElementsByTagName("text")[0].AppendChild(toastXml.CreateTextNode(text));
            var toastNotificaiton = new ScheduledToastNotification(toastXml, notificationTime);

            toastNotificaiton.Id = notificationId;
            toastNotifier.AddToSchedule(toastNotificaiton);
            return(toastNotificaiton.Id);
        }
Exemple #12
0
        private void AddToast(string id, string name, string glyph, DateTime start, DateTime finish)
        {
            XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

            xml.GetElementsByTagName("text")[0].InnerText = $"{glyph} {name}";
            xml.GetElementsByTagName("text")[1].InnerText = $"Start {start:HH:mm} Finish {finish:HH:mm}";
            ScheduledToastNotification toast = new ScheduledToastNotification(xml, finish)
            {
                Id = id
            };

            _notifier.AddToSchedule(toast);
        }
Exemple #13
0
        public void ScheduleNotification(DayOfWeek dayOfWeek, TimeSpan time)
        {
            var now = DateTime.Now;
            ScheduledToastNotification notification = null;
            var notificationDate = GetNextWeekday(now, dayOfWeek).Date + time;

            if (notificationDate > now)
            {
                notification = CreateNotification(notificationDate);
                _notificationManager.AddToSchedule(notification);
            }
            notification = CreateNotification(notificationDate.AddDays(7));
            _notificationManager.AddToSchedule(notification);

            notification = CreateNotification(notificationDate.AddDays(14));
            _notificationManager.AddToSchedule(notification);

            notification = CreateNotification(notificationDate.AddDays(21));
            _notificationManager.AddToSchedule(notification);

            notification = CreateNotification(notificationDate.AddDays(28));
            _notificationManager.AddToSchedule(notification);
        }
Exemple #14
0
        static void Schedule(
            ToastNotifier notifier, XmlDocument doc)
        {
            var notification = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddMinutes(1));

            notification.Tag            = START_NOTIFICATION_ID;
            notification.ExpirationTime = DateTimeOffset.Now.AddMinutes(2);
            notification.SuppressPopup  = true;

            notifier.AddToSchedule(notification);
            notifier.ScheduledToastNotificationShowing += (_, a) =>
            {
                notifier.RemoveFromSchedule(notification);
                Schedule(notifier, doc);
            };
        }
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            var date = MyDatePicker.Date;
            var time = MyHourPicker.Time;

            DateTime dateTime = new DateTime(date.Year, date.Month, date.Day, time.Hours, time.Minutes, time.Seconds);

            string title   = Title.Text;
            string content = Content.Text;


            ToastTemplateType toastType = ToastTemplateType.ToastText02;
            XmlDocument       toastXml  = ToastNotificationManager.GetTemplateContent(toastType);

            XmlNodeList toastTextElement = toastXml.GetElementsByTagName("text");

            toastTextElement[0].AppendChild(toastXml.CreateTextNode(title));
            toastTextElement[1].AppendChild(toastXml.CreateTextNode(content));

            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", "long");

            ScheduledToastNotification sheduledToast = new ScheduledToastNotification(toastXml, dateTime);

            sheduledToast.Id = IdService.GetNewId();


            ToastNotifier notifier =
                ToastNotificationManager.CreateToastNotifier();

            notifier.AddToSchedule(sheduledToast);

            NotificationItem notItem = new NotificationItem();

            notItem.Id           = sheduledToast.Id;
            notItem.Title        = title;
            notItem.Content      = content;
            notItem.DeliveryTime = dateTime;

            MainPage.NotificationList.Add(notItem);

            Frame.GoBack();

            //ShowMessage("Dodano powiadowmienie.");
        }
Exemple #16
0
        private void createToast()
        {
            var toastXml = Windows.UI.Notifications.ToastNotificationManager.GetTemplateContent(Windows.UI.Notifications.ToastTemplateType.ToastText02);
            var strings  = toastXml.GetElementsByTagName("text");

            strings[0].AppendChild(toastXml.CreateTextNode(param.stype));
            strings[1].AppendChild(toastXml.CreateTextNode("Время: " + param.dateTime.ToString()));

            try
            {
                var           toast = new Windows.UI.Notifications.ScheduledToastNotification(toastXml, param.dateTime);
                ToastNotifier not   = ToastNotificationManager.CreateToastNotifier();
                not.AddToSchedule(toast);
            }
            catch (Exception ex)
            {
            }
        }
Exemple #17
0
    // 지정된 시간에 커스터마이즈된 템플릿을 기반으로 ScheduledToastNotification을 만드는 메소드
    // AddToSchedule을 사용하여 일부 텍스트를 입력으로 허용한다.
    public void Add(TimeSpan occurs)
    {
        DateTime when = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                     occurs.Hours, occurs.Minutes, occurs.Seconds);

        if (when > DateTime.Now)
        {
            StringBuilder template = new StringBuilder();
            template.Append("<toast><visual version='2'><binding template='ToastText02'><text id='2'>Enter Message:</text></binding></visual>");
            template.Append("<actions><input id='message' type='text'/><action activationType='foreground' content='Ok' arguments='ok'/></actions></toast>");
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(template.ToString());
            ScheduledToastNotification toast = new ScheduledToastNotification(xml, when)
            {
                Id = _random.Next(1, 100000000).ToString()
            };
            _notifier.AddToSchedule(toast);
        }
    }
        /// <summary>
        /// Show a local notification at a specified time
        /// </summary>
        /// <param name="title">Title of the notification</param>
        /// <param name="body">Body or description of the notification</param>
        /// <param name="id">Id of the notification</param>
        /// <param name="notifyTime">Time to show notification</param>
        public void Show(string title, string body, int id, DateTime notifyTime)
        {
            var xmlData = string.Format(ToastTemplate, title, body);

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlData);

            var correctedTime = notifyTime <= DateTime.Now
              ? DateTime.Now.AddMilliseconds(100)
              : notifyTime;

            var scheduledTileNotification = new ScheduledToastNotification(xmlDoc, correctedTime)
            {
                Id = id.ToString()
            };

            _manager.AddToSchedule(scheduledTileNotification);
        }
        /*  public void sendToast(int timeAddedSec, string toastdescription, string toastTitle)
         * {
         *    Debug.WriteLine("toast");
         *    try
         *    {
         *        DateTime dueTime = DateTime.Now.AddSeconds(timeAddedSec);
         *        // Set up the notification text.
         *        var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
         *        var strings = toastXml.GetElementsByTagName("text");
         *        strings[0].AppendChild(toastXml.CreateTextNode(toastTitle));
         *        strings[1].AppendChild(toastXml.CreateTextNode(toastdescription));
         *
         *        // Create the toast notification object.
         *        var toast = new ScheduledToastNotification(toastXml, DateTime.Now);
         *        var idNumber = 5;  // Generates a unique ID number for the notification.
         *        toast.Id = "Toast" + idNumber;
         *
         *        // Add to the schedule.
         *        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
         *    }
         *    catch (Exception e)
         *    { Debug.WriteLine("toast exception = "+e.ToString()); }
         *
         *
         *
         *
         *
         * }*/
        void SendToast(string heading, string createdAt)
        {
            ToastNotifier toastNotifier   = ToastNotificationManager.CreateToastNotifier();
            XmlDocument   xmlToastContent = ToastNotificationManager.GetTemplateContent(
                ToastTemplateType.ToastImageAndText01);

            TemplateUtility.CompleteTemplate(
                xmlToastContent,
                new string[] { heading },
                new string[] { createdAt },
                "ms-winsoundevent:Notification.Mail");
            // TODO: change delivery time
            ScheduledToastNotification toastNotification = new ScheduledToastNotification(xmlToastContent,
                                                                                          (new DateTimeOffset(DateTime.Now) + TimeSpan.FromSeconds(10)));

            // TODO: change identifier
            toastNotification.Id = "AirTnT";
            toastNotifier.AddToSchedule(toastNotification);
        }
    public void Add(ref ListBox display, string value, TimeSpan occurs)
    {
        DateTime when = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                     occurs.Hours, occurs.Minutes, occurs.Seconds);

        if (when > DateTime.Now)
        {
            XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            xml.GetElementsByTagName("text")[0].InnerText = when.ToLocalTime().ToString();
            xml.GetElementsByTagName("text")[1].InnerText = value;
            ScheduledToastNotification toast = new ScheduledToastNotification(xml, when)
            {
                Id = _random.Next(1, 100000000).ToString()
            };
            _notifier.AddToSchedule(toast);
            display.Items.Add(new Item {
                Id = toast.Id, Content = value, Time = when.ToString()
            });
        }
    }
        public Task ScheduleNotification(
            Notification notification,
            DateTimeOffset deliveryTime,
            DateTimeOffset?expirationTime = null)
        {
            if (deliveryTime < DateTimeOffset.Now || deliveryTime > expirationTime)
            {
                throw new ArgumentException(nameof(deliveryTime));
            }

            var xmlContent        = GenerateXml(notification);
            var toastNotification = new ScheduledToastNotification(xmlContent, deliveryTime)
            {
                ExpirationTime = expirationTime
            };

            _toastNotifier.AddToSchedule(toastNotification);

            return(Task.CompletedTask);
        }
Exemple #22
0
        private void AddSheduleNotification()
        {
            string title   = Title.Text;
            string content = Content.Text;

            int seconds = PrepareTimeSpan();

            ToastTemplateType toastType = ToastTemplateType.ToastText02;
            XmlDocument       toastXml  = ToastNotificationManager.GetTemplateContent(toastType);

            XmlNodeList toastTextElement = toastXml.GetElementsByTagName("text");

            toastTextElement[0].AppendChild(toastXml.CreateTextNode(title));
            toastTextElement[1].AppendChild(toastXml.CreateTextNode(content));

            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", "long");

            ScheduledToastNotification sheduledToast = new ScheduledToastNotification(toastXml, DateTimeOffset.Now.AddSeconds(seconds));

            sheduledToast.Id = IdService.GetNewId();

            ToastNotifier notifier =
                ToastNotificationManager.CreateToastNotifier();

            notifier.AddToSchedule(sheduledToast);

            NotificationItem notItem = new NotificationItem();

            notItem.Title        = title;
            notItem.Content      = content;
            notItem.SecondsToEnd = seconds;
            notItem.Id           = sheduledToast.Id;

            MainPage.NotificationList.Add(notItem);

            Frame.GoBack();

            //ShowMessage("Dodano powiadowmienie.");
        }
Exemple #23
0
        private static bool UpdateNotification(ToastNotifier notifier, string notificationId, Countdown countdown)
        {
            var now = DateTime.Now;

            var schedule = CountdownCalculator.GetSchedule(countdown, now);
            var date     = schedule.NextCycle;

            var content      = CreateNotificationContent(countdown.Name, countdown.GetImageFileUri(), countdown.Guid);
            var notification = new ScheduledToastNotification(content, new DateTimeOffset(date))
            {
                Id = notificationId
            };

            if (notification.DeliveryTime > DateTime.Now)
            {
                notifier.AddToSchedule(notification);

                return(true);
            }

            return(false);
        }
        void SendToast(FlickrPhotoResult flickrPhotoResult)
        {
            ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();

            XmlDocument xmlToastContent = ToastNotificationManager.GetTemplateContent(
                ToastTemplateType.ToastImageAndText01);

            TemplateUtility.CompleteTemplate(
                xmlToastContent,
                new string[] { flickrPhotoResult.Title },
                new string[] { flickrPhotoResult.ImageUrl },
                "ms-winsoundevent:Notification.Mail");

            // TODO: change delivery time
            ScheduledToastNotification toastNotification = new ScheduledToastNotification(xmlToastContent,
                                                                                          (new DateTimeOffset(DateTime.Now) + TimeSpan.FromSeconds(10)));

            // TODO: change identifier
            toastNotification.Id = "Fred";

            toastNotifier.AddToSchedule(toastNotification);
        }
Exemple #25
0
        public static void ScheduleToast(string updateString, int eventID, DateTime dueTime, bool RepeatToast = false)
        {
            if (dueTime < DateTime.Now)
            {
                return;
            }
            //Random rand = new Random();
            //int idNumber = rand.Next(0, 10000000);
            // Scheduled toasts use the same toast templates as all other kinds of toasts.
            //ToastContent toastContent = To
            IToastText02 toastContent = ToastContentFactory.CreateToastText02();

            toastContent.TextHeading.Text = updateString;
            //toastContent.TextBodyWrap.Text = "Received: " + dueTime.ToLocalTime();

            ScheduledToastNotification toast;

            //Этот код нужен если отложить напоминайку
            if (RepeatToast == true)
            {
                toast = new ScheduledToastNotification(toastContent.GetXml(), dueTime, TimeSpan.FromSeconds(60), 5);

                // You can specify an ID so that you can manage toasts later.
                // Make sure the ID is 15 characters or less.
                //toast.Id = "Repeat" + eventID;
            }
            else
            {
                toast = new ScheduledToastNotification(toastContent.GetXml(), dueTime);
            }
            toast.Id = eventID.ToString();
            //Everyday.listNotrfications.Add(toast.Id);
            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.AddToSchedule(toast);
            //NotifyUser("Event scheduled on " + dueTime + ", a toast with ID: " + toast.Id, NotifyType.StatusMessage);
        }
Exemple #26
0
        public void Schedule(Note note)
        {
            if (note.Reminder == null)
            {
                return;
            }

            foreach (var occurrence in note.Reminder.GetOccurrences())
            {
                var group = GetGroup(note.Id);
                if (occurrence < DateTime.Now.AddSeconds(5))
                {
                    Logger.Current.Warn($"Cannot schedule '{group}' on {occurrence} - it's in the past");
                    continue;
                }

                var content = contentBuilder.Build(note);
                var toast   = new ScheduledToastNotification(content, occurrence);
                toast.Group = group;

                Logger.Current.Info($"Add to schedule '{toast.Group}.{toast.Tag}' on {toast.DeliveryTime}");
                notifier.AddToSchedule(toast);
            }
        }
        private async void Add_Click(object sender, RoutedEventArgs e)
        {
            string str;

            description.Document.GetText(Windows.UI.Text.TextGetOptions.None, out str);
            DateTime dt = Convert.ToDateTime(String.Format("{0:dd/MM/yyyy} {1:t}", date.Date.Date, time.Time));
            WorkDB   db = new WorkDB();

            if (stype.SelectedIndex == 0)
            {
                Vaccine vac = new Vaccine();
                vac.cabinet = cabinet_v.Text;
                vac.phone   = telephone_v.Text;
                vac.vaccine = vaccin.Text;
                vac.fio     = fio_v.Text;

                db.InsertReminderVaccine(vac, dt, str);
            }
            if (stype.SelectedIndex == 1)
            {
                Doctor doct = new Doctor();
                doct.cabinet = cabinet_d.Text;
                doct.doctor  = doc.Text;
                doct.fio     = fio_d.Text;
                doct.phone   = telephone_d.Text;

                db.InsertReminderDoctor(doct, dt, str);
            }
            if (stype.SelectedIndex == 2)
            {
                DataModel.Action act = new DataModel.Action();
                act.place = place.Text;


                act.Latitude  = geo.Latitude;
                act.Longitude = geo.Longitude;

                db.InsertReminderAction(act, dt, str);
            }

            // Set up the notification text.
            var toastXml = Windows.UI.Notifications.ToastNotificationManager.GetTemplateContent(Windows.UI.Notifications.ToastTemplateType.ToastText02);
            var strings  = toastXml.GetElementsByTagName("text");

            strings[0].AppendChild(toastXml.CreateTextNode((stype.SelectedIndex == 0 ? "Прививка" : stype.SelectedIndex == 1 ? "Прием врача" : "Мероприятие")));
            strings[1].AppendChild(toastXml.CreateTextNode("Время: " + dt.ToString()));

            // Create the toast notification object.
            try
            {
                var           toast = new Windows.UI.Notifications.ScheduledToastNotification(toastXml, dt);
                ToastNotifier not   = ToastNotificationManager.CreateToastNotifier();
                var           v     = not.GetScheduledToastNotifications();
                not.AddToSchedule(toast);
            }
            catch (Exception ex)
            {
            }
            var dlg = new MessageDialog("Данные успешно сохранены !");

            dlg.ShowAsync();
            this.Frame.Navigate(typeof(MainPage));
        }
Exemple #28
0
        private async void SetLogFile(object sender, RoutedEventArgs e)
        {
            progress.Visibility   = Visibility.Visible;
            App.DisableSelection  = true;
            App.SgstBox.IsEnabled = false;

            FileOpenPicker open = new FileOpenPicker();

            open.FileTypeFilter.Add(".elog");
            StorageFile file = await open.PickSingleFileAsync();

            if (file != null)
            {
                string text;
                if (add.IsChecked.Value)
                {
                    text = App.Eng ? "Irrevocable operation. New records will be added to the current log." :
                           "Необратимая операция. Новые записи будут добавлены в текущий журнал.";
                }
                else
                {
                    text = App.Eng ? "Irrevocable operation. Current log will be erased." :
                           "Необратимая операция. Текущий журнал будет удален.";
                }
                MessageDialog dialog = new MessageDialog(text);
                string        proceed, cancel;
                if (App.Eng)
                {
                    proceed = "Proceed";
                    cancel  = "Cancel";
                }
                else
                {
                    proceed = "Продолжить";
                    cancel  = "Отмена";
                }
                bool consent = false;
                dialog.Commands.Add(new UICommand(proceed, x => consent = true));
                dialog.Commands.Add(new UICommand(cancel));
                await dialog.ShowAsync();

                if (!consent)
                {
                    App.DisableSelection  = false;
                    App.SgstBox.IsEnabled = true;
                    progress.Visibility   = Visibility.Collapsed;
                    return;
                }

                file = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, "events.elog", NameCollisionOption.ReplaceExisting);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)code.Length);

                        byte[] coded = new byte[code.Length];
                        for (int i = 0; i < coded.Length; i++)
                        {
                            coded[i] = (byte)(reader.ReadByte() ^ code[i]);
                        }
                        using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
                            writer.WriteBytes(coded);
                    }
                }
                StorageFolder folder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync("temp", CreationCollisionOption.ReplaceExisting);

                try
                {
                    await Task.Run(() => ZipFile.ExtractToDirectory(file.Path, folder.Path));
                }
                catch
                {
                    await(new MessageDialog("Wrong file format!")).ShowAsync();
                    await file.DeleteAsync();

                    await folder.DeleteAsync();

                    App.DisableSelection  = false;
                    App.SgstBox.IsEnabled = true;
                    progress.Visibility   = Visibility.Collapsed;
                    return;
                }

                await file.DeleteAsync();

                if (add.IsChecked.Value)
                {
                    XmlDocument doc = await XmlDocument.LoadFromFileAsync(await folder.GetFileAsync("data.xml"));

                    IXmlNode      root  = doc.FirstChild;
                    StorageFolder Icons = await folder.TryGetItemAsync("Icons") as StorageFolder;

                    StorageFolder Videos = await folder.TryGetItemAsync("Videos") as StorageFolder;

                    StorageFolder Audios = await folder.TryGetItemAsync("Audios") as StorageFolder;

                    StorageFolder Inks = await folder.TryGetItemAsync("Inks") as StorageFolder;

                    StorageFolder locIcons = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Icons", CreationCollisionOption.OpenIfExists);

                    StorageFolder locVideos = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Videos", CreationCollisionOption.OpenIfExists);

                    StorageFolder locAudios = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Audios", CreationCollisionOption.OpenIfExists);

                    StorageFolder locInks = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Inks", CreationCollisionOption.OpenIfExists);

                    foreach (IXmlNode evntNode in root.ChildNodes)
                    {
                        Event evnt = new Event(evntNode);
                        if (evnt.IsPast && !evnt.Keep)
                        {
                            continue;
                        }
                        if (App.Storage.Exist(evnt.Guid))
                        {
                            continue;
                        }

                        if (evnt.IconPath.AbsoluteUri != "ms-appx:///Assets/item.png")
                        {
                            StorageFile iconFile = await Icons.GetFileAsync(Path.GetFileName(evnt.IconPath.AbsolutePath));

                            await iconFile.CopyAsync(locIcons);
                        }
                        switch (evnt.MediaMessageType)
                        {
                        case MediaMessageType.Video:
                            StorageFile videoFile = await Videos.GetFileAsync(Path.GetFileName(evnt.MediaMessageUri.AbsolutePath));

                            await videoFile.CopyAsync(locVideos);

                            break;

                        case MediaMessageType.Voice:
                            StorageFile audioFile = await Audios.GetFileAsync(Path.GetFileName(evnt.MediaMessageUri.AbsolutePath));

                            await audioFile.CopyAsync(locAudios);

                            break;
                        }
                        if (evnt.HasStroke)
                        {
                            await(await Inks.GetFileAsync(evnt.Guid.ToString() + ".gif")).CopyAsync(locInks);
                        }

                        if (!evnt.IsPast && evnt.Alarm != null)
                        {
                            var xml = App.FormNotification(evnt.Name, evnt.Message, evnt.IconPath.AbsoluteUri, evnt.Guid.ToString());

                            ScheduledToastNotification notification = new ScheduledToastNotification(xml, evnt.Alarm.Value);
                            _notifier.AddToSchedule(notification);
                        }
                        await evnt.SaveToFileAsync();

                        App.Storage.AddEvent(evnt);
                    }
                }
                else
                {
                    foreach (var item in await ApplicationData.Current.LocalFolder.GetItemsAsync())
                    {
                        await item.DeleteAsync();
                    }
                    var notifs = _notifier.GetScheduledToastNotifications();
                    foreach (var notif in notifs)
                    {
                        _notifier.RemoveFromSchedule(notif);
                    }

                    foreach (var item in await folder.GetItemsAsync())
                    {
                        if (item.IsOfType(StorageItemTypes.File))
                        {
                            await((StorageFile)item).MoveAsync(ApplicationData.Current.LocalFolder);
                        }
                        else if (item.IsOfType(StorageItemTypes.Folder))
                        {
                            StorageFolder fld    = (StorageFolder)item;
                            StorageFolder locfld = await ApplicationData.Current.LocalFolder.CreateFolderAsync(fld.DisplayName);

                            foreach (var itm in await fld.GetFilesAsync())
                            {
                                await itm.MoveAsync(locfld);
                            }
                        }
                    }
                    App.Storage = await EventStorage.DeserializeAsync();

                    foreach (var year in App.Storage.CallendarActive)
                    {
                        foreach (var mnth in year.Months)
                        {
                            foreach (var evnt in mnth.Events)
                            {
                                if (evnt.Alarm != null)
                                {
                                    var xml = App.FormNotification(evnt.Name, evnt.Message, evnt.IconPath.AbsoluteUri, evnt.Guid.ToString());

                                    ScheduledToastNotification notification = new ScheduledToastNotification(xml, evnt.Alarm.Value);
                                    _notifier.AddToSchedule(notification);
                                }
                            }
                        }
                    }
                }
                await folder.DeleteAsync();
            }
            App.DisableSelection  = false;
            App.SgstBox.IsEnabled = true;
            progress.Visibility   = Visibility.Collapsed;
        }
        public Task <INotificationResult> Notify(INotificationOptions options)
        {
            return(Task.Run(() =>
            {
                ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier();
                Windows.Data.Xml.Dom.XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                Windows.Data.Xml.Dom.XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");
                toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(options.Title));
                toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(options.Description));
                Windows.Data.Xml.Dom.IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

                var id = _count.ToString();

                var root = toastXml.DocumentElement;
                root.SetAttribute("launch", id.ToString());

                if (!string.IsNullOrEmpty(options.WindowsOptions.LogoUri))
                {
                    Windows.Data.Xml.Dom.XmlElement image = toastXml.CreateElement("image");
                    image.SetAttribute("placement", "appLogoOverride");

                    var imageUri = options.WindowsOptions.LogoUri;
                    if (!options.WindowsOptions.LogoUri.Contains("//"))
                    {
                        imageUri = $"ms-appx:///{options.WindowsOptions.LogoUri}";
                    }

                    image.SetAttribute("src", imageUri);

                    toastXml.GetElementsByTagName("binding")[0].AppendChild(image);
                    toastXml.GetElementsByTagName("binding")[0].Attributes[0].InnerText = "ToastGeneric";
                }

                if (options.DelayUntil.HasValue)
                {
                    ScheduledToastNotification toast = new ScheduledToastNotification(toastXml, options.DelayUntil.Value);
                    ToastNotifier.AddToSchedule(toast);
                    return new NotificationResult()
                    {
                        Action = NotificationAction.NotApplicable
                    };
                }
                else
                {
                    Windows.UI.Notifications.ToastNotification toast = new Windows.UI.Notifications.ToastNotification(toastXml);


                    toast.Tag = id;
                    _count++;
                    toast.Dismissed += Toast_Dismissed;
                    toast.Activated += Toast_Activated;
                    toast.Failed += Toast_Failed;
                    _notificationOptions.Add(id, options);

                    var waitEvent = new ManualResetEvent(false);

                    _resetEvents.Add(id, waitEvent);

                    ToastNotifier.Show(toast);

                    waitEvent.WaitOne();

                    INotificationResult result = _eventResult[id];

                    if (!options.IsClickable && result.Action == NotificationAction.Clicked) // A click is transformed to manual dismiss
                    {
                        result = new NotificationResult()
                        {
                            Action = NotificationAction.Dismissed
                        }
                    }
                    ;

                    if (_resetEvents.ContainsKey(id))
                    {
                        _resetEvents.Remove(id);
                    }
                    if (_eventResult.ContainsKey(id))
                    {
                        _eventResult.Remove(id);
                    }
                    if (_notificationOptions.ContainsKey(id))
                    {
                        _notificationOptions.Remove(id);
                    }

                    return result;
                }
            }));
        }
Exemple #30
0
        private void ButtonPopUpAlarmNotification_Click(object sender, RoutedEventArgs e)
        {
            /*
             * string textLine1 = "Sample Toast App";
             * string textLine2 = "This is a sample message.";
             * string contentString =
             * "<toast duration=\"long\">\n" +
             *  "<visual>\n" +
             *    "<binding template=\"ToastText02\">\n" +
             *      "<text id=\"1\">" + textLine1 + "</text>\n" +
             *      "<text id=\"2\">" + textLine2 + "</text>\n" +
             *    "</binding>\n" +
             *  "</visual>\n" +
             * "</toast>\n";
             *   XmlDocument content = new Windows.Data.Xml.Dom.XmlDocument();
             * content.LoadXml(contentString);
             */

            var toastContent = new ToastContent()
            {
                Visual = new ToastVisual()
                {
                    BaseUri        = new Uri("ms-appx:///Assets/Weather/"),
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = "Today will be sunny with a high of 63 and a low of 42."
                            },
                            new AdaptiveGroup()
                            {
                                Children =
                                {
                                    new AdaptiveSubgroup()
                                    {
                                        HintWeight = 1,
                                        Children   =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text      = "Mon",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveImage()
                                            {
                                                HintRemoveMargin = true,
                                                Source           = "Mostly Cloudy.png"
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "63°",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "42°",
                                                HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                                HintAlign = AdaptiveTextAlign.Center
                                            }
                                        }
                                    },
                                    new AdaptiveSubgroup()
                                    {
                                        HintWeight = 1,
                                        Children   =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text      = "Tue",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveImage()
                                            {
                                                HintRemoveMargin = true,
                                                Source           = "Cloudy.png"
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "57°",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "38°",
                                                HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                                HintAlign = AdaptiveTextAlign.Center
                                            }
                                        }
                                    },
                                    new AdaptiveSubgroup()
                                    {
                                        HintWeight = 1,
                                        Children   =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text      = "Wed",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveImage()
                                            {
                                                HintRemoveMargin = true,
                                                Source           = "Sunny.png"
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "59°",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "43°",
                                                HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                                HintAlign = AdaptiveTextAlign.Center
                                            }
                                        }
                                    },
                                    new AdaptiveSubgroup()
                                    {
                                        HintWeight = 1,
                                        Children   =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text      = "Thu",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveImage()
                                            {
                                                HintRemoveMargin = true,
                                                Source           = "Sunny.png"
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "62°",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "42°",
                                                HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                                HintAlign = AdaptiveTextAlign.Center
                                            }
                                        }
                                    },
                                    new AdaptiveSubgroup()
                                    {
                                        HintWeight = 1,
                                        Children   =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text      = "Fri",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveImage()
                                            {
                                                HintRemoveMargin = true,
                                                Source           = "Sunny.png"
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "71°",
                                                HintAlign = AdaptiveTextAlign.Center
                                            },
                                            new AdaptiveText()
                                            {
                                                Text      = "66°",
                                                HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                                HintAlign = AdaptiveTextAlign.Center
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            // Create the toast notification
            var content = toastContent.GetXml();

            // And send the notification
            //ToastNotificationManager.CreateToastNotifier().Show(toastNotif);

            ToastNotifier toastNotifier =
                ToastNotificationManager.CreateToastNotifier();
            var scheduledToast = new ScheduledToastNotification(
                content, DateTime.Now.AddSeconds(5));

            scheduledToast.Tag = "TestTag";
            toastNotifier.AddToSchedule(scheduledToast);
            toastNotifier.ScheduledToastNotificationShowing += ToastNotifier_ScheduledToastNotificationShowing;
        }