예제 #1
0
파일: Irc.cs 프로젝트: owensdj/WinIRC
        internal async Task HandleLine(string receivedData)
        {
            if (receivedData.Contains("Nickname is already in use"))
            {
                this.server.username += "_";
                AttemptAuth();
                return;
            }

            if (receivedData.StartsWith("ERROR"))
            {
                if (!IsReconnecting)
                {
                    ReadOrWriteFailed = true;

                    var autoReconnect = Config.GetBoolean(Config.AutoReconnect);

                    var msg = autoReconnect
                        ? "Attempting to reconnect..."
                        : "Please try again later.";

                    AddError("Error with connection: \n" + msg);

                    DisconnectAsync(attemptReconnect: autoReconnect);
                }
                return;
            }

            if (receivedData.StartsWith("PING"))
            {
                await WriteLine(writer, receivedData.Replace("PING", "PONG"));

                return;
            }

            var parsedLine = new IrcMessage(receivedData);

            ReconnectionAttempts = 0;

            if (parsedLine.CommandMessage.Command == "CAP")
            {
                if (parsedLine.CommandMessage.Parameters[1] == "LS")
                {
                    var requirements      = "";
                    var compatibleFeatues = parsedLine.TrailMessage.TrailingContent;

                    if (compatibleFeatues.Contains("znc"))
                    {
                        IsBouncer = true;
                    }

                    if (compatibleFeatues.Contains("znc.in/server-time-iso"))
                    {
                        requirements += "znc.in/server-time-iso ";
                    }

                    if (compatibleFeatues.Contains("multi-prefix"))
                    {
                        requirements += "multi-prefix ";
                    }


                    WriteLine("CAP REQ :" + requirements);
                    WriteLine("CAP END");
                }
            }
            else if (parsedLine.CommandMessage.Command == "JOIN")
            {
                var channel = parsedLine.TrailMessage.TrailingContent;
                if (parsedLine.PrefixMessage.Nickname == this.server.username)
                {
                    await AddChannel(channel);
                }

                if (parsedLine.CommandMessage.Parameters != null)
                {
                    channel = parsedLine.CommandMessage.Parameters[0];
                }

                if ((!Config.Contains(Config.IgnoreJoinLeave)) || (!Config.GetBoolean(Config.IgnoreJoinLeave)))
                {
                    Message msg = new Message();
                    msg.Type = MessageType.Info;
                    msg.User = parsedLine.PrefixMessage.Nickname;

                    msg.Text = String.Format("({0}) {1}", parsedLine.PrefixMessage.Prefix, "joined the channel");
                    await AddMessage(channel, msg);
                }

                channelStore[channel].AddUser(parsedLine.PrefixMessage.Nickname, true);
            }
            else if (parsedLine.CommandMessage.Command == "PART")
            {
                var channel = parsedLine.TrailMessage.TrailingContent;
                if (parsedLine.PrefixMessage.Nickname == this.server.username)
                {
                    RemoveChannel(channel);
                }
                else
                {
                    if (parsedLine.CommandMessage.Parameters.Count > 0)
                    {
                        channel = parsedLine.CommandMessage.Parameters[0];
                    }

                    if ((!Config.Contains(Config.IgnoreJoinLeave)) || (!Config.GetBoolean(Config.IgnoreJoinLeave)))
                    {
                        Message msg = new Message();
                        msg.Type = MessageType.Info;
                        msg.User = parsedLine.PrefixMessage.Nickname;

                        msg.Text = String.Format("({0}) {1}", parsedLine.PrefixMessage.Prefix, "left the channel");
                        await AddMessage(channel, msg);
                    }

                    channelStore[channel].RemoveUser(parsedLine.PrefixMessage.Nickname);
                }
            }
            else if (parsedLine.CommandMessage.Command == "PRIVMSG")
            {
                // handle messages to this irc client
                var destination = parsedLine.CommandMessage.Parameters[0];
                var content     = parsedLine.TrailMessage.TrailingContent;

                if (destination == server.username)
                {
                    destination = parsedLine.PrefixMessage.Nickname;
                }

                if (!channelList.Contains(destination))
                {
                    await AddChannel(destination);
                }

                Message msg = new Message();

                msg.Type = MessageType.Normal;
                msg.User = parsedLine.PrefixMessage.Nickname;
                if (parsedLine.ServerTime != null)
                {
                    var time = DateTime.Parse(parsedLine.ServerTime);
                    msg.Timestamp = time.ToString("HH:mm");
                }

                if (content.Contains("ACTION"))
                {
                    msg.Text = content.Replace("ACTION ", "");
                    msg.Type = MessageType.Action;
                }
                else
                {
                    msg.Text = content;
                }

                var key  = Config.PerChannelSetting(this.server.name, destination, Config.AlwaysNotify);
                var ping = Config.GetBoolean(key, false);

                if (parsedLine.TrailMessage.TrailingContent.Contains(server.username) || parsedLine.CommandMessage.Parameters[0] == server.username || ping)
                {
                    if (currentChannel != destination || (App.Current as App).IncrementPings == true || MainPage.instance.currentServer == this.server.name || ping)
                    {
                        var toast = CreateMentionToast(parsedLine.PrefixMessage.Nickname, destination, content);
                        toast.ExpirationTime = DateTime.Now.AddDays(2);
                        ToastNotificationManager.CreateToastNotifier().Show(toast);
                        (App.Current as App).NumberPings++;
                    }

                    msg.Mention = parsedLine.TrailMessage.TrailingContent.Contains(server.username) || parsedLine.CommandMessage.Parameters[0] == server.username;
                }

                await AddMessage(destination, msg);
            }
            else if (parsedLine.CommandMessage.Command == "KICK")
            {
                // handle messages to this irc client
                var destination = parsedLine.CommandMessage.Parameters[0];
                var reciever    = parsedLine.CommandMessage.Parameters[1];
                var content     = parsedLine.TrailMessage.TrailingContent;
                if (!channelList.Contains(destination))
                {
                    AddChannel(destination);
                }

                Message msg = new Message();

                msg.Type = MessageType.Info;

                if (reciever == server.username)
                {
                    var kickTitle = String.Format("{0} kicked you from {1}", parsedLine.PrefixMessage.Nickname, destination);

                    var toast = CreateBasicToast(kickTitle, content);
                    toast.ExpirationTime = DateTime.Now.AddDays(2);
                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                    msg.User = parsedLine.PrefixMessage.Nickname;
                    msg.Text = "kicked you from the channel: " + content;
                }
                else
                {
                    msg.User = parsedLine.PrefixMessage.Nickname;
                    msg.Text = String.Format("kicked {0} from the channel: {1}", reciever, content);
                }

                await AddMessage(destination, msg);
            }
            else if (parsedLine.CommandMessage.Command == "353")
            {
                // handle /NAMES
                var list    = parsedLine.TrailMessage.TrailingContent.Split(' ').ToList();
                var channel = parsedLine.CommandMessage.Parameters[2];

                if (!channelList.Contains(channel))
                {
                    await AddChannel(channel);
                }

                channelStore[channel].AddUsers(list);

                if (!IsBouncer)
                {
                    channelStore[channel].SortUsers();
                }
            }
            else if (parsedLine.CommandMessage.Command == "332")
            {
                // handle initial topic recieve
                var topic   = parsedLine.TrailMessage.TrailingContent;
                var channel = parsedLine.CommandMessage.Parameters[1];

                if (!channelList.Contains(channel))
                {
                    await AddChannel(channel);
                }

                Message msg = new Message();
                msg.Type = MessageType.Info;

                msg.User = "";
                msg.Text = String.Format("Topic for channel {0}: {1}", channel, topic);
                await AddMessage(channel, msg);

                channelStore[channel].SetTopic(topic);
            }
            else if (parsedLine.CommandMessage.Command == "TOPIC")
            {
                // handle topic recieved
                var topic   = parsedLine.TrailMessage.TrailingContent;
                var channel = parsedLine.CommandMessage.Parameters[0];

                if (!channelList.Contains(channel))
                {
                    await AddChannel(channel);
                }

                Message msg = new Message();
                msg.Type = MessageType.Info;

                msg.User = "";
                msg.Text = String.Format("Topic for channel {0}: {1}", channel, topic);
                await AddMessage(channel, msg);

                channelStore[channel].SetTopic(topic);
            }
            else if (parsedLine.CommandMessage.Command == "QUIT")
            {
                var username = parsedLine.PrefixMessage.Nickname;
                foreach (var channel in channelList)
                {
                    var users = channelStore[channel.Name];
                    if (users.HasUser(username))
                    {
                        if ((!Config.Contains(Config.IgnoreJoinLeave)) || (!Config.GetBoolean(Config.IgnoreJoinLeave)))
                        {
                            Message msg = new Message();
                            msg.Type = MessageType.Info;
                            msg.User = parsedLine.PrefixMessage.Nickname;
                            msg.Text = String.Format("({0}) {1}: {2}", parsedLine.PrefixMessage.Prefix, "quit the server", parsedLine.TrailMessage.TrailingContent);
                            await AddMessage(channel.Name, msg);
                        }

                        users.RemoveUser(username);
                    }
                }
            }
            else if (parsedLine.CommandMessage.Command == "MODE")
            {
                Debug.WriteLine(parsedLine.CommandMessage.Command + " - " + receivedData);

                if (parsedLine.CommandMessage.Parameters.Count > 2)
                {
                    var channel = parsedLine.CommandMessage.Parameters[0];

                    if (parsedLine.CommandMessage.Parameters.Count == 3)
                    {
                        string currentPrefix = channelStore[channel].GetPrefix(parsedLine.CommandMessage.Parameters[2]);
                        string prefix        = "";
                        string mode          = parsedLine.CommandMessage.Parameters[1];
                        if (mode == "+o")
                        {
                            if (currentPrefix.Length > 0 && currentPrefix[0] == '+')
                            {
                                prefix = "@+";
                            }
                            else
                            {
                                prefix = "@";
                            }
                        }
                        else if (mode == "-o")
                        {
                            if (currentPrefix.Length > 0 && currentPrefix[1] == '+')
                            {
                                prefix = "+";
                            }
                        }
                        else if (mode == "+v")
                        {
                            if (currentPrefix.Length > 0 && currentPrefix[0] == '@')
                            {
                                prefix = "@+";
                            }
                            else
                            {
                                prefix = "+";
                            }
                        }
                        else if (mode == "-v")
                        {
                            if (currentPrefix.Length > 0 && currentPrefix[0] == '@')
                            {
                                prefix = "@";
                            }
                            else
                            {
                                prefix = "";
                            }
                        }

                        channelStore[channel].ChangePrefix(parsedLine.CommandMessage.Parameters[2], prefix);
                    }

                    ClientMessage(channel, "Mode change: " + String.Join(" ", parsedLine.CommandMessage.Parameters));
                }
            }
            else if (parsedLine.CommandMessage.Command == "470")
            {
                RemoveChannel(parsedLine.CommandMessage.Parameters[1]);
                AddChannel(parsedLine.CommandMessage.Parameters[2]);
            }
            else if (WhoisCmds.Any(str => str.Contains(parsedLine.CommandMessage.Command)))
            {
                var cmd = parsedLine.CommandMessage.Command;
                if (currentWhois == "")
                {
                    currentWhois += "Whois for " + parsedLine.CommandMessage.Parameters[1] + ": \r\n";
                }

                var whoisLine = "";

                if (cmd == "330")
                {
                    whoisLine    += parsedLine.CommandMessage.Parameters[1] + " " + parsedLine.TrailMessage.TrailingContent + " " + parsedLine.CommandMessage.Parameters[2] + " ";
                    currentWhois += whoisLine + "\r\n";
                }
                else
                {
                    for (int i = 2; i < parsedLine.CommandMessage.Parameters.Count; i++)
                    {
                        whoisLine += parsedLine.CommandMessage.Command + " " + parsedLine.CommandMessage.Parameters[i] + " ";
                    }
                    currentWhois += whoisLine + parsedLine.TrailMessage.TrailingContent + "\r\n";
                }
            }
            else if (parsedLine.CommandMessage.Command == "318")
            {
                Debug.WriteLine(currentWhois);
                Message msg = new Message();
                msg.Text = currentWhois;
                msg.Type = MessageType.Info;
                await AddMessage(currentChannel, msg);

                currentWhois = "";
            }
            else if (parsedLine.CommandMessage.Command == "376")
            {
                if (server.nickservPassword != null && server.nickservPassword != "")
                {
                    SendMessage("nickserv", "identify " + server.nickservPassword);
                }

                if (server.channels != null && server.channels != "")
                {
                    var channelsList = server.channels.Split(',');
                    foreach (string channel in channelsList)
                    {
                        JoinChannel(channel);
                    }
                }
            }
            else
            {
                if (!parsedLine.PrefixMessage.IsUser)
                {
                    if (!channelList.Contains("Server"))
                    {
                        AddChannel("Server");
                    }

                    Message msg = new Message();
                    msg.Text = parsedLine.OriginalMessage;
                    msg.Type = MessageType.Info;
                    msg.User = "";
                    await AddMessage("Server", msg);
                }
                Debug.WriteLine(parsedLine.CommandMessage.Command + " - " + receivedData);
            }

            //Debug.WriteLine(parsedLine.CommandMessage.Command + " - " + receivedData);
        }
