Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created June 3, 2022 13:25
Show Gist options
  • Save emoacht/5f8e4d210c45a26b0c3bf0d1b9fd2b89 to your computer and use it in GitHub Desktop.
Save emoacht/5f8e4d210c45a26b0c3bf0d1b9fd2b89 to your computer and use it in GitHub Desktop.
Update package by Windows.Services.Store API on .NET 5.0.
using System;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using Windows.Services.Store;
using WinRT.Interop;
internal static class StoreHelper
{
/// <summary>
/// Checks if updated packages are available.
/// </summary>
/// <returns>True if available</returns>
/// <remarks>
/// If the packages are installed locally or published but as Package flights, this method
/// will not work correctly.
/// </remarks>
public static async Task<bool> CheckUpdateAsync()
{
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
var context = StoreContext.GetDefault();
try
{
var updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();
return (updates.Count > 0);
}
catch
{
return false;
}
}
/// <summary>
/// Proceeds to download and install updated packages.
/// </summary>
/// <param name="window">Owner window</param>
/// <returns>True if successfully finished downloading and installing</returns>
public static async Task<bool> ProceedUpdateAsync(Window window)
{
if (window is null)
throw new ArgumentNullException(nameof(window));
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
var context = StoreContext.GetDefault();
try
{
var updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();
if (updates.Count == 0)
return false;
SetOwnerWindow(context, window);
var result = await context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates);
return (result.OverallState == StorePackageUpdateState.Completed);
}
catch
{
return false;
}
}
private static void SetOwnerWindow(StoreContext context, Window window)
{
var handle = new WindowInteropHelper(window).Handle;
InitializeWithWindow.Initialize(context, handle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment