Defines the visual aspects of a toast notification.
예제 #1
0
        public void NotifyWithTemperature(string title, string message, float temperature)
        {
            StringBuilder sb = new StringBuilder();
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                },
                BodyTextLine1 = new ToastText()
                {
                    Text = sb.AppendFormat(message, temperature).ToString()
                }
            };

            _toastContent = new ToastContent()
            {
                Visual = visual,

                // Arguments when the user taps body of toast
                Launch = new QueryString()
                {
                    { "action", "showtemperature" },
                    { "temperature", temperature.ToString() }

                }.ToString()
            };
            SendNotification();
        }
예제 #2
0
        public void NotifyWithDistance(string title, string message, double distance)
        {
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                },
                BodyTextLine1 = new ToastText()
                {
                    Text = message
                }
            };

            _toastContent = new ToastContent()
            {
                Visual = visual,

                // Arguments when the user taps body of toast
                Launch = new QueryString()
                {
                    { "action", "gettingfar" },
                    { "distance", distance.ToString() }

                }.ToString()
            };
            SendNotification();
        }
예제 #3
0
        public static void Do(Match fromWho, Message message_obj)
        {
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = fromWho.person.name + " has sent you a message"
                },
            };

            string textForToast = "";

            if (message_obj.type == "gif")
            {
                textForToast = "Sent you a Giphy";
            }
            else
            {
                var t = message_obj.message;
                textForToast = t;
            }

            visual.BodyTextLine1 = new ToastText()
            {
                Text = textForToast
            };

            // Pass a payload as JSON to the Toast
            dynamic payload = new JObject();
            payload.source = typeof(NewMessageToast).ToString();
            payload.args = fromWho._id;

            string payload_json = payload.ToString();

            ToastContent toastContent = new ToastContent()
            {
                Visual = visual,
                Audio = null,
                Actions = new ToastActionsCustom()
                {
                    Buttons =
                    {
                        new ToastButton("Go to Message", payload_json)
                        {
                            ActivationType = ToastActivationType.Foreground,
                        },
                        new ToastButtonDismiss()
                    }
                },
                Launch = payload_json
            };

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

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        public ToastVisual GetVisualToast(
            string title,
            string contentFirstLine,
            string contentSecondLine,
            IEnumerable<string> imagesPaths = null,
            string logoPath = null)
        {
            var result = new ToastVisual();

            if (title != null)
            {
                result.TitleText = new ToastText()
                {
                    Text = title
                };
            }

            if (contentFirstLine != null)
            {
                result.BodyTextLine1 = new ToastText()
                {
                    Text = contentFirstLine
                };
            }

            if (contentSecondLine != null)
            {
                result.BodyTextLine2 = new ToastText()
                {
                    Text = contentSecondLine
                };
            }

            if (imagesPaths != null && imagesPaths.Count() <= 6)
            {
                imagesPaths
                    .ForEach(i =>
                        result.InlineImages.Add(new ToastImage()
                        {
                            Source = new ToastImageSource(i)
                        }));
            }

            if (logoPath != null)
            {
                result.AppLogoOverride = new ToastAppLogo()
                {
                    Source = new ToastImageSource(logoPath)
                };
            }

            return result;
        }