예제 #2
0
        public static void BigImageToast(string id, string imageUri, string avatarUri)
        {
            ToastContent toastContent = new ToastContent()
            {
                Launch = "Toast",

                Actions = new ToastActionsCustom()
                {
                    Buttons =
                    {
                        new ToastButton("Favorite", new QueryString()
                        {
                            { "action",             "favorite"      },
                            { "id",                 id              }
                        }.ToString())
                        {
                            ActivationType = ToastActivationType.Background
                        },

                        new ToastButton("Undo",     new QueryString()
                        {
                            { "action",             "undoWallpaper" },
                            { "id",                 id              }
                        }.ToString())
                        {
                            ActivationType = ToastActivationType.Background
                        },

                        new ToastButton("Dismiss",  "dismiss")
                        {
                            ActivationType = ToastActivationType.Protocol
                        },
                    }
                },

                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text      = "Your wallpaper is updated!",
                                HintStyle = AdaptiveTextStyle.Header
                            },

                            new AdaptiveText()
                            {
                                Text      = "Happy?",
                                HintStyle = AdaptiveTextStyle.Body
                            },

                            //new AdaptiveImage()
                            //{
                            //    Source = imageUri,
                            //    HintRemoveMargin = true,
                            //    HintCrop = AdaptiveImageCrop.None,
                            //},
                        },

                        HeroImage = new ToastGenericHeroImage()
                        {
                            Source = imageUri
                        },

                        Attribution = new ToastGenericAttributionText()
                        {
                            Text = "prpr"
                        },

                        AppLogoOverride = new ToastGenericAppLogo()
                        {
                            Source   = "Assets/Square44x44Logo.targetsize-256_altform-unplated.png",// avatarUri,
                            HintCrop = ToastGenericAppLogoCrop.None,
                        },
                    }
                }
            };
            ToastNotification toast = new ToastNotification(toastContent.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        private async void myimport_Click(object sender, RoutedEventArgs e)
        {
            var fileopen = new FileOpenPicker();

            fileopen.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            fileopen.FileTypeFilter.Add(".mp3");
            fileopen.FileTypeFilter.Add(".wav");
            fileopen.FileTypeFilter.Add(".mp4");
            fileopen.FileTypeFilter.Add(".avi");
            fileopen.FileTypeFilter.Add(".vob");

            newelements.AutoPlay = true;
            var file = await fileopen.PickSingleFileAsync();

            var stream = await file.OpenAsync(FileAccessMode.Read);

            var filename = file.Name;
            var filetype = file.FileType;

            if (filetype == ".mp4" || filetype == ".avi" || filetype == ".mp3" || filetype == ".wav" || filetype == ".vob")
            {
                newelements.SetSource(stream, file.ContentType);
                newelements.IsFullWindow = !newelements.IsFullWindow;
                newelements.TransportControls.IsStopEnabled              = true;
                newelements.TransportControls.IsStopButtonVisible        = true;
                newelements.TransportControls.IsFastForwardButtonVisible = true;
                newelements.TransportControls.IsFastForwardEnabled       = true;
                newelements.TransportControls.IsFastRewindButtonVisible  = true;
                newelements.TransportControls.IsFastRewindEnabled        = true;
            }

            newelements.SetSource(stream, file.ContentType);
            newelements.TransportControls.IsStopEnabled              = true;
            newelements.TransportControls.IsStopButtonVisible        = true;
            newelements.TransportControls.IsFastForwardButtonVisible = true;
            newelements.TransportControls.IsFastForwardEnabled       = true;
            newelements.TransportControls.IsFastRewindButtonVisible  = true;
            newelements.TransportControls.IsFastRewindEnabled        = true;

            newelements.Play();
            remaintxt.Text       = string.Format("Now Playing: {0}", filename);
            resultetxtblock.Text = filename;
            presstxt.Visibility  = Visibility.Collapsed;


            var tilexml  = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150IconWithBadgeAndText);
            var tileattr = tilexml.GetElementsByTagName("text");

            tileattr[0].AppendChild(tilexml.CreateTextNode(resultetxtblock.Text));
            tileattr[1].AppendChild(tilexml.CreateTextNode(tiletxt.Text));
            var tilenotify = new TileNotification(tilexml);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tilenotify);

            var template = ToastTemplateType.ToastText01;
            var xml      = ToastNotificationManager.GetTemplateContent(template);

            xml.DocumentElement.SetAttribute("launch", "Args");
            var text     = xml.CreateTextNode(remaintxt.Text);
            var elements = xml.GetElementsByTagName("text");

            elements[0].AppendChild(text);
            var toast    = new ToastNotification(xml);
            var notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.Show(toast);
        }
