Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
#nullable enable
Microsoft.Testing.Extensions.PackagedApp.PackageDeployer
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.FullName.get -> string!
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.InstalledPath.get -> string!
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.IsDevelopmentMode.get -> bool
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.RegisteredPackageInfo(string! fullName, string! installedPath, bool isDevelopmentMode) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.RegisterAsync(string! manifestPath, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task!>! registerPackage, System.Func<System.Collections.Generic.IReadOnlyList<Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo!>!>! findRegisteredPackages, System.Func<string!, System.Threading.CancellationToken, System.Threading.Tasks.Task!>! removeDevelopmentPackage, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ Microsoft.Testing.Extensions.PackagedApp.ActivatedAppTestHostHandle.Terminate()
Microsoft.Testing.Extensions.PackagedApp.ActivatedAppTestHostHandle.WaitForExitAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
Microsoft.Testing.Extensions.PackagedApp.Interop.ApplicationActivationManager
static Microsoft.Testing.Extensions.PackagedApp.Interop.ApplicationActivationManager.ActivateApplication(string! appUserModelId, string? arguments) -> uint
Microsoft.Testing.Extensions.PackagedApp.PackageDeployer
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.Activate(string! appUserModelId, string? activationArguments) -> uint
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.RegisterAsync(string! manifestPath, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ It is the consumer of the platform's `ITestHostLauncher` extension point for Win
- **Packaged AUMID activation** (Windows build): a packaged (MSIX) layout is registered in place with the `PackageManager` and the app is activated by AUMID via `IApplicationActivationManager`. `packagedClassicApp`/`win32App` hosts receive the platform-prepared command line through `argv`, including when their trust level is `appContainer`. `windowsApp`/UWP hosts receive one opaque launch string and restore the exact logical argument array through `PackagedAppExtensions.GetTestApplicationArguments(args.Arguments)` in `Application.OnLaunched` (see [#10485](https://github.com/microsoft/testfx/issues/10485)). Registering an unsigned build-output layout requires Developer Mode (or sideloading). The plain `net8.0`/`net9.0` build rejects a packaged layout with an actionable error pointing at the Windows TFM.
- **Deploy + launch loose layout** (opt-in): a non-packaged app — one without an `AppxManifest.xml` — is deployed to a deployment directory and the produced executable is launched from there.

## Switching packaged build layouts

Before activation, the launcher verifies that the current user's main package registration points to the directory containing the requested `AppxManifest.xml`. Windows can report registration success while retaining a different layout with the same package identity and version. In that case, the launcher removes only the stale **development registration**, using `PreserveApplicationData`, and registers the requested layout again. Repeated runs from the same layout do not remove its registration.

If the conflicting package is not a development registration, or the requested location still cannot be registered, the launcher reports an error instead of activating another build. A failed replacement can leave the package unregistered, but its application data is retained; resolve the reported deployment error and retry. Callers do not need to uninstall their app or change its version for each build.

## When the launcher takes over

Registering an *enabled* test host launcher switches the run to the test host controller (process restart) model, because a launcher only has an effect when an out-of-process test host is started. To avoid charging that cost to apps that do not need it, the launcher enables itself only when it has real work to do:
Expand Down
146 changes: 115 additions & 31 deletions src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackageDeployer.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,40 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if PACKAGEDAPP_WINRT
using Microsoft.Testing.Extensions.PackagedApp.Resources;

#if PACKAGEDAPP_WINRT
using Microsoft.Testing.Extensions.PackagedApp.Interop;
using Microsoft.Testing.Extensions.PackagedApp.Resources;

using Windows.Management.Deployment;
#endif

namespace Microsoft.Testing.Extensions.PackagedApp;

/// <summary>
/// Registers a packaged (MSIX) loose layout with the OS and activates it by Application User Model ID,
/// using only public, redistributable Windows APIs — the <see cref="PackageManager"/> WinRT class for
/// registration and <see cref="ApplicationActivationManager"/> for activation. This is the equivalent
/// using only public, redistributable Windows APIs — the <c>PackageManager</c> WinRT class for
/// registration and <c>ApplicationActivationManager</c> for activation. This is the equivalent
/// of the Visual-Studio-internal deployment components VSTest relies on, implemented without them.
/// </summary>
[SupportedOSPlatform("windows10.0.19041.0")]
internal static class PackageDeployer
{
#if PACKAGEDAPP_WINRT
/// <summary>
/// Registers the loose layout described by <paramref name="manifestPath"/> in place (no copy) and
/// prepares its package-owned storage before any activation handoffs are written.
/// verifies its registered location before any activation handoffs are written.
/// </summary>
/// <param name="manifestPath">The full path to the layout's <c>AppxManifest.xml</c>.</param>
/// <param name="cancellationToken">A token to observe while registering.</param>
public static async Task RegisterAsync(
[SupportedOSPlatform("windows10.0.19041.0")]
public static Task RegisterAsync(
string manifestPath,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var packageManager = new PackageManager();
string packageFamilyName = AppxManifestInfo.ReadFromManifest(manifestPath).PackageFamilyName;
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved

// DeveloperMode registers the unsigned build-output layout in place. It requires Developer Mode
// (or sideloading) to be enabled on the machine, exactly like 'Add-AppxPackage -Register'.
Expand All @@ -40,13 +43,98 @@ public static async Task RegisterAsync(
DeveloperMode = true,
};

DeploymentResult result;
return RegisterAsync(
manifestPath,
async token =>
{
DeploymentResult result = await packageManager
.RegisterPackageByUriAsync(new Uri(manifestPath), options)
.AsTask(token)
.ConfigureAwait(false);

// IsRegistered is authoritative for registration; ExtendedErrorCode can be informational.
if (!result.IsRegistered)
{
throw new InvalidOperationException(result.ErrorText, result.ExtendedErrorCode);
}
},
() => packageManager
.FindPackagesForUserWithPackageTypes(string.Empty, packageFamilyName, PackageTypes.Main)
.Select(static package => new RegisteredPackageInfo(package.Id.FullName, package.InstalledPath, package.IsDevelopmentMode))
.ToArray(),
async (packageFullName, token) =>
{
DeploymentResult result = await packageManager
.RemovePackageAsync(packageFullName, RemovalOptions.PreserveApplicationData)
.AsTask(token)
.ConfigureAwait(false);

if (result.ExtendedErrorCode is { HResult: < 0 })
{
throw new InvalidOperationException(result.ErrorText, result.ExtendedErrorCode);
}
},
cancellationToken);
}

/// <summary>Activates a registered packaged app and returns its process id.</summary>
[SupportedOSPlatform("windows10.0.19041.0")]
public static uint Activate(string appUserModelId, string? activationArguments)
=> ApplicationActivationManager.ActivateApplication(appUserModelId, activationArguments);
#endif

internal static async Task RegisterAsync(
string manifestPath,
Func<CancellationToken, Task> registerPackage,
Func<IReadOnlyList<RegisteredPackageInfo>> findRegisteredPackages,
Func<string, CancellationToken, Task> removeDevelopmentPackage,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

try
{
result = await packageManager
.RegisterPackageByUriAsync(new Uri(manifestPath), options)
.AsTask(cancellationToken)
.ConfigureAwait(false);
string layoutDirectory = Path.GetDirectoryName(Path.GetFullPath(manifestPath))!;

await registerPackage(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
IReadOnlyList<RegisteredPackageInfo> packages = findRegisteredPackages();

if (!IsRegisteredFromLayout(packages, layoutDirectory))
{
if (packages.Count != 1)
{
throw CreateLocationMismatchException(layoutDirectory, packages);
}

RegisteredPackageInfo previousPackage = packages[0];
if (!previousPackage.IsDevelopmentMode)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
ExtensionResources.PackagedAppRegistrationNotDevelopment,
previousPackage.FullName,
previousPackage.InstalledPath,
layoutDirectory));
}

// A successful same-version registration can retain the old layout. Only development
// registrations support removal with PreserveApplicationData; never uninstall a retail app.
cancellationToken.ThrowIfCancellationRequested();
await removeDevelopmentPackage(previousPackage.FullName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
await registerPackage(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();

packages = findRegisteredPackages();
if (!IsRegisteredFromLayout(packages, layoutDirectory))
{
throw CreateLocationMismatchException(layoutDirectory, packages);
}
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved
}

cancellationToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Expand All @@ -55,29 +143,25 @@ public static async Task RegisterAsync(
}
catch (Exception ex)
{
// The WinRT operation can fault (rather than completing with a DeploymentResult), for example
// when Developer Mode is disabled or the layout is invalid. Surface it with the actionable
// registration message instead of a raw COM/WinRT exception.
// Include the requested manifest even when a Windows operation faults instead of returning
// a DeploymentResult, or Windows reports success without registering the requested location.
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, ExtensionResources.PackagedAppRegistrationFailed, manifestPath, ex.Message),
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved
ex);
}

// Registration reports success through IsRegistered; ExtendedErrorCode can also carry a non-fatal
// (informational) HRESULT, so IsRegistered is the authoritative signal.
if (!result.IsRegistered)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, ExtensionResources.PackagedAppRegistrationFailed, manifestPath, result.ErrorText),
result.ExtendedErrorCode);
}

cancellationToken.ThrowIfCancellationRequested();
}

/// <summary>Activates a registered packaged app and returns its process id.</summary>
public static uint Activate(string appUserModelId, string? activationArguments)
=> ApplicationActivationManager.ActivateApplication(appUserModelId, activationArguments);
}
private static bool IsRegisteredFromLayout(IReadOnlyList<RegisteredPackageInfo> packages, string layoutDirectory)
=> packages.Count == 1
&& string.Equals(
Path.TrimEndingDirectorySeparator(Path.GetFullPath(packages[0].InstalledPath)),
layoutDirectory,
StringComparison.OrdinalIgnoreCase);

#endif
private static InvalidOperationException CreateLocationMismatchException(string layoutDirectory, IReadOnlyList<RegisteredPackageInfo> packages)
=> new(string.Format(
CultureInfo.CurrentCulture,
ExtensionResources.PackagedAppRegistrationLocationMismatch,
layoutDirectory,
string.Join(", ", packages.Select(static package => package.InstalledPath))));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Testing.Extensions.PackagedApp;

internal sealed class RegisteredPackageInfo(string fullName, string installedPath, bool isDevelopmentMode)
{
public string FullName { get; } = fullName;

public string InstalledPath { get; } = installedPath;

public bool IsDevelopmentMode { get; } = isDevelopmentMode;
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,14 @@
<data name="PackagedAppRegistrationFailed" xml:space="preserve">
<value>Failed to register the packaged Windows app layout '{0}'. Registering an unsigned build-output layout requires Developer Mode (or sideloading) to be enabled. Error: {1}</value>
</data>
<data name="PackagedAppRegistrationLocationMismatch" xml:space="preserve">
<value>Cannot activate the requested layout '{0}': Windows reported registration success, but the current user's registered package locations are [{1}]. Close any running instances of the package and retry. No test host was activated.</value>
<comment>{0} is the requested layout directory. {1} is a comma-separated list of registered layout directories, or empty if no registration was found.</comment>
</data>
<data name="PackagedAppRegistrationNotDevelopment" xml:space="preserve">
<value>Cannot switch package '{0}' from '{1}' to '{2}': the existing package is not a development registration, so it cannot be removed while preserving application data. Use a separate package identity for development. No test host was activated.</value>
<comment>{0} is the package full name. {1} is the registered layout directory. {2} is the requested layout directory.</comment>
</data>
<data name="ActivationArgumentsInvalidArgumentCount" xml:space="preserve">
<value>The Microsoft Testing Platform activation-argument payload has an invalid argument count.</value>
<comment>Do not localize the technology name {Locked="Microsoft Testing Platform"}.</comment>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@
<target state="translated">Nepodařilo se zaregistrovat rozložení zabalené aplikace pro Windows „{0}“. Registrace nepodepsaného rozložení výstupu sestavení vyžaduje, aby byl povolen Režim vývojáře (nebo zkušební načtení). Chyba: {1}</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppRegistrationLocationMismatch">
<source>Cannot activate the requested layout '{0}': Windows reported registration success, but the current user's registered package locations are [{1}]. Close any running instances of the package and retry. No test host was activated.</source>
<target state="new">Cannot activate the requested layout '{0}': Windows reported registration success, but the current user's registered package locations are [{1}]. Close any running instances of the package and retry. No test host was activated.</target>
<note>{0} is the requested layout directory. {1} is a comma-separated list of registered layout directories, or empty if no registration was found.</note>
</trans-unit>
<trans-unit id="PackagedAppRegistrationNotDevelopment">
<source>Cannot switch package '{0}' from '{1}' to '{2}': the existing package is not a development registration, so it cannot be removed while preserving application data. Use a separate package identity for development. No test host was activated.</source>
<target state="new">Cannot switch package '{0}' from '{1}' to '{2}': the existing package is not a development registration, so it cannot be removed while preserving application data. Use a separate package identity for development. No test host was activated.</target>
<note>{0} is the package full name. {1} is the registered layout directory. {2} is the requested layout directory.</note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@
<target state="translated">Fehler beim Registrieren des gepackten Windows-App-Layouts "{0}". Zum Registrieren eines nicht signierten Buildausgabelayouts muss der Entwicklermodus (oder Querladen) aktiviert sein. Fehler: {1}</target>
<note />
</trans-unit>
<trans-unit id="PackagedAppRegistrationLocationMismatch">
<source>Cannot activate the requested layout '{0}': Windows reported registration success, but the current user's registered package locations are [{1}]. Close any running instances of the package and retry. No test host was activated.</source>
<target state="new">Cannot activate the requested layout '{0}': Windows reported registration success, but the current user's registered package locations are [{1}]. Close any running instances of the package and retry. No test host was activated.</target>
<note>{0} is the requested layout directory. {1} is a comma-separated list of registered layout directories, or empty if no registration was found.</note>
</trans-unit>
<trans-unit id="PackagedAppRegistrationNotDevelopment">
<source>Cannot switch package '{0}' from '{1}' to '{2}': the existing package is not a development registration, so it cannot be removed while preserving application data. Use a separate package identity for development. No test host was activated.</source>
<target state="new">Cannot switch package '{0}' from '{1}' to '{2}': the existing package is not a development registration, so it cannot be removed while preserving application data. Use a separate package identity for development. No test host was activated.</target>
<note>{0} is the package full name. {1} is the registered layout directory. {2} is the requested layout directory.</note>
</trans-unit>
</body>
</file>
</xliff>
Loading
Loading