예제 #5
0
        public static void Do(Match fromWho)
        {
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = "Matched!"
                },
            };

            visual.BodyTextLine1 = new ToastText()
            {
                Text = "You have matched " + fromWho.person.name
            };

            visual.BodyTextLine2 = new ToastText()
            {
                Text = "Chat em up!"
            };

            // Pass a payload as JSON to the Toast
            dynamic payload = new JObject();
            payload.source = typeof(NewMatchToast).ToString();
            payload.args = fromWho._id;

            string payload_json = payload.ToString();

            ToastContent toastContent = new ToastContent()
            {
                Visual = visual,
                Audio = null,
                Actions = new ToastActionsCustom()
                {
                    Buttons =
                    {
                        new ToastButton("Go to Match", payload_json)
                        {
                            ActivationType = ToastActivationType.Foreground,
                        },
                        new ToastButtonDismiss()
                    }
                },
                Launch = payload_json
            };

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

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        public void ShowToast(String value)
        {
            var loader = new Windows.ApplicationModel.Resources.ResourceLoader();

            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = loader.GetString(value)
                },
            };

            ToastContent content = new ToastContent();
            content.Visual = visual;
            var toast = new ToastNotification(content.GetXml());
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        private void OnSendNotificationWithExtension(object sender, RoutedEventArgs e)
        {
            ToastVisual visual = new ToastVisual
            {
                AppLogoOverride = new ToastAppLogo
                {
                    Crop = ToastImageCrop.None,
                    Source = new ToastImageSource("ms-appx:///Assets/MicrosoftLogo.png")
                },
                TitleText = new ToastText
                {
                    Text = "DotNet Spain Conference"
                },
                BodyTextLine1 = new ToastText
                {
                    Text = "How much do you like my session ?"
                }
            };

            ToastSelectionBox selection = new ToastSelectionBox("rating");
            selection.Items.Add(new ToastSelectionBoxItem("1", "1 (Not very much)"));
            selection.Items.Add(new ToastSelectionBoxItem("2", "2"));
            selection.Items.Add(new ToastSelectionBoxItem("3", "3"));
            selection.Items.Add(new ToastSelectionBoxItem("4", "4"));
            selection.Items.Add(new ToastSelectionBoxItem("5", "5 (A lot!)"));

            ToastButton button = new ToastButton("Vote", "vote");
            button.ActivationType = ToastActivationType.Background;

            ToastContent toast = new ToastContent
            {
                Visual = visual,
                ActivationType = ToastActivationType.Background,
                Actions = new ToastActionsCustom
                {
                    Inputs = {selection},
                    Buttons = { button }
                }
            };

            XmlDocument doc = toast.GetXml();
            ToastNotification notification = new ToastNotification(doc);
            ToastNotificationManager.CreateToastNotifier().Show(notification);
        }
        public ToastContent GetToastContent(ToastVisual visual, ToastActionsCustom actions)
        {
            var content = new ToastContent();

            if (visual != null)
            {
                content.Visual = visual;
            }

            if (actions != null)
            {
                content.Actions = actions;
            }

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

            return content;
        }