예제 #4
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var details = taskInstance.TriggerDetails as BackgroundTransferCompletionGroupTriggerDetails;

            if (details == null)
            {
                System.Diagnostics.Debug.WriteLine("下载任务非下载完成后触发", "Error");
                return;
            }

            // 寻找对应的下载计划
            RecordSchedule schedule = null;

            foreach (var item in RecordScheduleManager.Container.Values)
            {
                if ((Guid)item.Value == taskInstance.Task.TaskId)
                {
                    schedule = new RecordSchedule(item.Key);
                }
            }

            if (schedule == null)
            {
                System.Diagnostics.Debug.WriteLine("未找到对应的下载计划", "Error");
                return;
            }
            if (details.Downloads.Any(op => IsFailed(op)))
            {
                // 下载失败
                schedule.Status = ScheduleStatus.Failed;

                // 生成下载失败的消息提醒
                XmlDocument failedToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
                failedToastXml.GetElementsByTagName("text").Item(0).InnerText = "一项录播任务失败";
                ToastNotification failedToast = new ToastNotification(failedToastXml);
                ToastNotificationManager.CreateToastNotifier().Show(failedToast);
                return;
            }

            RecordScheduleMessager.Instance.Trigger(schedule.Key, RecordScheduleMessageType.DownloadedOne);
            var _defer = taskInstance.GetDeferral();

            if (schedule.Status == ScheduleStatus.Terminated)
            {
                System.Diagnostics.Debug.WriteLine("下载计划被终止");
                // 将已下载的缓存合并成文件保存下来
                schedule.Status = ScheduleStatus.Decoding;
                var continuous = await schedule.ConcatenateSegments(schedule.SavePath);

                schedule.Status = ScheduleStatus.Terminated;
                return;
            }

            // 生成下一个下载,若下载完毕则直接处理文件
            var operation = await schedule.GenerateDownloadTask();

            if (operation == null)
            {
                schedule.Status = ScheduleStatus.Decoding;
                var continuous = await schedule.ConcatenateSegments(schedule.SavePath);

                // 生成下载成功的消息提醒
                XmlDocument successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
                successToastXml.GetElementsByTagName("text").Item(0).InnerText =
                    "一项录播任务已经成功结束" + (continuous ? string.Empty : ",但可能录播不完整。");
                ToastNotification successToast = new ToastNotification(successToastXml);
                ToastNotificationManager.CreateToastNotifier().Show(successToast);
            }
            _defer.Complete();
        }
예제 #5
0
        void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
        {
            AuthenticateClass token = new AuthenticateClass();

            token.appname = null;
            var authfile = ApplicationData.Current.LocalFolder.GetFileAsync("auth.txt");

            authfile.AsTask().Wait();
            var tokenfile = authfile.GetResults();
            var ioop      = FileIO.ReadTextAsync(tokenfile);

            ioop.AsTask().Wait();
            token.token  = ioop.GetResults();
            token.server = MainPage.getServerName();
            string baseuri = "https://" + token.server;

            baseuri = baseuri + "/api/v1/streaming/user";
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
            var msg = client.GetStreamAsync(baseuri);

            msg.Wait();
            var msga = msg.Result;

            while (1 == 1)
            {
                var    st   = new StreamReader(msga);
                string text = st.ReadLine();
                if ((text.ToArray())[0] != ':')
                {
                    string[] text2  = text.Split(':');
                    string   text3  = st.ReadLine();
                    string   stdata = new string((text3.Skip(5)).ToArray());
                    if (text2[1] == " notification")
                    {
                        NotificationClass_new notification = NotificationClass_new.parseNotification(stdata);
                        if (notification.id != null)
                        {
                            if (notification.type == "favourite")
                            {
                            }
                            if (notification.type == "reblog")
                            {
                            }
                            if (notification.type == "follow")
                            {
                                if (notification.account.avatar[0] == 'h')
                                {
                                    notification.account.avatar = "https://" + token.server + notification.account.avatar;
                                }
                                ToastVisual visual = new ToastVisual()
                                {
                                    BindingGeneric = new ToastBindingGeneric()
                                    {
                                        Children =
                                        {
                                            new AdaptiveText()
                                            {
                                                Text = notification.account.display_name + " followed you."
                                            },
                                            new AdaptiveImage()
                                            {
                                                Source = notification.account.avatar
                                            }
                                        }
                                    }
                                };
                                ToastContent toastContent = new ToastContent()
                                {
                                    Visual = visual
                                };
                                var toast = new ToastNotification(toastContent.GetXml());
                                toast.ExpirationTime = DateTime.Now.AddDays(1);
                                ToastNotificationManager.CreateToastNotifier().Show(toast);
                            }
                            if (notification.type == "mention")
                            {
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
        private async void AncsManagerOnOnNotification(PlainNotification o)
        {
            XmlDocument toastXml = null;

            ToastVisual toastVisual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        {
                            Text = o.Title
                        },
                        new AdaptiveText
                        {
                            Text = o.Message
                        }
                    }
                },
            };

            // toast actions
            ToastActionsCustom toastActions = new ToastActionsCustom();

            switch (o.CategoryId)
            {
            case CategoryId.IncomingCall:
                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Phone.png" };
                toastActions.Buttons.Add(new ToastButton("Answer", new QueryString()
                {
                    { "action", "positive" },
                    { "uid", o.Uid.ToString() }
                }.ToString())
                {
                    ActivationType = ToastActivationType.Foreground
                });

                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Phone.png" };
                toastActions.Buttons.Add(new ToastButton("Dismiss", new QueryString()
                {
                    { "action", "negative" },
                    { "uid", o.Uid.ToString() }
                }.ToString())
                {
                    ActivationType = ToastActivationType.Foreground
                });

                break;

            case CategoryId.MissedCall:
                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Phone.png" };
                toastActions.Buttons.Add(new ToastButton("Dial", new QueryString()
                {
                    { "action", "positive" },
                    { "uid", o.Uid.ToString() }
                }.ToString())
                {
                    ActivationType = ToastActivationType.Foreground
                });

                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Phone.png" };
                toastActions.Buttons.Add(new ToastButton("Dismiss", new QueryString()
                {
                    { "action", "negative" },
                    { "uid", o.Uid.ToString() }
                }.ToString())
                {
                    ActivationType = ToastActivationType.Foreground
                });
                break;

            case CategoryId.Voicemail:
                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Phone.png" };
                toastActions.Buttons.Add(new ToastButton("Dial", new QueryString()
                {
                    { "action", "positive" },
                    { "uid", o.Uid.ToString() }
                }.ToString())
                {
                    ActivationType = ToastActivationType.Foreground
                });

                toastActions.Buttons.Add(new ToastButtonDismiss());
                break;

            case CategoryId.Email:
                //toastVisual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo() { Source = "Assets/iOS7_App_Icon_Email.png" };
                toastActions.Buttons.Add(new ToastButtonDismiss());
                break;

            default:
                toastActions.Buttons.Add(new ToastButtonDismiss());
                break;
            }

            ToastContent toastContent = new ToastContent()
            {
                Visual   = toastVisual,
                Scenario = ToastScenario.Default,
                Actions  = toastActions,
            };

            toastXml = toastContent.GetXml();

            ToastNotification toastNotification = new ToastNotification(toastXml)
            {
                ExpirationTime = DateTime.Now.AddMinutes(5)
            };

            ToastNotificationManager.CreateToastNotifier().Show(toastNotification);

            // Old stuff
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                this.DataList.Add(o);
            });
        }
예제 #7
0
        private async Task CreateNotifications()
        {
            var ToastNotifier      = ToastNotificationManager.CreateToastNotifier();
            var ScheduledToastList = ToastNotifier.GetScheduledToastNotifications();

            ActiList = await ActiMan.GetItemsAsync(true);

            var ValidItems = ActiList.Where(x => (DateTime.Now.TimeOfDay - x.WhenNotify.TimeOfDay).TotalMinutes <= 0)?.Where(x => !ScheduledToastList.Select(y => y.Id).Contains("Acti" + x.ID)).ToList();

            if (ValidItems == null)
            {
                return;
            }
            else if (ValidItems.Count == 0)
            {
                return;
            }


            foreach (var item in ValidItems)
            {
                if (!item.Notify || item.Secured || !item.NotifyDays.Contains(DateTime.Today.DayOfWeek))
                {
                    break;
                }

                if ((!item.Dates.Contains(DateTime.Today)) && ((item.End >= DateTime.Today) && (item.Start <= DateTime.Today)))
                {
                    XmlDocument xml = Notifications.GetXml(new string[2] {
                        "Uncompleted activity", $"Activity {item.Name} isn't completed."
                    }, ToastTemplateType.ToastText02);

                    DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, item.WhenNotify.Hour, item.WhenNotify.Minute, item.WhenNotify.Second);

                    if (now.Minute == DateTime.Now.Minute)
                    {
                        now.AddMinutes(1);
                    }

                    ScheduledToastNotification newScheduled = new ScheduledToastNotification(xml, now)
                    {
                        Id = "Acti" + item.ID
                    };

                    ToastNotificationManager.CreateToastNotifier().AddToSchedule(newScheduled);
                    //if (NotifyQueue <= 5)
                    //{
                    //    NotifyQueue++;

                    //    Queue.Add(item);
                    //}
                }

                if (item.Dates.Contains(DateTime.Today))
                {
                    var scheduledNotification = ToastNotificationManager.CreateToastNotifier().GetScheduledToastNotifications().FirstOrDefault(x => x.Id == "Acti" + item.ID);

                    if (scheduledNotification != null)
                    {
                        ToastNotificationManager.CreateToastNotifier().RemoveFromSchedule(scheduledNotification);
                    }
                }
            }

            defferal.Complete();
        }
