protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); var deferral = args.TaskInstance.GetDeferral(); // We make a toast notification saying what time it is. var manager = ToastNotificationManager.GetDefault(); var notifier = manager.CreateToastNotifier(); var toastContent = new ToastContent() { Visual = new ToastVisual() { BindingGeneric = new ToastBindingGeneric() { Children = { new AdaptiveText() { Text = $"Toast fired at {DateTime.Now:hh-mm}" } } } } }; notifier.Show(new ToastNotification(toastContent.GetXml())); deferral.Complete(); }
private void Add_Via_Toast_Click(object sender, RoutedEventArgs e) { var toastManager = ToastNotificationManager.GetDefault(); var toastNotifier = toastManager.CreateToastNotifier(); XmlDocument xml = new XmlDocument(); xml.LoadXml(@" <toast> <visual> <binding template='ToastGeneric'> <text>Send an image path to the app</text> </binding> </visual> <actions> <input id='textBox' type='text' placeHolderContent='Type a reply'/> <action content='Send' arguments='action=send' activationType='foreground'/> <action content='Cancel' arguments='dismiss' activationType='system'/> </actions> </toast>"); ToastNotification notification = new ToastNotification(xml); toastNotifier.Show(notification); }
public static void HandlePackageInstallCompletedToast(SuccessMessage m, ToastNotification progressToast) { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362)) { return; } PackageBase package = (PackageBase)m.Context; var builder = new ToastContentBuilder().SetToastScenario(ToastScenario.Reminder) .AddToastActivationInfo($"package/{package.Urn}", ToastActivationType.Foreground) .AddText(package.ShortTitle) .AddText(package.Title + " just got installed."); try { if (package.GetAppIcon().Result is SDK.Images.FileImage image && !image.Uri.IsFile) { builder.AddAppLogoOverride(image.Uri, addImageQuery: false); } } finally { } var notif = new ToastNotification(builder.GetXml()); // Hide progress notification Hide(progressToast); // Show the final notification ToastNotificationManager.GetDefault().CreateToastNotifier().Show(notif); }
private static void Hide(ToastNotification toast) { try { ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(toast); } catch { } }
public void Initializate() { NotificationListener = UserNotificationListener.Current; TileUpdater = TileUpdateManager.CreateTileUpdaterForApplication(); ToastNotificationManagerForUser = ToastNotificationManager.GetDefault(); ToastNotifier = ToastNotificationManager.CreateToastNotifier(); ToastCollectionManager = ToastNotificationManagerForUser.GetToastCollectionManager(); NotificationListener.NotificationChanged += NotificationListener_NotificationChanged; }
public static void HandlePackageDownloadStartedToast(PackageDownloadStartedMessage m, ToastNotification progressToast) { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362)) { return; } ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast); }
public static async void CreateCollection(string name, string option) { string launchArg = "Collection"; string displayName = string.IsNullOrEmpty(option) ? name : name + "::" + option; /*Register Group*/ var workEmailToastCollection = ConvertCollection(displayName, displayName, launchArg); await ToastNotificationManager.GetDefault().GetToastCollectionManager().SaveToastCollectionAsync(workEmailToastCollection); }
private async Task <ToastNotificationHistory> GetCollectionHistoryAsync() { var collectionHistory = await ToastNotificationManager.GetDefault().GetHistoryForToastCollectionIdAsync($"{_sessionService.Id}"); if (collectionHistory == null) { collectionHistory = ToastNotificationManager.History; } return(collectionHistory); }
public static void HandlePackageInstallFailedToast(ErrorMessage m, ToastNotification progressToast) { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362)) { return; } // Hide progress notification Hide(progressToast); // Show the final notification ToastNotificationManager.GetDefault().CreateToastNotifier().Show(GenerateInstallFailureToast((PackageBase)m.Context, m.Exception)); }
public static async Task Send(ToastNotification toast, string id) { try { var notifier = await ToastNotificationManager.GetDefault().GetToastNotifierForToastCollectionIdAsync(id); notifier?.Show(toast); } catch (Exception e) { MessageBox.Show("Notification Error: " + e.ToString()); } }
public static async Task <bool> InstallPackage(Package package, ProductDetails product) { try { // Download the file to the app's temp directory //var client = new System.Net.WebClient(); string filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.Name); //client.DownloadFile(package.Uri, filepath); StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync( package.Name, CreationCollisionOption.ReplaceExisting); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.SuccessToastNotification = GenerateDonwloadSuccessToast(package, product); downloader.FailureToastNotification = GenerateDonwloadFailureToast(package, product); var progressToast = GenerateDonwloadProgressToast(package, product); DownloadOperation download = downloader.CreateDownload(package.Uri, destinationFile); download.RangesDownloaded += (op, args) => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() } }), progressToast.Tag ); }; ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast); await download.StartAsync(); // Clear the progress notif ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast); // Pass the file to App Installer to install it Uri launchUri = new Uri("ms-appinstaller:?source=" + filepath); switch (await Launcher.QueryUriSupportAsync(launchUri, LaunchQuerySupportType.Uri)) { case LaunchQuerySupportStatus.Available: return(await Launcher.LaunchUriAsync(launchUri)); default: return(false); } } catch { return(false); } }
public static void HandlePackageInstallProgressToast(PackageInstallProgressMessage m, ToastNotification progressToast) { if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362)) { return; } ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", m.Progress.ToString() }, { "progressStatus", "Installing..." } }), progressToast.Tag ); }
private async void CreateToastCollection(User user) { try { var displayName = user.GetFullName(); var launchArg = $"session={_sessionService.Id}&user_id={user.Id}"; var icon = new Uri("ms-appx:///Assets/Logos/Square44x44Logo/Square44x44Logo.png"); #if DEBUG displayName += " BETA"; #endif var collection = new ToastCollection($"{_sessionService.Id}", displayName, launchArg, icon); await ToastNotificationManager.GetDefault().GetToastCollectionManager().SaveToastCollectionAsync(collection); } catch { } }
private void ShowToastNotification() { var notificationManager = ToastNotificationManager.GetDefault(); var toastContent = new ToastContent { Visual = new ToastVisual { BindingGeneric = new ToastBindingGeneric { Children = { new AdaptiveText { Text = _input.Text ?? "Hest er best på fest" } } } }, Actions = new ToastActionsCustom { Buttons = { new ToastButton("Ingen protest!", "action=NoProtest") { ActivationType = ToastActivationType.Foreground } } } }; var doc = new Windows.Data.Xml.Dom.XmlDocument(); doc.LoadXml(toastContent.GetContent()); var toast = new ToastNotification(doc); notificationManager.CreateToastNotifier().Show(toast); }
private async void ShowNotification_OnClick(object sender, RoutedEventArgs e) { Task.Run(async() => { var uri = new Uri("ms-appx:///Assets/StoreSolo.png"); var toastCollection = new ToastCollection(ToastCollectionId, "ContosoInc", "Args", uri); await ToastNotificationManager.GetDefault().GetToastCollectionManager().SaveToastCollectionAsync(toastCollection); _toastNotifierManager = await ToastNotificationManager.GetDefault().GetToastNotifierForToastCollectionIdAsync(ToastCollectionId); var toastsHistory = ToastNotificationManager.History.GetHistory().ToList(); foreach (var toast in toastsHistory) { lock (_toastNotifierManager) { _toastNotifierManager.Hide(toast); } } await ShowDownloadNotification("status", 2, "tag"); }); }
public async void Initializate() { NotificationListener = UserNotificationListener.Current; if (await NotificationListener.RequestAccessAsync() == UserNotificationListenerAccessStatus.Allowed) { try { // Crashes windows notification platform //NotificationListener.NotificationChanged += NotificationListener_NotificationChanged; } catch (Exception) { Debug.WriteLine("NotificationListener.NotificationChanged.EventAdd failed.\nWarning: Windows Notification Platform might be unavailable, have you crashed something?"); } } try { TileUpdater = TileUpdateManager.CreateTileUpdaterForApplication(); } catch (Exception) { Debug.WriteLine("TileUpdateManager.CreateTileUpdaterForApplication failed.\nWarning: Windows Notification Platform might be unavailable, have you crashed something?"); } try { ToastNotificationManagerForUser = ToastNotificationManager.GetDefault(); try { ToastCollectionManager = ToastNotificationManagerForUser.GetToastCollectionManager(); } catch (Exception) { Debug.WriteLine("ToastNotificationManagerForUser.GetToastCollectionManager failed.\nWarning: Windows Notification Platform might be unavailable, have you crashed something?"); } } catch (Exception) { Debug.WriteLine("ToastNotificationManager.GetDefault failed.\nWarning: Windows Notification Platform might be unavailable, have you crashed something?"); } try { ToastNotifier = ToastNotificationManager.CreateToastNotifier(); } catch (Exception) { Debug.WriteLine("ToastNotificationManager.CreateToastNotifier failed.\nWarning: Windows Notification Platform might be unavailable, have you crashed something?"); } }
public static async Task <Tuple <StorageFile, ToastNotification> > DownloadPackage(PackageInstance package, ProductDetails product, bool hideProgressToastWhenDone = true) { // Download the file to the app's temp directory //var client = new System.Net.WebClient(); string filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.PackageMoniker); Debug.WriteLine(filepath); //client.DownloadFile(package.Uri, filepath); StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync( package.PackageMoniker, CreationCollisionOption.ReplaceExisting); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.FailureToastNotification = GenerateDownloadFailureToast(package, product); var progressToast = GenerateProgressToast(package, product); Debug.WriteLine(package.PackageUri.AbsoluteUri); DownloadOperation download = downloader.CreateDownload(package.PackageUri, destinationFile); download.RangesDownloaded += (op, args) => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() }, { "progressStatus", "Downloading..." } }), progressToast.Tag ); }; ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast); await download.StartAsync(); if (hideProgressToastWhenDone) { ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast); } string extension = ""; string contentTypeFilepath = filepath + "_[Content_Types].xml"; using (var archive = ZipFile.OpenRead(filepath)) { var entry = archive.GetEntry("[Content_Types].xml"); entry.ExtractToFile(contentTypeFilepath, true); var ctypesXml = XDocument.Load(contentTypeFilepath); var defaults = ctypesXml.Root.Elements().Where(e => e.Name.LocalName == "Default"); if (defaults.Any(d => d.Attribute("Extension").Value == "msix")) { // Package contains one or more MSIX packages extension += ".msix"; } else if (defaults.Any(d => d.Attribute("Extension").Value == "appx")) { // Package contains one or more MSIX packages extension += ".appx"; } if (defaults.Any(defaults => defaults.Attribute("ContentType").Value == "application/vnd.ms-appx.bundlemanifest+xml")) { // Package is a bundle extension += "bundle"; } } if (File.Exists(contentTypeFilepath)) { File.Delete(contentTypeFilepath); } if (extension != "") { await destinationFile.RenameAsync(destinationFile.Name + extension, NameCollisionOption.ReplaceExisting); } return((destinationFile, progressToast).ToTuple()); }
public static async Task <Tuple <StorageFile, ToastNotification> > DownloadPackage(PackageInstance package, ProductDetails product, bool hideProgressToastWhenDone = true, string filepath = null) { // Download the file to the app's temp directory if (filepath == null) { filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.PackageMoniker); } Debug.WriteLine(filepath); StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync( package.PackageMoniker, CreationCollisionOption.ReplaceExisting); BackgroundDownloader downloader = new BackgroundDownloader(); downloader.FailureToastNotification = GenerateDownloadFailureToast(package, product); var progressToast = GenerateProgressToast(package, product); Debug.WriteLine(package.PackageUri.AbsoluteUri); DownloadOperation download = downloader.CreateDownload(package.PackageUri, destinationFile); download.RangesDownloaded += (op, args) => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() }, { "progressStatus", "Downloading..." } }), progressToast.Tag ); }; ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast); await download.StartAsync(); if (hideProgressToastWhenDone) { ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast); } string extension = ""; string contentTypeFilepath = filepath + "_[Content_Types].xml"; using (var stream = await destinationFile.OpenStreamForReadAsync()) { var bytes = new byte[4]; stream.Read(bytes, 0, 4); uint magicNumber = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]); switch (magicNumber) { // ZIP /// Typical [not empty or spanned] ZIP archive case 0x504B0304: using (var archive = ZipFile.OpenRead(filepath)) { var entry = archive.GetEntry("[Content_Types].xml"); entry.ExtractToFile(contentTypeFilepath, true); var ctypesXml = XDocument.Load(contentTypeFilepath); var defaults = ctypesXml.Root.Elements().Where(e => e.Name.LocalName == "Default"); if (defaults.Any(d => d.Attribute("Extension").Value == "msix")) { // Package contains one or more MSIX packages extension += ".msix"; } else if (defaults.Any(d => d.Attribute("Extension").Value == "appx")) { // Package contains one or more MSIX packages extension += ".appx"; } if (defaults.Any(defaults => defaults.Attribute("ContentType").Value == "application/vnd.ms-appx.bundlemanifest+xml")) { // Package is a bundle extension += "bundle"; } if (extension == string.Empty) { // We're not sure exactly what kind of package it is, but it's definitely // a package archive. Even if it's not actually an appxbundle, it will // likely still work. extension = ".appxbundle"; } } break; // EMSIX, EAAPX, EMSIXBUNDLE, EAPPXBUNDLE /// An encrypted installer [bundle]? case 0x45584248: // This means the downloaded file wasn't a zip archive. // Some inspection of a hex dump of the file leads me to believe that this means // the installer is encrypted. There's probably nothing that can be done about this, // but since it's a known case, let's leave this here. extension = ".eappxbundle"; break; } } if (File.Exists(contentTypeFilepath)) { File.Delete(contentTypeFilepath); } if (extension != string.Empty) { await destinationFile.RenameAsync(destinationFile.Name + extension, NameCollisionOption.ReplaceExisting); } return((destinationFile, progressToast).ToTuple()); }
public static async Task <bool> InstallPackage(PackageInstance package, ProductDetails product, bool?useAppInstaller = null) { ToastNotification finalNotif = GenerateInstallSuccessToast(package, product); bool isSuccess = true; try { (await DownloadPackage(package, product, false)).Deconstruct(out var installer, out var progressToast); PackageManager pkgManager = new PackageManager(); Progress <DeploymentProgress> progressCallback = new Progress <DeploymentProgress>(prog => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", (prog.percentage / 100).ToString() }, { "progressStatus", "Installing..." } }), progressToast.Tag ); }); if (Settings.Default.UseAppInstaller || (useAppInstaller.HasValue && useAppInstaller.Value)) { // Pass the file to App Installer to install it Uri launchUri = new Uri("ms-appinstaller:?source=" + installer.Path); switch (await Launcher.QueryUriSupportAsync(launchUri, LaunchQuerySupportType.Uri)) { case LaunchQuerySupportStatus.Available: isSuccess = await Launcher.LaunchUriAsync(launchUri); if (!isSuccess) { finalNotif = GenerateInstallFailureToast(package, product, new Exception("Failed to launch App Installer.")); } break; case LaunchQuerySupportStatus.AppNotInstalled: finalNotif = GenerateInstallFailureToast(package, product, new Exception("App Installer is not available on this device.")); isSuccess = false; break; case LaunchQuerySupportStatus.AppUnavailable: finalNotif = GenerateInstallFailureToast(package, product, new Exception("App Installer is not available right now, try again later.")); isSuccess = false; break; case LaunchQuerySupportStatus.Unknown: default: finalNotif = GenerateInstallFailureToast(package, product, new Exception("An unknown error occured.")); isSuccess = false; break; } } else { // Attempt to install the downloaded package var result = await pkgManager.AddPackageByUriAsync( new Uri(installer.Path), new AddPackageOptions() { ForceAppShutdown = true } ).AsTask(progressCallback); if (result.IsRegistered) { finalNotif = GenerateInstallSuccessToast(package, product); } else { finalNotif = GenerateInstallFailureToast(package, product, result.ExtendedErrorCode); } isSuccess = result.IsRegistered; await installer.DeleteAsync(); } // Hide progress notification ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast); // Show the final notification ToastNotificationManager.GetDefault().CreateToastNotifier().Show(finalNotif); return(true); } catch (Exception ex) { ToastNotificationManager.GetDefault().CreateToastNotifier().Show(GenerateInstallFailureToast(package, product, ex)); return(false); } }
public static async Task <bool> InstallPackage(Package package, ProductDetails product) { try { // Download the file to the app's temp directory //var client = new System.Net.WebClient(); string filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.Name); //client.DownloadFile(package.Uri, filepath); StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync( package.Name, CreationCollisionOption.ReplaceExisting); BackgroundDownloader downloader = new BackgroundDownloader(); //downloader.SuccessToastNotification = GenerateDownloadSuccessToast(package, product); downloader.FailureToastNotification = GenerateDownloadFailureToast(package, product); var progressToast = GenerateProgressToast(package, product); DownloadOperation download = downloader.CreateDownload(package.Uri, destinationFile); download.RangesDownloaded += (op, args) => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() }, { "progressStatus", "Downloading..." } }), progressToast.Tag ); }; ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast); await download.StartAsync(); PackageManager pkgManager = new PackageManager(); Progress <DeploymentProgress> progressCallback = new Progress <DeploymentProgress>(prog => { ToastNotificationManager.GetDefault().CreateToastNotifier().Update( new NotificationData(new Dictionary <string, string>() { { "progressValue", (prog.percentage / 100).ToString() }, { "progressStatus", "Installing..." } }), progressToast.Tag ); }); // Attempt to install the downloaded package var result = await pkgManager.AddPackageAsync(new Uri(filepath), new Uri[] { }, DeploymentOptions.ForceTargetApplicationShutdown).AsTask(progressCallback); if (result.IsRegistered) { // Remove the progress notifcation ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast); // Show the success notification ToastNotificationManager.GetDefault().CreateToastNotifier().Show(GenerateInstallSuccessToast(package, product)); return(true); } else { return(false); } // Pass the file to App Installer to install it //Uri launchUri = new Uri("ms-appinstaller:?source=" + filepath); //switch (await Launcher.QueryUriSupportAsync(launchUri, LaunchQuerySupportType.Uri)) //{ // case LaunchQuerySupportStatus.Available: // return await Launcher.LaunchUriAsync(launchUri); // default: // return false; //} } catch { return(false); } }