예제 #9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Task Started!");
            string title = "Holy Balls Background Agent Works!";
            string content = "Shits Great Son!";
            string imageUrl = "http://community.zimbra.com/cfs-file/__key/communityserver-discussions-components-files/1589/girl-happy.JPG";

            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                },

                BodyTextLine1 = new ToastText()
                {
                    Text = content
                },

                InlineImages =
                {
                    new ToastImage()
                    {
                         Source = new ToastImageSource(imageUrl)
                    }
                }
            };

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

            var toast = new ToastNotification(Tcontent.GetXml());
            toast.ExpirationTime = DateTime.Now.AddHours(1);
            toast.Tag = "1";
            toast.Group = "t1";
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
예제 #10
0
        private void ToastGenerator()
        {
            const string title = "Click on time of Emergency!";

            var visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                }

            };

            const int conversationId = 177777;

            var toastContent = new ToastContent()
            {
                Visual = visual,
                Launch = new QueryString()
                {
                    {"conversationId", conversationId.ToString()}
                }.ToString()
            };

            var toast = new ToastNotification(toastContent.GetXml())
            {
                ExpirationTime = DateTime.Now.AddHours(5),
                SuppressPopup = true,
                Tag = "Friends"
            };
            if (ToastNotificationManager.History != null)
            {
                ToastNotificationManager.History.Remove("Friends");
            }

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        //Een (eenmalige) pop up tonen om toestemming aan de gebruiker te vragen voor zijn locatie
        private async void LocatieToestemmingVragen()
        {
            try
            {
                //De pop up tonen en toestemming vragen
                var accessStatus = await Geolocator.RequestAccessAsync();

                //De mogelijke antwoorden overlopen
                switch (accessStatus)
                {
                    case GeolocationAccessStatus.Allowed: //De gebruiker heeft ons toegang gegeven

                        //Mag verdergaan en inloggen
                        this.EnableLogin = true;

                        //aanmaken Geolocator
                        Geolocator geolocator = new Geolocator();

                        //Inschrijven op de StatusChanged voor updates van de permissies voor locaties.
                        geolocator.StatusChanged += OnStatusChanged;
                        geolocator.PositionChanged += OnPositionChanged();

                        //Locatie opvragen
                        Geoposition pos = await geolocator.GetGeopositionAsync();
                        Debug.WriteLine("Positie opgevraagd, lat: " + pos.Coordinate.Point.Position.Latitude + " lon: " + pos.Coordinate.Point.Position.Longitude);

                        //Locatie opslaan als gebruikerslocatie
                        (App.Current as App).UserLocation = pos;

                        break;

                    case GeolocationAccessStatus.Denied: //De gebruiker heeft ons geen toegang gegeven.
                        Debug.WriteLine("Geen locatie: Toestemming geweigerd");

                        //We gaan een Toast tonen om te zeggen dat we de locatie nodig hebben.
                        //Aanmaken tekst voor in Toast
                        string title = "Locatie Nodig";
                        string content = "We krijgen geen toegang tot uw locatie, deze staat softwarematig uitgeschakeld of u geeft ons geen toegang.";

                        //De visuals van de Toast aanmaken
                        ToastVisual visual = new ToastVisual()
                        {
                            TitleText = new ToastText()
                            {
                                Text = title
                            },
                            BodyTextLine1 = new ToastText()
                            {
                                Text = content
                            },
                            AppLogoOverride = new ToastAppLogo()
                            {
                                Source = new ToastImageSource("../Assets/StoreLogo.png"),
                                Crop = ToastImageCrop.Circle
                            }
                        };

                        //De interacties met de toast aanmaken
                        ToastActionsCustom actions = new ToastActionsCustom()
                        {
                            Buttons =
                        {
                            new ToastButton("Geef Toestemming", new QueryString()
                            {
                                {"action", "openLocationServices" }
                            }.ToString())
                        }
                        };

                        //De final toast content aanmaken
                        ToastContent toastContent = new ToastContent()
                        {
                            Visual = visual,
                            Actions = actions,

                            //Argumenten wanneer de user de body van de toast aanklikt
                            Launch = new QueryString()
                        {
                            { "action", "openBobApp"}
                        }.ToString()
                        };

                        //De toast notification maken
                        var toast = new ToastNotification(toastContent.GetXml());
                        toast.ExpirationTime = DateTime.Now.AddDays(2);//Tijd totdat de notification vanzelf verdwijnt

                        //En uiteindelijk de toast tonen
                        ToastNotificationManager.CreateToastNotifier().Show(toast);

                        break;

                    case GeolocationAccessStatus.Unspecified: //Er is iets vreemds misgelopen
                        Debug.WriteLine("Geen locatie: Unspecified");
                        break;

                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error in LoginVM, LocatieToestemmingVragen: " + ex.Message);
            }
        }
예제 #12
0
        public static void Do(string title, string b1, string b2)
        {
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                },
            };

            if (b1 != "")
            {
                visual.BodyTextLine1 = new ToastText()
                {
                    Text = b1
                };
            }

            if (b2 != "")
            {
                visual.BodyTextLine2 = new ToastText()
                {
                    Text = b2
                };
            }

            ToastContent toastContent = new ToastContent()
            {
                Visual = visual,
                Audio = null

            };

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

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        public void Test_Toast_XML_Visual_SevenImages()
        {
            try
            {
                var visual = new ToastVisual()
                {
                    InlineImages =
                    {
                        new ToastImage(),
                        new ToastImage(),
                        new ToastImage(),
                        new ToastImage(),
                        new ToastImage(),
                        new ToastImage(),
                        new ToastImage()
                    }
                };
            }

            catch { return; }

            Assert.Fail("Exception should have been thrown, since adding more than 6 images is not allowed.");
        }
        public void Test_Toast_XML_Visual_TwoImages()
        {
            var visual = new ToastVisual()
            {
                InlineImages =
                {
                    new ToastImage()
                    {
                        Source = new ToastImageSource("http://msn.com/image.jpg")
                        {
                            AddImageQuery = true,
                            Alt = "alternate"
                        }
                    },

                    new ToastImage()
                    {
                        Source = new ToastImageSource("Assets/img2.jpg")
                    }
                }
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><image src='http://msn.com/image.jpg' addImageQuery='true' alt='alternate'/><image src='Assets/img2.jpg'/></binding></visual>", visual);
        }
        private static async void BackgroundProcessRegisterer()
        {
            const string taskName = "ActionCenterToastMaker";

            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            if (backgroundAccessStatus != BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity &&
                backgroundAccessStatus != BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) return;
            if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == taskName))
            {
                return;
            }

            var taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = taskName;
            taskBuilder.TaskEntryPoint = typeof(BackgroundProcesses.ActionCenterToastMaker).FullName;
            taskBuilder.SetTrigger(new TimeTrigger(500, false));

            var register = taskBuilder.Register();

            //Create a new Toast immediately after user toggles the switch     
            const string title = "Click on time of Emergency!";

            var visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                }

            };

            const int conversationId = 177777;

            var toastContent = new ToastContent()
            {
                Visual = visual,
                Launch = new QueryString()
                {
                    {"conversationId", conversationId.ToString()}
                }.ToString()
            };

            var toast = new ToastNotification(toastContent.GetXml())
            {
                ExpirationTime = DateTime.Now.AddHours(5),
                SuppressPopup = true,
                Tag = "Friends"
            };
            if (ToastNotificationManager.History != null)
            {
                ToastNotificationManager.History.Remove("Friends");
            }

            ToastNotificationManager.CreateToastNotifier().Show(toast);


        }
        public void Test_Toast_XML_Visual_BodyTextLine2_All()
        {
            var visual = new ToastVisual()
            {
                BodyTextLine2 = new ToastText()
                {
                    Text = "The second line of body text",
                    Language = "en-US"
                }
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text/><text/><text lang='en-US'>The second line of body text</text></binding></visual>", visual);
        }
        /// <summary>
        /// Updates all of the notifications based on the message list.
        /// </summary>
        /// <param name="newMessages"></param>
        public async void UpdateNotifications(List<Message> newMessages)
        {
            bool updateSliently = !m_baconMan.IsBackgroundTask;

            // Check if we are disabled.
            if (!IsEnabled || !m_baconMan.UserMan.IsUserSignedIn)
            {
                // Clear things out
                ToastNotificationManager.History.Clear();
                // Clear the tile
                BadgeNumericNotificationContent content = new BadgeNumericNotificationContent();
                content.Number = 0;
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(new BadgeNotification(content.GetXml()));
                return;
            }

            try
            {
                // Get the current state of the messages.
                IReadOnlyList<ToastNotification> history = ToastNotificationManager.History.GetHistory();

                // We need to keep track of anything new to send to the band.
                List<Tuple<string, string, string>> newNotifications = new List<Tuple<string, string, string>>();

                // We also need to keep track of how many are unread so we can updates our badge.
                int unreadCount = 0;

                if (NotificationType == 0)
                {
                    // For help look here.
                    // http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/09/quickstart-sending-a-local-toast-notification-and-handling-activations-from-it-windows-10.aspx

                    // We need to keep track of what notifications we should have so we can remove ones we don't need.
                    Dictionary<string, bool> unReadMessages = new Dictionary<string, bool>();

                    foreach (Message message in newMessages.Reverse<Message>())
                    {
                        // If it is new
                        if (message.IsNew)
                        {
                            unreadCount++;

                            // Add the message to our list
                            unReadMessages.Add(message.Id, true);

                            // Check if it is already been reported but dismissed from the UI
                            if (ShownMessageNotifications.ContainsKey(message.Id))
                            {
                                continue;
                            }

                            // If not add that we are showing it.
                            ShownMessageNotifications[message.Id] = true;

                            // Check if it is already in the UI
                            foreach (ToastNotification oldToast in history)
                            {
                                if (oldToast.Tag.Equals(message.Id))
                                {
                                    continue;
                                }
                            }

                            // Get the post title.
                            string title = "";
                            if (message.WasComment)
                            {
                                string subject = message.Subject;
                                if (subject.Length > 0)
                                {
                                    subject = subject.Substring(0, 1).ToUpper() + subject.Substring(1);
                                }
                                title = subject + " from " + message.Author;
                            }
                            else
                            {
                                title = message.Subject;
                            }

                            // Get the body
                            string body = message.Body;

                            // Add the notification to our list
                            newNotifications.Add(new Tuple<string, string, string>(title, body, message.Id));
                        }
                    }

                    // Make sure that all of the messages in our history are still unread
                    // if not remove them.
                    for(int i = 0; i < history.Count; i++)
                    {
                        if(!unReadMessages.ContainsKey(history[i].Tag))
                        {
                            // This message isn't unread any longer.
                            ToastNotificationManager.History.Remove(history[i].Tag);
                        }
                    }

                    // Save any settings we changed
                    SaveSettings();
                }
                else
                {
                    // Count how many are unread
                    foreach (Message message in newMessages)
                    {
                        if (message.IsNew)
                        {
                            unreadCount++;
                        }
                    }

                    // If we have a different unread count now show the notification.
                    if(LastKnownUnreadCount != unreadCount)
                    {
                        // Update the notification.
                        LastKnownUnreadCount = unreadCount;

                        // Clear anything we have in the notification center already.
                        ToastNotificationManager.History.Clear();

                        if (unreadCount != 0)
                        {
                            newNotifications.Add(new Tuple<string, string, string>($"You have {unreadCount} new inbox message" + (unreadCount == 1 ? "." : "s."), "", "totalCount"));
                        }
                    }              
                }

                // For every notification, show it.
                bool hasShownNote = false;
                foreach(Tuple<string, string, string> newNote in newNotifications)
                {
                    // Make the visual
                    ToastVisual visual = new ToastVisual();
                    visual.TitleText = new ToastText() { Text = newNote.Item1 };
                    if(!String.IsNullOrWhiteSpace(newNote.Item2))
                    {
                        visual.BodyTextLine1 = new ToastText() { Text = newNote.Item2 };
                    }

                    // Make the toast content
                    ToastContent toastContent = new ToastContent();
                    toastContent.Visual = visual;
                    toastContent.Launch = c_messageInboxOpenArgument;
                    toastContent.ActivationType = ToastActivationType.Foreground;
                    toastContent.Duration = ToastDuration.Short;

                    var toast = new ToastNotification(toastContent.GetXml());
                    toast.Tag = newNote.Item3;

                    // Only show if we should and this is the first message to show.
                    toast.SuppressPopup = hasShownNote || updateSliently || AddToNotificationCenterSilently;
                    ToastNotificationManager.CreateToastNotifier().Show(toast);

                    // Mark that we have shown one.
                    hasShownNote = true;
                }

                // Make sure the main tile is an iconic tile.
                m_baconMan.TileMan.EnsureMainTileIsIconic();

                // Update the badge
                BadgeNumericNotificationContent content = new BadgeNumericNotificationContent();
                content.Number = (uint)unreadCount;
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(new BadgeNotification(content.GetXml()));

                // Update the band if we have one.
                if(!updateSliently)
                {
                    await m_baconMan.BackgroundMan.BandMan.UpdateInboxMessages(newNotifications, newMessages);
                }

                // If all was successful update the last time we updated
                LastUpdateTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "messageUpdaterFailed", ex);
                m_baconMan.MessageMan.DebugDia("failed to update message notifications", ex);
            }

            // When we are done release the deferral
            ReleaseDeferal();
        }