예제 #8
0
        private async void Share_Click(object sender, RoutedEventArgs e)
        {
            var    bitmap = new RenderTargetBitmap();
            string name;

            if (_card.Name == null || _card.Name == "")
            {
                name = "色卡";
            }
            else
            {
                name = _card.Name;
            }
            StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(name + ".jpg", CreationCollisionOption.ReplaceExisting);

            await bitmap.RenderAsync(Stamp);

            var buffer = await bitmap.GetPixelsAsync();

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encod = await BitmapEncoder.CreateAsync(
                    BitmapEncoder.JpegEncoderId, stream);

                encod.SetPixelData(BitmapPixelFormat.Bgra8,
                                   BitmapAlphaMode.Ignore,
                                   (uint)bitmap.PixelWidth,
                                   (uint)bitmap.PixelHeight,
                                   DisplayInformation.GetForCurrentView().LogicalDpi,
                                   DisplayInformation.GetForCurrentView().LogicalDpi,
                                   buffer.ToArray()
                                   );
                await encod.FlushAsync();
            }
            // In a real app, these would be initialized with actual data
            string title = "色卡已保存到图片库中";
            string image = file.Path;
            // Construct the visuals of the toast
            ToastVisual visual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        {
                            Text = title
                        },
                        new AdaptiveImage()
                        {
                            Source = image
                        }
                    },
                }
            };
            int conversationId = 2;
            // Construct the actions for the toast (inputs and buttons)
            ToastActionsCustom actions = new ToastActionsCustom()
            {
                Buttons =
                {
                    new ToastButton("复制", new QueryString()
                    {
                        { "action",       "copy"                    },
                        { "conversationId",conversationId.ToString() }
                    }.ToString())

                    /*
                     * new ToastButton("查看", new QueryString()
                     * {
                     *  { "action", "viewImage" },
                     *  { "imageUrl", image }
                     *
                     * }.ToString())
                     */
                }
            };
            ToastContent toastContent = new ToastContent()
            {
                Visual  = visual,
                Actions = actions,
                // Arguments when the user taps body of toast
                Launch = new QueryString()
                {
                    { "action", "viewConversation" },
                    { "conversationId", conversationId.ToString() }
                }.ToString()
            };
            var toast = new ToastNotification(toastContent.GetXml());

            toast.ExpirationTime = DateTime.Now.AddMinutes(1);
            ToastNotificationManager.CreateToastNotifier().Show(toast);
            DataPackage dataPackage = new DataPackage();

            dataPackage.RequestedOperation = DataPackageOperation.Copy;
            dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromFile(file));
            Clipboard.SetContent(dataPackage);
        }
예제 #9
0
 public NotificationService()
 {
     notifier       = ToastNotificationManager.CreateToastNotifier();
     contentBuilder = new ContentBuilder();
 }
예제 #10
0
        public override async void Connect()
        {
            if (server == null)
            {
                return;
            }

            IsAuthed          = false;
            ReadOrWriteFailed = false;

            if (!ConnCheck.HasInternetAccess)
            {
                var autoReconnect = Config.GetBoolean(Config.AutoReconnect);
                var msg           = autoReconnect
                    ? "We'll try to connect once a connection is available."
                    : "Please try again once your connection is restored";

                var error = Irc.CreateBasicToast("No connection detected.", msg);
                error.ExpirationTime = DateTime.Now.AddDays(2);
                ToastNotificationManager.CreateToastNotifier().Show(error);

                if (!autoReconnect)
                {
                    DisconnectAsync(attemptReconnect: autoReconnect);
                }

                return;
            }

            streamSocket = new StreamSocket();
            streamSocket.Control.KeepAlive = true;

            if (Config.GetBoolean(Config.IgnoreSSL))
            {
                streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
            }

            dataStreamLineReader = new SafeLineReader();

            try
            {
                var protectionLevel = server.ssl ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
                Debug.WriteLine("Attempting to connect...");
                await streamSocket.ConnectAsync(new Windows.Networking.HostName(server.hostname), server.port.ToString(), protectionLevel);

                Debug.WriteLine("Connected!");

                reader = new DataReader(streamSocket.InputStream);
                writer = new DataWriter(streamSocket.OutputStream);

                IsConnected    = true;
                IsReconnecting = false;

                ConnectionHandler();
            }
            catch (Exception e)
            {
                var autoReconnect = Config.GetBoolean(Config.AutoReconnect, true);
                var msg           = autoReconnect
                    ? "Attempting to reconnect..."
                    : "Please try again later.";

                AddError("Error whilst connecting: " + e.Message + "\n" + msg);
                AddError(e.StackTrace);
                AddError("If this error keeps occuring, ensure your connection settings are correct.");

                DisconnectAsync(attemptReconnect: autoReconnect);

                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
        }
 public ToastNotifier CreateToastNotifier()
 {
     return(ToastNotificationManager.CreateToastNotifier());
 }
예제 #12
0
        private void session_Revoked(object sender, ExtendedExecutionRevokedEventArgs args)
        {
            var toast = CreateBasicToast("Warning", "The extended execution session has been revoked. Connection may be lost when minimized.");

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
예제 #13
0
        private void UpdatePrimaryTile(List <GetAttentionUpdate> news)
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;

            if (news == null || !news.Any())
            {
                return;
            }

            try
            {
                var updater = TileUpdateManager.CreateTileUpdaterForApplication();
                updater.EnableNotificationQueueForWide310x150(true);
                updater.EnableNotificationQueueForSquare150x150(true);
                updater.EnableNotificationQueueForSquare310x310(true);
                updater.EnableNotificationQueue(true);

                List <string> oldList = new List <string>();
                updater.Clear();
                bool updateVideo   = SettingHelper.Get_DT();
                bool updateBnagumi = SettingHelper.Get_FJ();
                try
                {
                    if (SettingHelper.Get_TsDt().Length != 0)
                    {
                        oldList = SettingHelper.Get_TsDt().ToString().Split(',').ToList();
                        //oldList.RemoveAt(0);
                    }
                    else
                    {
                        string s1 = "";
                        foreach (var item in news)
                        {
                            s1 += item.addition.aid + ",";
                        }
                        s1 = s1.Remove(s1.Length - 1);
                        SettingHelper.Set_TsDt(s1);
                        //container.Values["TsDt"] = s1;
                    }
                }
                catch (Exception)
                {
                }


                foreach (var n in news)
                {
                    if (news.IndexOf(n) <= 4)
                    {
                        var doc = new XmlDocument();
                        var xml = string.Format(TileTemplateXml, n.addition.pic, n.addition.title, n.addition.description);
                        doc.LoadXml(WebUtility.HtmlDecode(xml), new XmlLoadSettings
                        {
                            ProhibitDtd              = false,
                            ValidateOnParse          = false,
                            ElementContentWhiteSpace = false,
                            ResolveExternals         = false
                        });
                        updater.Update(new TileNotification(doc));
                    }

                    //通知
                    if (oldList != null && oldList.Count != 0)
                    {
                        if (!oldList.Contains(n.addition.aid))
                        {
                            ToastTemplateType toastTemplate     = ToastTemplateType.ToastText01;
                            XmlDocument       toastXml          = ToastNotificationManager.GetTemplateContent(toastTemplate);
                            XmlNodeList       toastTextElements = toastXml.GetElementsByTagName("text");
                            IXmlNode          toastNode         = toastXml.SelectSingleNode("/toast");
                            ((XmlElement)toastNode).SetAttribute("duration", "short");
                            ((XmlElement)toastNode).SetAttribute("launch", n.addition.aid);
                            if (n.type == 3)
                            {
                                if (updateBnagumi)
                                {
                                    toastTextElements[0].AppendChild(toastXml.CreateTextNode("您关注的《" + n.source.title + "》" + "更新了第" + n.content.index + "话"));
                                    ToastNotification toast = new ToastNotification(toastXml);
                                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                                }
                            }
                            else
                            {
                                if (updateVideo)
                                {
                                    toastTextElements[0].AppendChild(toastXml.CreateTextNode(n.source.uname + "" + "上传了《" + n.addition.title + "》"));
                                    ToastNotification toast = new ToastNotification(toastXml);
                                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                                }
                            }
                        }
                    }
                }
                //container.Values["Ts"] = news;
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                string s = "";
                foreach (var item in news)
                {
                    s += item.addition.aid + ",";
                }
                s = s.Remove(s.Length - 1);
                SettingHelper.Set_TsDt(s);
            }
        }
        private void UIElement_OnTapped(object sender, TappedRoutedEventArgs e)
        {
            var notification = NielsNotification();

            ToastNotificationManager.CreateToastNotifier().Show(notification);
        }
예제 #15
0
        public async Task UpdateScheduleSummaryNotificationAsync()
        {
            if (!ShouldUpdateScheduleSummary)
            {
                return;
            }

            List <ScheduleEntryViewModel> schedule;

            try
            {
                schedule = await GetTodayScheduleAsync();
            }
            catch (LocalCacheRequestFailedException)
            {
                return;
            }

            TileUpdateManager.CreateTileUpdaterForApplication().Clear();
            BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
            if (schedule.Count == 0)
            {
                return;
            }

            var tile = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileSmall = new TileBinding()
                    {
                        Content = new TileBindingContentIconic()
                    },
                    TileMedium          = GetTile(schedule, TileSize.Medium),
                    TileWide            = GetTile(schedule, TileSize.Wide),
                    TileLarge           = GetTile(schedule, TileSize.Large),
                    LockDetailedStatus1 = schedule[0].Name,
                    LockDetailedStatus2 = schedule[0].TimeRangeDisplay,
                    LockDetailedStatus3 = schedule[0].Room
                }
            };
            var tileNotification = new TileNotification(tile.GetXml());

            tileNotification.ExpirationTime = schedule[0].LocalEndTime;
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            var badge             = new BadgeNumericContent((uint)schedule.Count);
            var badgeNotification = new BadgeNotification(badge.GetXml());

            badgeNotification.ExpirationTime = schedule[0].LocalEndTime;
            BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeNotification);

            if (ShouldSendScheduleSummaryToast)
            {
                ToastContent toast             = GetToast(schedule);
                var          toastNotification = new ToastNotification(toast.GetXml())
                {
                    Group          = ToastTypes.ScheduleSummary.ToString(),
                    Tag            = Guid.NewGuid().ToString(),
                    ExpirationTime = schedule.Max(x => x.LocalEndTime)
                };
                ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
                SetScheduleSummaryToastSentStatus();
            }
        }
 public ToastNotification()
 {
     _toastNotifier = ToastNotificationManager.CreateToastNotifier();
 }
