Created
June 3, 2022 13:25
-
-
Save emoacht/5f8e4d210c45a26b0c3bf0d1b9fd2b89 to your computer and use it in GitHub Desktop.
Update package by Windows.Services.Store API on .NET 5.0.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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