예제 #18
0
		private async static void ShowToast(int checkInId, string eventName)
		{
			// In a real app, these would be initialized with actual data
			string title = "Check-in completed!";
			string content = "You checked-in to " + eventName;
			string image = "http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-81-permanent/2727.happycanyon1_5B00_1_5D00_.jpg";
			string logo = "ms-appdata:///local/StoreLogo.scale-100.png";
			//int conversationId = 384928;

			// Construct the visuals of the toast
			ToastVisual visual = new ToastVisual()
			{
				TitleText = new ToastText()
				{
					Text = title,
				},
				BodyTextLine1 = new ToastText()
				{
					Text = content
				},

				InlineImages =
				{
					new ToastImage()
					{
						Source = new ToastImageSource(image)
					}
				},

				AppLogoOverride = new ToastAppLogo()
				{
					Source = new ToastImageSource(logo),
					Crop = ToastImageCrop.Circle
				}
			};

			// Construct the actions for the toast (inputs and buttons)
			//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",

   //                     // Reference the text box's ID in order to
   //                     // place this button next to the text box
   //                     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())
			//	}
			//};


			// Now we can construct the final toast content
			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()
			};


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


			// And then send the toast
			ToastNotificationManager.CreateToastNotifier().Show(notification);
		}
        public void Test_Toast_XML_Visual_SixImages()
        {
            var visual = new ToastVisual()
            {
                InlineImages =
                {
                    new ToastImage() { Source = new ToastImageSource("Assets/img1.jpg") },
                    new ToastImage() { Source = new ToastImageSource("Assets/img2.jpg") },
                    new ToastImage() { Source = new ToastImageSource("Assets/img3.jpg") },
                    new ToastImage() { Source = new ToastImageSource("Assets/img4.jpg") },
                    new ToastImage() { Source = new ToastImageSource("Assets/img5.jpg") },
                    new ToastImage() { Source = new ToastImageSource("Assets/img6.jpg") }
                }
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><image src='Assets/img1.jpg'/><image src='Assets/img2.jpg'/><image src='Assets/img3.jpg'/><image src='Assets/img4.jpg'/><image src='Assets/img5.jpg'/><image src='Assets/img6.jpg'/></binding></visual>", visual);
        }
        public void Test_Toast_XML_Visual_AddImageQuery_True()
        {
            var visual = new ToastVisual()
            {
                AddImageQuery = true
            };

            AssertVisualPayload(@"<visual addImageQuery=""true""><binding template=""ToastGeneric""/></visual>", visual);
        }
 private static void AssertVisualPayload(string expectedVisualXml, ToastVisual visual)
 {
     AssertPayload("<toast>" + expectedVisualXml + "</toast>", new ToastContent()
     {
         Visual = visual
     });
 }
        public void Test_Toast_XML_Visual_Version_Value()
        {
            var visual = new ToastVisual()
            {
                Version = 3
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""/></visual>", visual);
        }
        private async void ReminderRegister()
        {

            const string title = "Are you there?";
            const string content = "Click the button below if you are alright!";

            var visual = new ToastVisual
            {
                TitleText = new ToastText
                {
                    Text = title
                },

                BodyTextLine1 = new ToastText
                {
                    Text = content
                }

            };

            var actions = new ToastActionsCustom
            {
                Buttons =
                {
                    new ToastButton("Dismiss", new QueryString
                    {
                        {"action", "dismiss"}
                    }.ToString())
                    {
                        ActivationType = ToastActivationType.Background
                    }
                }

            };

            const int conversationId = 177777;

            var toastContent = new ToastContent
            {
                Visual = visual,
                Actions = actions,
                Scenario = ToastScenario.Reminder,
                Launch = new QueryString
                {
                    {"action","viewConversation" },
                    {"conversationId", conversationId.ToString()}
                }.ToString()
            };

            if (Time > DateTime.Now.TimeOfDay)
            {
                try
                {
                    var scheduled = new ScheduledToastNotification(toastContent.GetXml(),
                        new DateTimeOffset(DateTime.Today + Time)) {Id = "scheduledtoast"};

                    var timeDifference = Time - DateTime.Now.TimeOfDay;
                    timeDifference = timeDifference.Add(new TimeSpan(0, 0, 15, 0));
                    const string taskName = "Reminder";
                    var taskBuilder = new BackgroundTaskBuilder();
                    taskBuilder.Name = taskName;
                    taskBuilder.TaskEntryPoint = typeof (Reminder).FullName;
                    taskBuilder.SetTrigger(new TimeTrigger(Convert.ToUInt32(timeDifference.Minutes.ToString()), true));

                    var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                    foreach (var task in BackgroundTaskRegistration.AllTasks.Where(task => task.Value.Name == taskName))
                    {
                        task.Value.Unregister(true);
                    }
                    taskBuilder.Register();
                    ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduled);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }
            else
            {
                try
                {
                    var scheduled = new ScheduledToastNotification(toastContent.GetXml(),
                        new DateTimeOffset(DateTime.Today.AddDays(1) + Time))
                    {Id = "scheduledtoast"};
                    
                    var timeDifference = Time.Add(new TimeSpan(1,0,0,0)) ;
                    timeDifference = timeDifference.Add(new TimeSpan(0, 0, 15, 0));
                    const string taskName = "Reminder";
                    var taskBuilder = new BackgroundTaskBuilder();
                    taskBuilder.Name = taskName;
                    taskBuilder.TaskEntryPoint = typeof (Reminder).FullName;
                    taskBuilder.SetTrigger(new TimeTrigger(Convert.ToUInt32(timeDifference.Minutes.ToString()), true));

                    var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                    foreach (var task in BackgroundTaskRegistration.AllTasks.Where(task => task.Value.Name == taskName))
                    {
                        task.Value.Unregister(true);
                    }

                    ToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduled);
                    taskBuilder.Register();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }
            
        }
        public void Test_Toast_XML_Visual_BodyTextLine2_Defaults()
        {
            var visual = new ToastVisual()
            {
                BodyTextLine2 = new ToastText()
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text/><text/><text/></binding></visual>", visual);
        }
예제 #25
0
        private async void downloadbutton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Tracker myTracker = EasyTracker.GetTracker();
              myTracker.SendEvent("Downloads", "Download Button Clicked", "Download Attempted",1);
                Uri source = new Uri("http://convertmyurl.net/?url=" + urltext.Text.Trim());
                ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                StorageFolder folder;
                string pathname;
                object v = localSettings.Values["pathkey"];
                if (v != null)
                {
                    pathname = v.ToString();
                    try {
                        folder = await StorageFolder.GetFolderFromPathAsync(pathname);
                    }
                    catch(FileNotFoundException ex)
                    {
                        folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("PDF Me", CreationCollisionOption.OpenIfExists);
                    }
                }
                else {
                     folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("PDF Me", CreationCollisionOption.OpenIfExists);
                    
                }
                string filename;

                object value = localSettings.Values["filekey"];
                if (value != null)
                {
                   filename  = localSettings.Values["filekey"].ToString();
                    Debug.WriteLine("New filename");
                }
                else
                {
                    filename = "PDF Me.pdf";
                    Debug.WriteLine("Default filename");
                }
                char[] a = new char[25];
                StorageFile destinationFile;
                if (browserweb.DocumentTitle.Length > 60)
                {
                    destinationFile = await folder.CreateFileAsync(
                 "PDF Me.pdf", CreationCollisionOption.GenerateUniqueName);
                }
                else
                {
                    destinationFile = await folder.CreateFileAsync(
                browserweb.DocumentTitle+".pdf", CreationCollisionOption.GenerateUniqueName);
                }
                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                downloading.Visibility = Visibility.Visible;
                downloadprogress.Visibility = Visibility.Visible;
                downloadprogress.IsActive = true;
                await download.StartAsync();


                int progress = (int)(100 * (download.Progress.BytesReceived / (double)download.Progress.TotalBytesToReceive));
                if (progress >= 100)
                {
                    myTracker.SendEvent("Downloads", "Download Finished", "Download Successfull", 2);
                    downloading.Visibility = Visibility.Collapsed;
                    downloading.Text = "Downloading: ";
                    downloadprogress.Visibility = Visibility.Collapsed;
                    BasicProperties basic = await download.ResultFile.GetBasicPropertiesAsync();
                    string size;
                        double siz = basic.Size;
               //     ulong mb = ulong.Parse(1000000);
                    if (siz > 1000000)
                    {
                        double s = siz / 1000000;
                        size = s.ToString() + "MB";
                    }
                    else
                    {
                        double s = siz / 1000;
                        
                        size = s.ToString() + "KB";
                    }

                    DatabaseController.AddDownload(destinationFile.Name, download.ResultFile.Path,download.ResultFile.DateCreated.DateTime.ToString(),size);
                    AdDuplex.InterstitialAd interstitialAd = new AdDuplex.InterstitialAd("180815");
                    await interstitialAd.LoadAdAsync();
                    /* MessageDialog m = new MessageDialog(destinationFile.Name + " is saved in PDF Me folder.", "Download Completed");
                     m.Commands.Add(new UICommand("Open File", (command) =>
                     {
                          Launcher.LaunchFileAsync(download.ResultFile);
                     }
                     ));

                     m.Commands.Add(new UICommand("Close", (command) =>
                     {

                     }, 0));

                     m.CancelCommandIndex = 0;
                   await  m.ShowAsync();
                   */
                    string title = "Download Successful";
                    string content = destinationFile.Name + " is saved in PDF Me folder.";
                    ToastVisual visual = new ToastVisual()
                    {
                        TitleText = new ToastText()
                        {
                            Text = title
                        },

                        BodyTextLine1 = new ToastText()
                        {
                            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()
                    {


                        Buttons =
    {
        new ToastButton("Open", new QueryString()
        {
            { "action", "open" },
            {"file",destinationFile.Path }

        }.ToString())
        {
            ActivationType = ToastActivationType.Foreground,
           
 
            // Reference the text box's ID in order to
            // place this button next to the text box
            
        },

        new ToastButton("Share", new QueryString()
        {
            { "action", "share" },
              {"file",destinationFile.Path }
        }.ToString())
        {
            ActivationType = ToastActivationType.Foreground
        }

       
    }
                    };
                    // Now we can construct the final toast content
                    ToastContent toastContent = new ToastContent()
                    {
                        Visual = visual,
                        Actions = actions,

                        // Arguments when the user taps body of toast
                        Launch = new QueryString()
{

{ "conversationId", conversationId.ToString() }

}.ToString()
                    };

                    // And create the toast notification
                    var toast = new ToastNotification(toastContent.GetXml());
                    toast.ExpirationTime = DateTime.Now.AddSeconds(10);
                    ToastNotificationManager.CreateToastNotifier().Show(toast);

                    await interstitialAd.LoadAdAsync();
                    await interstitialAd.ShowAdAsync();



                }
                else

                {
                    downloading.Visibility = Visibility.Collapsed;
                    downloadprogress.Visibility = Visibility.Collapsed;
                    BasicProperties basic = await download.ResultFile.GetBasicPropertiesAsync();

                    double siz = basic.Size;
                    if(siz == 0)
                    {
                      await  destinationFile.DeleteAsync();
                        myTracker.SendEvent("Downloads", "Download Failed due to Server Error", null, 3);
                        MessageDialog m = new MessageDialog("Server is down. Try again later","Fatal Error");
                        await   m.ShowAsync();
                    }
                }
                /*
                var authClient = new LiveAuthClient();
                var authResult = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" });
                if (authResult.Session == null)
                {
                    throw new InvalidOperationException("You need to sign in and give consent to the app.");
                }

                var liveConnectClient = new LiveConnectClient(authResult.Session);

                string skyDriveFolder = await CreateDirectoryAsync(liveConnectClient, "PDF Me - Saved PDFs", "me/skydrive");
            */
            }
            catch (Exception ex)
            {
               
                Tracker myTracker = EasyTracker.GetTracker();      // Get a reference to tracker.
                myTracker.SendException(ex.Message, false);
                MessageDialog m = new MessageDialog(ex.ToString());
                m.ShowAsync();
            }
        }
        public void Test_Toast_XML_Visual_Language_Value()
        {
            var visual = new ToastVisual()
            {
                Language = "en-US"
            };

            AssertVisualPayload(@"<visual lang=""en-US""><binding template=""ToastGeneric""/></visual>", visual);
        }
        public void Test_Toast_XML_Visual_AllTexts()
        {
            var visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = "My title"
                },

                BodyTextLine1 = new ToastText()
                {
                    Text = "My body 1"
                },

                BodyTextLine2 = new ToastText()
                {
                    Text = "My body 2"
                }
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text>My title</text><text>My body 1</text><text>My body 2</text></binding></visual>", visual);
        }
        public void Test_Toast_XML_Visual_TitleText_All()
        {
            var visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = "Hi, I am a title",
                    Language = "en-US"
                }
            };

            AssertVisualPayload(@"<visual><binding template=""ToastGeneric""><text lang='en-US'>Hi, I am a title</text></binding></visual>", visual);
        }
        private void ButtonSendToast_Click(object sender, RoutedEventArgs e)
        {
            // In a real app, these would be initialized with actual data
            string title = "Andrew sent you a picture";
            string content = "Check this out, Happy Canyon in Utah!";
            string image = "http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-81-permanent/2727.happycanyon1_5B00_1_5D00_.jpg";
            string logo = "ms-appdata:///local/Andrew.jpg";
            int conversationId = "384928";

            // Construct the visuals of the toast
            ToastVisual visual = new ToastVisual()
            {
                TitleText = new ToastText()
                {
                    Text = title
                },

                BodyTextLine1 = new ToastText()
                {
                    Text = content
                },

                InlineImages =
                {
                    new ToastImage()
                    {
                        Source = new ToastImageSource(image)
                    }
                },

                AppLogoOverride = new ToastAppLogo()
                {
                    Source = new ToastImageSource(logo),
                    Crop = ToastImageCrop.Circle
                }
            };

            // Construct the actions for the toast (inputs and buttons)
            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",

                        // Reference the text box's ID in order to
                        // place this button next to the text box
                        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())
                }
            };


            // Now we can construct the final toast content
            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()
            };


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


            // And then send the toast
            ToastNotificationManager.CreateToastNotifier().Show(notification);
        }
        public void Test_Toast_XML_Visual_BaseUri_Value()
        {
            var visual = new ToastVisual()
            {
                BaseUri = new Uri("http://msn.com")
            };

            AssertVisualPayload(@"<visual baseUri=""http://msn.com/""><binding template=""ToastGeneric""/></visual>", visual);
        }