예제 #17
0
 public NotificationsManager(IStartMenuShortcutManager shortcutManager, IAppInfo appInfo)
 {
     shortcutManager.EnsureShortcut();
     toastNotifier = ToastNotificationManager.CreateToastNotifier(appInfo.Name);
     dispatcher    = Dispatcher.CurrentDispatcher;
 }
예제 #18
0
        private async void Create_Click(object sender, RoutedEventArgs e)
        {
            if (CLListView.SelectedItems.Count == 1)
            {
                Reminder reminder = new Reminder();

                if (String.IsNullOrWhiteSpace(NameBox.Text))
                {
                    reminder.ReminderName = "Untitled Reminder";
                }
                else
                {
                    reminder.ReminderName = NameBox.Text;
                }

                if (String.IsNullOrWhiteSpace(LocationBox.Text))
                {
                    reminder.ReminderLocation = "Location: None";
                }
                else
                {
                    reminder.ReminderLocation = LocationBox.Text;
                }

                if (String.IsNullOrWhiteSpace(NotesBox.Text))
                {
                    reminder.ReminderNotes = "Notes: None";
                }
                else
                {
                    reminder.ReminderNotes = NotesBox.Text;
                }

                var reminderDate = CLDatePicker.Date;

                if (reminderDate.HasValue)
                {
                    DateTime date          = reminderDate.Value.DateTime;
                    string   formattedDate = date.ToString("MM/dd/yyyy");
                    reminder.ReminderDate = formattedDate;

                    var notificationDate = CLDatePicker.Date.Value.DateTime;
                    reminder.ReminderNotification = notificationDate;
                }
                else
                {
                    reminder.ReminderDate         = "Date: None";
                    reminder.ReminderNotification = DateTime.Now;
                }

                var    timeHours   = CLTimePicker.Time.Hours;
                var    timeMinutes = CLTimePicker.Time.Minutes;
                string amPm;
                string formattedHours;
                string formattedMinutes;
                string formattedTime;

                if (timeHours > 12)
                {
                    timeHours -= 12;
                    amPm       = "PM";
                }
                else
                {
                    amPm = "AM";
                }

                formattedHours = timeHours.ToString();

                if (timeMinutes < 10)
                {
                    formattedMinutes = timeMinutes.ToString();
                    formattedMinutes = "0" + formattedMinutes;
                }
                else
                {
                    formattedMinutes = timeMinutes.ToString();
                }

                if (timeHours == 0 && timeMinutes == 0)
                {
                    formattedTime = "Time: None";
                }
                else
                {
                    formattedTime = formattedHours + ":" + formattedMinutes + " " + amPm;
                }

                reminder.ReminderTime = formattedTime;

                ToastVisual visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderName
                            },
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderLocation
                            },
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderNotes
                            }
                        }
                    }
                };

                ToastContent toastContent = new ToastContent()
                {
                    Visual = visual
                };

                var toast = new ToastNotification(toastContent.GetXml());
                toast.ExpirationTime = DateTime.Now.AddSeconds(5);

                if (CLDatePicker.Date.HasValue)
                {
                    if (CLDatePicker.Date.Value.Date == DateTime.Today.Date)
                    {
                        if (CLTimePicker.Time.Hours <= DateTime.Now.Hour && CLTimePicker.Time.Minutes <= DateTime.Now.Minute)
                        {
                            ToastNotificationManager.CreateToastNotifier().Show(toast);
                        }
                        else
                        {
                            var current        = DateTime.Now;
                            var minutesCounter = CLTimePicker.Time.Minutes - DateTime.Now.Minute;
                            var hoursCounter   = CLTimePicker.Time.Hours - DateTime.Now.Hour;

                            int      intMinutes = Convert.ToInt32(minutesCounter);
                            int      intHours   = Convert.ToInt32(hoursCounter);
                            TimeSpan timeSpan   = new TimeSpan(0, intHours, intMinutes, 0);

                            DateTimeOffset scheduledTime = current + timeSpan;
                            var            toast1        = new ScheduledToastNotification(toastContent.GetXml(), scheduledTime);
                            ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast1);
                        }
                    }
                    else if (CLDatePicker.Date.Value.Date < DateTime.Today.Date)
                    {
                        ToastNotificationManager.CreateToastNotifier().Show(toast);
                    }
                    else
                    {
                        var current        = DateTime.Now;
                        var daysCounter    = CLTimePicker.Time.Days - DateTime.Now.Day;
                        var minutesCounter = CLTimePicker.Time.Minutes - DateTime.Now.Minute;
                        var hoursCounter   = CLTimePicker.Time.Hours - DateTime.Now.Hour;

                        int      intDays    = Convert.ToInt32(daysCounter);
                        int      intMinutes = Convert.ToInt32(minutesCounter);
                        int      intHours   = Convert.ToInt32(hoursCounter);
                        TimeSpan timeSpan   = new TimeSpan(intDays, intHours, intMinutes, 0);

                        DateTimeOffset scheduledTime = current + timeSpan;
                        var            toast1        = new ScheduledToastNotification(toastContent.GetXml(), scheduledTime);
                        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast1);
                    }
                }

                RemindersList.Add(reminder);

                foreach (Reminder selectedItem in CLListView.SelectedItems)
                {
                    RemindersList.Remove(selectedItem);
                }
            }
            else
            {
                Reminder reminder = new Reminder();

                if (String.IsNullOrWhiteSpace(NameBox.Text))
                {
                    reminder.ReminderName = "Untitled Reminder";
                }
                else
                {
                    reminder.ReminderName = NameBox.Text;
                }

                if (String.IsNullOrWhiteSpace(LocationBox.Text))
                {
                    reminder.ReminderLocation = "Location: None";
                }
                else
                {
                    reminder.ReminderLocation = LocationBox.Text;
                }

                if (String.IsNullOrWhiteSpace(NotesBox.Text))
                {
                    reminder.ReminderNotes = "Notes: None";
                }
                else
                {
                    reminder.ReminderNotes = NotesBox.Text;
                }

                var reminderDate = CLDatePicker.Date;

                if (reminderDate.HasValue)
                {
                    DateTime date          = reminderDate.Value.DateTime;
                    string   formattedDate = date.ToString("MM/dd/yyyy");
                    reminder.ReminderDate = formattedDate;

                    var notificationDate = CLDatePicker.Date.Value.DateTime;
                    reminder.ReminderNotification = notificationDate;
                }
                else
                {
                    reminder.ReminderDate         = "Date: None";
                    reminder.ReminderNotification = DateTime.Now;
                }

                var    timeHours   = CLTimePicker.Time.Hours;
                var    timeMinutes = CLTimePicker.Time.Minutes;
                string amPm;
                string formattedHours;
                string formattedMinutes;
                string formattedTime;

                if (timeHours > 12)
                {
                    timeHours -= 12;
                    amPm       = "PM";
                }
                else
                {
                    amPm = "AM";
                }

                formattedHours = timeHours.ToString();

                if (timeMinutes < 10)
                {
                    formattedMinutes = timeMinutes.ToString();
                    formattedMinutes = "0" + formattedMinutes;
                }
                else
                {
                    formattedMinutes = timeMinutes.ToString();
                }

                if (timeHours == 0 && timeMinutes == 0)
                {
                    formattedTime = "Time: None";
                }
                else
                {
                    formattedTime = formattedHours + ":" + formattedMinutes + " " + amPm;
                }

                reminder.ReminderTime = formattedTime;

                ToastVisual visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderName
                            },
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderLocation
                            },
                            new AdaptiveText()
                            {
                                Text = reminder.ReminderNotes
                            }
                        }
                    }
                };

                ToastContent toastContent = new ToastContent()
                {
                    Visual = visual
                };

                var toast = new ToastNotification(toastContent.GetXml());
                toast.ExpirationTime = DateTime.Now.AddSeconds(5);

                if (CLDatePicker.Date.HasValue)
                {
                    if (CLDatePicker.Date.Value.Date == DateTime.Today.Date)
                    {
                        if (CLTimePicker.Time.Hours <= DateTime.Now.Hour && CLTimePicker.Time.Minutes <= DateTime.Now.Minute)
                        {
                            ToastNotificationManager.CreateToastNotifier().Show(toast);
                        }
                        else
                        {
                            var current        = DateTime.Now;
                            var minutesCounter = CLTimePicker.Time.Minutes - DateTime.Now.Minute;
                            var hoursCounter   = CLTimePicker.Time.Hours - DateTime.Now.Hour;

                            int      intMinutes = Convert.ToInt32(minutesCounter);
                            int      intHours   = Convert.ToInt32(hoursCounter);
                            TimeSpan timeSpan   = new TimeSpan(0, intHours, intMinutes, 0);

                            DateTimeOffset scheduledTime = current + timeSpan;
                            var            toast1        = new ScheduledToastNotification(toastContent.GetXml(), scheduledTime);
                            ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast1);
                        }
                    }
                    else if (CLDatePicker.Date.Value.Date < DateTime.Today.Date)
                    {
                        ToastNotificationManager.CreateToastNotifier().Show(toast);
                    }
                    else
                    {
                        var current        = DateTime.Now;
                        var daysCounter    = CLTimePicker.Time.Days - DateTime.Now.Day;
                        var minutesCounter = CLTimePicker.Time.Minutes - DateTime.Now.Minute;
                        var hoursCounter   = CLTimePicker.Time.Hours - DateTime.Now.Hour;

                        int      intDays    = Convert.ToInt32(daysCounter);
                        int      intMinutes = Convert.ToInt32(minutesCounter);
                        int      intHours   = Convert.ToInt32(hoursCounter);
                        TimeSpan timeSpan   = new TimeSpan(intDays, intHours, intMinutes, 0);

                        DateTimeOffset scheduledTime = current + timeSpan;
                        var            toast1        = new ScheduledToastNotification(toastContent.GetXml(), scheduledTime);
                        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast1);
                    }
                }
                RemindersList.Add(reminder);
            }

            NameBox.Text      = "";
            LocationBox.Text  = "";
            NotesBox.Text     = "";
            CLDatePicker.Date = null;
            CLTimePicker.Time = TimeSpan.Zero;

            var localfolder = ApplicationData.Current.LocalFolder;
            var file        = await localfolder.CreateFileAsync("collection.json", CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenStreamForWriteAsync())
                using (var writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    string json = JsonConvert.SerializeObject(RemindersList);
                    await writer.WriteAsync(json);
                }

            ReminderView.IsPaneOpen = false;
        }
 private void PopToast()
 {
     ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(_toastContent.GetXml()));
 }
예제 #20
0
        public async void timertick(object sender, object e)
        {
            timer.Stop();

            string response = await getnewmail();

            dynamic rss = JObject.Parse(response);

            JArray abc = rss.value;

            if (abc.Count <= 0)
            {
                timer.Start();
                return;
            }

            var a = abc[abc.Count - 1];


            foreach (dynamic item in a)
            {
                if (item.Name == "receivedDateTime")
                {
                    receivedDateTime = item.Value;
                }

                if (item.Name == "subject")
                {
                    subject = item.Value;
                }

                if (item.Name == "id")
                {
                    if (!(id == (string)item.Value))
                    {
                        id = item.Value;
                    }
                    else
                    {
                        timer.Start();
                        return;
                    }
                }

                if (item.Name == "sender")
                {
                    JObject senderinfo = item.Value;

                    foreach (dynamic i in senderinfo)
                    {
                        JObject aaa = i.Value;

                        foreach (dynamic items in aaa)
                        {
                            if (items.Key == "address")
                            {
                                sendermailid = items.Value;
                            }
                        }
                    }
                }
            }

            // get mails to check for any new emails
            if (string.IsNullOrEmpty(receivedDateTime.ToString()))
            {
                timer.Start();
                return;
            }

            // Data for toast notification
            string title       = "You've got a new Mail.";
            string mailfrom    = "From : " + sendermailid;
            string mailsubject = "Subject : " + subject;

            // Toast content
            var toastContent = new ToastContent()
            {
                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = title
                            },
                            new AdaptiveText()
                            {
                                Text = mailfrom
                            },
                            new AdaptiveText()
                            {
                                Text = mailsubject
                            }
                        }
                    }
                },
                Actions = new ToastActionsCustom()
                {
                    Buttons =
                    {
                        new ToastButtonDismiss()
                    }
                },
                Launch   = "action=viewEvent&eventId=1983",
                Scenario = ToastScenario.Reminder
            };

            // And create the toast notification
            var toast = new ToastNotification(toastContent.GetXml());

            // Set expiration time
            toast.ExpirationTime = DateTime.Now.AddMinutes(1);

            // pri
            toast.Tag   = "18365";
            toast.Group = "wallPosts";

            ToastNotificationManager.CreateToastNotifier().Show(toast);

            timer.Start();
        }
예제 #21
0
        private void ShowNewVideosToastNotification(Subscription subscription, SubscriptionSource source, IEnumerable <Database.NicoVideo> newItems)
        {
            var mylistMan = App.Current.Container.Resolve <UserMylistManager>();

            // TODO: プレイリスト毎にまとめたほうがいい?

            foreach (var dest in subscription.Destinations)
            {
                Interfaces.IMylist list = null;
                if (dest.Target == SubscriptionDestinationTarget.LocalPlaylist)
                {
                    list = MylistHelper.FindMylistInCached(dest.PlaylistId, PlaylistOrigin.Local);
                }
                else if (dest.Target == SubscriptionDestinationTarget.LoginUserMylist)
                {
                    list = MylistHelper.FindMylistInCached(dest.PlaylistId, PlaylistOrigin.LoginUser);
                }

                IList <Database.NicoVideo> videoList;
                if (NewItemsPerPlayableList.TryGetValue(list, out var cacheVideoList))
                {
                    videoList = cacheVideoList.Item1;

                    if (!cacheVideoList.Item2.Contains(subscription))
                    {
                        cacheVideoList.Item2.Add(subscription);
                    }
                }
                else
                {
                    videoList = new List <Database.NicoVideo>();
                    NewItemsPerPlayableList.Add(list, new Tuple <IList <Database.NicoVideo>, IList <Subscription> >(videoList, new List <Subscription>()
                    {
                        subscription
                    }));
                }

                foreach (var video in newItems)
                {
                    videoList.Add(video);
                }
            }


            try
            {
                foreach (var pair in NewItemsPerPlayableList)
                {
                    var playableList    = pair.Key;
                    var newItemsPerList = pair.Value.Item1;
                    var subscriptions   = pair.Value.Item2;

                    ToastVisual visual = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children = { }
                        }
                    };

                    visual.BindingGeneric.Children.Insert(0, new AdaptiveText()
                    {
                        Text      = $"『{playableList.Label}』に新着動画を追加",
                        HintStyle = AdaptiveTextStyle.Base
                    });

                    foreach (var item in newItemsPerList)
                    {
                        visual.BindingGeneric.Children.Add(new AdaptiveText()
                        {
                            Text      = item.Title,
                            HintStyle = AdaptiveTextStyle.BaseSubtle
                        });
                    }



                    ToastActionsCustom action = new ToastActionsCustom()
                    {
                        Buttons =
                        {
                            new ToastButton("視聴する",  new LoginRedirectPayload()
                            {
                                RedirectPageType = HohoemaPageType.VideoPlayer,RedirectParamter                             = newItemsPerList.First().RawVideoId
                            }.ToParameterString())
                            {
                                ActivationType = ToastActivationType.Foreground,
                            },
                            new ToastButton("購読を管理", new LoginRedirectPayload()
                            {
                                RedirectPageType = HohoemaPageType.Subscription
                            }.ToParameterString())
                            {
                                ActivationType = ToastActivationType.Foreground,
                            },
                        }
                    };

                    ToastContent toastContent = new ToastContent()
                    {
                        Visual  = visual,
                        Actions = action,
                    };

                    var toast = new ToastNotification(toastContent.GetXml());

                    var notifier = ToastNotificationManager.CreateToastNotifier();

                    toast.Tag   = playableList.Id;
                    toast.Group = TOAST_GROUP;
                    notifier.Show(toast);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
예제 #22
0
        public void Create(DateTime alarmTime, string id, string content)
        {
            string title = "浅易便签";

            // Construct the visuals of the toast
            ToastVisual visual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        {
                            Text = title
                        },

                        new AdaptiveText()
                        {
                            Text = content
                        }
                    }
                }
            };
            // In a real app, these would be initialized with actual data
            //int conversationId = 384928;
            // Construct the actions for the toast (inputs and buttons)
            ToastActionsCustom actions = new ToastActionsCustom()
            {
                Inputs =
                {
                    new ToastSelectionBox("snoozeTime")
                    {
                        DefaultSelectionBoxItemId = "15",
                        Title = "推迟时间为",
                        Items =
                        {
                            new ToastSelectionBoxItem("5",    "5 分钟"),
                            new ToastSelectionBoxItem("15",   "15 分钟"),
                            new ToastSelectionBoxItem("60",   "1 小时"),
                            new ToastSelectionBoxItem("240",  "4 小时"),
                            new ToastSelectionBoxItem("1440", "1 天")
                        }
                    }
                },

                Buttons =
                {
                    new ToastButtonSnooze()
                    {
                        SelectionBoxId = "snoozeTime",
                    },

                    new ToastButtonDismiss()
                }
            };

            ToastContent toastContent = new ToastContent()
            {
                Visual   = visual,
                Actions  = actions,
                Scenario = ToastScenario.Reminder,
                // Arguments when the user taps body of toast
                Launch = new QueryString()
                {
                    { "action", "viewConversation" },
                    //{ "conversationId", conversationId.ToString() }
                }.ToString()
            };

            if (alarmTime > DateTime.Now.AddSeconds(5))
            {
                // Create the scheduled notification
                var scheduledNotif = new ScheduledToastNotification(
                    toastContent.GetXml(), // Content of the toast
                    alarmTime              // Time we want the toast to appear at
                    )
                {
                    Id = id
                };

                // And add it to the schedule
                ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledNotif);
            }
            else
            {
                var notifyPopup = new NotifyPopup("设定时间已过期");
                notifyPopup.Show();
            }
        }
예제 #23
0
        public async static Task Update()
        {
            StorageSettings settings = new StorageSettings();

            if (settings.UserSignedIn)
            {
                //计算当前周数以及当天是一周中的哪一天
                int daySpan = (DateTime.Today - settings.TermlyDate).Days;
                if (daySpan < 0 || daySpan / 7 > settings.WeekNum)
                {
                    return;
                }

                int weekOfTerm = daySpan / 7;
                int temp       = (int)DateTime.Today.DayOfWeek;//0表示一周的开始(周日),所以需要根据自身需要做个修订
                int dayOfWeek  = temp == 0 ? 6 : --temp;

                //获取所需课程数据 (上课20分钟内不更新)
                var weeklyList = await CourseDataService.LoadWeeklyDataFromIsoStoreAsync(weekOfTerm + 1); //当前周数据

                var dailyList = weeklyList[dayOfWeek];                                                    //当天数据
                var result    = from c in dailyList
                                where !string.IsNullOrEmpty(c.FullName) && DateTime.Now < Convert.ToDateTime(c.StartTime).AddMinutes(20)
                                select c;
                Debug.WriteLine(result.Count());

                //更新磁贴
                if (result.Count() > 0)
                {
                    var         c                      = result.First();
                    XmlDocument wideTileXML            = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150IconWithBadgeAndText);
                    XmlNodeList wideTileTestAttributes = wideTileXML.GetElementsByTagName("text");
                    wideTileTestAttributes[0].AppendChild(wideTileXML.CreateTextNode(c.FullName));
                    wideTileTestAttributes[1].AppendChild(wideTileXML.CreateTextNode($"时间: {c.StartTime} - {c.EndTime}"));
                    wideTileTestAttributes[2].AppendChild(wideTileXML.CreateTextNode("地点: " + c.Classroom));

                    XmlNodeList wideTileImageAttributes = wideTileXML.GetElementsByTagName("image");
                    ((XmlElement)wideTileImageAttributes[0]).SetAttribute("src", "ms-appx:///Assets/Toast.png");
                    TileNotification notification = new TileNotification(wideTileXML);
                    //notification.ExpirationTime = DateTime
                    TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
                    //TileUpdateManager.CreateTileUpdaterForSecondaryTile("SecondaryTile")?.Update(notification);

                    XmlDocument badgeXml     = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
                    XmlElement  badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
                    badgeElement.SetAttribute("value", result.Count().ToString());
                    BadgeNotification badge = new BadgeNotification(badgeXml);
                    BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
                    //TileUpdateManager.CreateTileUpdaterForSecondaryTile("SecondaryTile")?.Update(notification);

                    //未开放二级磁贴选项
                    //if (SecondaryTile.Exists("SecondaryTile"))
                    //{
                    //    notification = new TileNotification(wideTileXML);
                    //    badge = new BadgeNotification(badgeXml);
                    //    TileUpdateManager.CreateTileUpdaterForSecondaryTile("SecondaryTile").Update(notification);
                    //    BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile("SecondaryTile").Update(badge);
                    //}
                }
                else
                {
                    //清空磁贴
                    TileUpdateManager.CreateTileUpdaterForApplication().Clear();
                    BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();

                    //if (SecondaryTile.Exists("SecondaryTile"))//应用中未设置二级磁贴
                    //{
                    //    TileUpdateManager.CreateTileUpdaterForSecondaryTile("SecondaryTile").Clear();
                    //    BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile("SecondaryTile").Clear();
                    //}

                    if (settings.PushNotification && DateTime.Now.Hour >= 21 && settings.NotificationDate != DateTime.Today)//每天晚上9点钟以后推送一次
                    {
                        //检查次日是否有课
                        if (++dayOfWeek == 7)
                        {
                            weekOfTerm++;
                            dayOfWeek = 0;
                        }
                        weeklyList = await CourseDataService.LoadWeeklyDataFromIsoStoreAsync(weekOfTerm);

                        dailyList = weeklyList[dayOfWeek];

                        result = from c in dailyList
                                 where !string.IsNullOrEmpty(c.FullName)
                                 select c;
                        Debug.WriteLine(result.Count());

                        if (result.Count() != 0)
                        {
                            settings.NotificationDate = DateTime.Today;

                            XmlDocument toastXML          = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
                            var         toastTextElements = toastXML.GetElementsByTagName("text");
                            toastTextElements[0].AppendChild(toastXML.CreateTextNode(String.Format($"亲,你明天共有{result.Count()}节课,不要迟到哟!(●ˇ∀ˇ●)")));
                            ToastNotification notification = new ToastNotification(toastXML);
                            ToastNotificationManager.CreateToastNotifier().Show(notification);
                        }
                    }
                }
            }
        }
예제 #24
0
        private void SendToast(string text = null)
        {
            //This is using NotificationsExtensions
            var content = new ToastContent()
            {
                Launch = "toastResponse",

                Visual = new ToastVisual()
                {
                    TitleText = new ToastText
                    {
                        Text = "UwpDeepDive notification"
                    },

                    BodyTextLine1 = new ToastText
                    {
                        Text = "Got a note to add?"
                    },
                    BodyTextLine2 = new ToastText()
                    {
                        Text = text ?? ""
                    }
                },

                Actions = new ToastActionsCustom()
                {
                    Inputs =
                    {
                        new ToastTextBox("tbReply")
                        {
                            PlaceholderContent = "add note here"
                        }
                    },

                    Buttons =
                    {
                        new ToastButton("save", "save")
                        {
                            ActivationType = ToastActivationType.Background
                        },
                        new ToastButton("launch", "launch")
                        {
                            ActivationType = ToastActivationType.Foreground
                        }
                    }
                },

                Audio = new ToastAudio
                {
                    Src = new Uri("ms-winsoundevent:Notification.IM")
                }
            };

            var doc = content.GetXml();

            // Generate WinRT notification
            var toast = new ToastNotification(doc);

            var notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.Show(toast);

            //Debug.WriteLine(content.GetContent());

            /*
             * <?xml version="1.0" encoding="UTF-8"?>
             *  <toast launch="toastResponse">
             *      <visual>
             *          <binding template="ToastGeneric">
             *              <text>UwpDeepDive notification</text>
             *              <text>Got a note to add?</text>
             *              <text>ApplicationTriggerDetails</text>
             *          </binding>
             *      </visual>
             *      <audio src="ms-winsoundevent:Notification.IM" />
             *      <actions>
             *          <input id="tbReply" type="text" placeHolderContent="add note here" />
             *          <action content="save" arguments="save" activationType="background" />
             *          <action content="launch" arguments="launch" />
             *      </actions>
             *  </toast>
             * </xml>
             */
        }
예제 #25
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string title          = "Welcome To Best of Beijing!";
            string content        = "Hope you enjoy this app!";
            string image          = "Image Content";
            string logo           = "Logo";
            int    conversationId = 384928;

            ToastVisual visual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        {
                            Text = title
                        },
                        new AdaptiveText()
                        {
                            Text = content
                        },
                        new AdaptiveImage()
                        {
                            Source = image
                        }
                    },
                    AppLogoOverride = new ToastGenericAppLogo()
                    {
                        Source   = logo,
                        HintCrop = ToastGenericAppLogoCrop.Circle
                    }
                }
            };
            ToastActionsCustom actions = new ToastActionsCustom()
            {
                Inputs =
                {
                    new ToastTextBox("tbReply")
                    {
                        PlaceholderContent = "Type a response"
                    }
                },
                Buttons =
                {
                    new ToastButton("Reply", new QueryString()
                    {
                        { "action",          "reply"                   },
                        { "conversationId",  conversationId.ToString() }
                    }.ToString())
                    {
                        ActivationType = ToastActivationType.Background,
                        ImageUri       = "Assets/Reply.png",
                        TextBoxId      = "tbReply"
                    },
                    new ToastButton("Like",  new QueryString()
                    {
                        { "action",          "like"                    },
                        { "conversationId",  conversationId.ToString() }
                    }.ToString())
                    {
                        ActivationType = ToastActivationType.Background
                    },
                    new ToastButton("View",  new QueryString()
                    {
                        { "action",          "viewImage"               },
                        { "imageUrl",        image                     }
                    }.ToString())
                }
            };
            ToastContent toastContent = new ToastContent()
            {
                Visual  = visual,
                Actions = actions,

                Launch = new QueryString()
                {
                    { "action", "viewConversation" },
                    { "conversationId", conversationId.ToString() }
                }.ToString()
            };
            ToastNotification notification = new ToastNotification(toastContent.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(notification);
        }
예제 #26
0
        public void SendAlarmToast(bool UseDefaultToast, DateTime timeOffset, string title = "", string content = "")
        {
            if (UseDefaultToast)
            {
                ToastVisual visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = DefaultTitel
                            },
                            new AdaptiveText()
                            {
                                Text = DefaultContent
                            }
                        },
                        //AppLogoOverride = new ToastGenericAppLogo()
                        //{
                        //    Source = DefaultLogo,
                        //    HintCrop = ToastGenericAppLogoCrop.Circle
                        //}
                    }
                };

                ToastContent toastContent = new ToastContent()
                {
                    Scenario = ToastScenario.Alarm,
                    Audio    = new ToastAudio()
                    {
                        Src = new Uri("ms-winsoundevent:Notification.Looping.Alarm")
                    },
                    Visual  = visual,
                    Actions = new ToastActionsCustom()
                    {
                        Buttons =
                        {
                            new ToastButtonSnooze(),
                            new ToastButtonDismiss()
                        }
                    },
                    Launch = new QueryString()
                    {
                        { "action", "CapturePage" }
                    }.ToString()
                };
                try
                {
                    ToastNotificationManager.History.Clear();
                    ScheduledToastNotification toast = new ScheduledToastNotification(toastContent.GetXml(), timeOffset);
                    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
                }
                catch
                { }
            }
            else
            {
                ToastVisual visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = title
                            },
                            new AdaptiveText()
                            {
                                Text = content
                            }
                        },
                        //AppLogoOverride = new ToastGenericAppLogo()
                        //{
                        //    Source = DefaultLogo,
                        //    HintCrop = ToastGenericAppLogoCrop.Circle
                        //}
                    }
                };

                ToastContent toastContent = new ToastContent()
                {
                    Scenario = ToastScenario.Alarm,
                    Audio    = new ToastAudio()
                    {
                        Src = new Uri("ms-winsoundevent:Notification.Looping.Alarm")
                    },
                    Visual  = visual,
                    Actions = new ToastActionsCustom()
                    {
                        Buttons =
                        {
                            new ToastButtonSnooze(),
                            new ToastButtonDismiss()
                        }
                    },
                    Launch = new QueryString()
                    {
                        { "action", "CapturePage" }
                    }.ToString()
                };

                try
                {
                    ToastNotificationManager.History.Clear();
                    ScheduledToastNotification toast = new ScheduledToastNotification(toastContent.GetXml(), timeOffset);
                    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
                }
                catch
                {
                }
            };
        }
        private async void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var song       = new Songprop();
            var playesouns = (Songprop)e.ClickedItem;
            var images     = playesouns.albumcover;
            var name       = playesouns.songartist;
            var names      = playesouns.songname;

            newelements.AutoPlay     = true;
            newelements.PosterSource = images;


            mygridview.ScrollIntoView(playesouns);
            mygridview.SelectedItem = true;

            newelements.TransportControls.IsStopEnabled               = true;
            newelements.TransportControls.IsStopButtonVisible         = true;
            newelements.TransportControls.IsFastForwardButtonVisible  = true;
            newelements.TransportControls.IsFastForwardEnabled        = true;
            newelements.TransportControls.IsFastRewindButtonVisible   = true;
            newelements.TransportControls.IsFastRewindEnabled         = true;
            newelements.TransportControls.IsPlaybackRateEnabled       = true;
            newelements.TransportControls.IsPlaybackRateButtonVisible = true;

            newelements.SetSource(await playesouns.songfile.OpenAsync(FileAccessMode.Read), playesouns.songfile.ContentType);
            newelements.Play();
            remaintxt.Text = string.Format("Now Playing: {0}", names);

            resultetxtblock.Text = names;
            tiletxt.Text         = name;


            var tilexml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText02);

            var tileattr = tilexml.GetElementsByTagName("text");

            tileattr[0].AppendChild(tilexml.CreateTextNode(resultetxtblock.Text));
            tileattr[1].AppendChild(tilexml.CreateTextNode(tiletxt.Text));
            var tilenotify = new TileNotification(tilexml);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tilenotify);

            var tiles   = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150IconWithBadgeAndText);
            var tileatr = tiles.GetElementsByTagName("text");

            tileatr[0].AppendChild(tiles.CreateTextNode(resultetxtblock.Text));
            tileatr[1].AppendChild(tiles.CreateTextNode(tiletxt.Text));
            var tilenotifyy = new TileNotification(tiles);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tilenotifyy);

            var template = ToastTemplateType.ToastText01;
            var xml      = ToastNotificationManager.GetTemplateContent(template);

            xml.DocumentElement.SetAttribute("launch", "Args");
            var text     = xml.CreateTextNode(resultetxtblock.Text);
            var elements = xml.GetElementsByTagName("text");

            elements[0].AppendChild(text);
            var toast    = new ToastNotification(xml);
            var notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.Show(toast);
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            try
            {
                var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();

                if (NetworkInterface.GetIsNetworkAvailable() &&
                    (connectionCost.NetworkCostType == NetworkCostType.Unknown ||
                     connectionCost.NetworkCostType == NetworkCostType.Unrestricted))
                {
                    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

                    var player = JsonConvert.DeserializeObject <DestinyPlayerInformation>((string)localSettings.Values["player"]);

                    int    platform  = player.MembershipType;
                    string accountId = player.MembershipID;
                    int    mode      = 5;

                    var bungie = new BungieService(SharedData.BungieApiKey);
                    await bungie.DownloadDestinyManifest();

                    foreach (var characterId in player.CharacterIDs)
                    {
                        var history = await bungie.GetActivityHistory(platform, accountId, characterId, mode);

                        await Task.WhenAll(from pgcr in history
                                           select Task.Run(async() =>
                        {
                            var getActivityDefinition = bungie.GetActivityDefinitionAsync(pgcr.ActivityDetails.ReferenceId);
                            var getModeDefinition     = bungie.GetActivityModeDefinitionAsync(pgcr.ActivityDetails.Mode);

                            var activity = new DestinyUserActivity(pgcr, await getActivityDefinition, await getModeDefinition, characterId);

                            var msGraph = new MsGraphService(SharedData.MsGraphClientId);
                            await msGraph.CreateOrReplaceActivityAsync(activity.Activity);
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                ToastContent toastContent = new ToastContent()
                {
                    Launch = "refresh-activity",
                    Visual = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children =
                            {
                                new AdaptiveText
                                {
                                    Text = "An error occured while refreshing Destiny 2 activity history"
                                }
                            }
                        }
                    }
                };

                var toast = new ToastNotification(toastContent.GetXml());
                toast.ExpirationTime = DateTime.Now.AddDays(2);
                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }

            deferral.Complete();
        }
예제 #29
0
 public void ShowToastNotification(ToastNotification toastNotification)
 {
     ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
 }
예제 #30
0
 private void ScheduleToastNotification(ScheduledToastNotification scheduledToast)
 => ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledToast);