### Run HelloWorldAdvancedCPP Example Source: https://github.com/microsoft/windowsappsdk/blob/main/test/DynamicDependency/ManualTest/README.md Executes HelloWorldAdvancedCPP.exe with different version parameters to test Dynamic Dependencies initialization. ```bash [C:] BuildOutput\Debug\x64\HelloWorldAdvancedCPP\HelloWorldAdvancedCPP.exe 1.0 MddBootstrapInitialize(0x00010000, "", 0.0.0.0)... Hello World! ``` ```bash [C:] BuildOutput\Debug\x64\HelloWorldAdvancedCPP\HelloWorldAdvancedCPP.exe 1.1 MddBootstrapInitialize(0x00010001, "", 0.0.0.0)... Error 0x80070491 in MddBootstrapInitialize(0x00010001, "", 0.0.0.0) ``` ```bash [C:] BuildOutput\Debug\x64\HelloWorldAdvancedCPP\HelloWorldAdvancedCPP.exe 5.9 MddBootstrapInitialize(0x00050009, "", 0.0.0.0)... Error 0x80070491 in MddBootstrapInitialize(0x00050009, "", 0.0.0.0) ``` -------------------------------- ### Check Visual Studio Installation Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/VSIX/build-local-VSIX-package/build-local-VSIX-package.md Quickly checks for the latest Visual Studio installation and lists installed .NET SDKs. ```powershell & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -format json dotnet --list-sdks ``` -------------------------------- ### Build Error Log Example Source: https://github.com/microsoft/windowsappsdk/blob/main/docs/Coding-Guidelines/GettingStarted.md Example of MSB3073 error output indicating a signing tool failure. ```text MSB3073 The command "signtool.exe sign ..." exited with code 1...\MakeMsix.targets... ``` ```text Build Output: EXEC : SignTool error : No certificates were found that met all the given criteria. ...\MakeMsix.targets...error MSB3073: The command "signtool.exe sign ..." exited with code 1. ``` -------------------------------- ### Install Local Windows App SDK Templates Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/Dotnet/README.md Installs the locally packed Windows App SDK .NET templates. Replace `` with the actual version number from the generated .nupkg file. ```shell dotnet new install ./localpackages/Microsoft.WindowsAppSDK.WinUI.CSharp.Templates..nupkg ``` -------------------------------- ### Run Manual Tests Source: https://github.com/microsoft/windowsappsdk/blob/main/tools/mcp/github-artifacts/README.md Execute these commands in the server directory to install dependencies and run the test suite. ```bash cd tools/mcp/github-artifacts npm install npm test ``` -------------------------------- ### Install a package from a local file using AddPackageAsync Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md Installs a package from a local .msix file path. Requires a PackageDeploymentManager instance and AddPackageOptions. ```c# void Install() { var package = "d:\\contoso\\muffin.msix"; var packageDeploymentManager = PackageDeploymentManager.GetDefault(); var options = new AddPackageOptions(); var deploymentResult = await packageDeploymentManager.AddPackageAsync(package, options); if (deplymentResult.Status == PackageDeploymentStatus.CompletedSuccess) { Console.WriteLine("OK"); } else { Console.WriteLine("Error:{} ExtendedError:{} {}", deploymentResult.Error.HResult, deploymentResult.ExtendedError.HResult, deploymentResult.ErrorText); } } ``` -------------------------------- ### Install WinUI 3 C# Templates Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/Dotnet/README.md Installs the official WinUI 3 project and item templates for the Windows App SDK using the .NET CLI. ```shell dotnet new install Microsoft.WindowsAppSDK.WinUI.CSharp.Templates ``` -------------------------------- ### Configure FileTypeChoices and InitialFileTypeIndex Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Storage.Pickers/Microsoft.Windows.Storage.Pickers.md Example demonstrating how FileTypeChoices interacts with InitialFileTypeIndex to determine the default category selection. ```text FileTypeChoices = { "Texts": [".txt"], "Documents": [".doc", ".docx"] } with InitialFileTypeIndex = 1, the file dialog initially selects the Documents category; with InitialFileTypeIndex = -1 or not specified by developer, the file dialog initially selects the first - the "Texts" - category. ``` -------------------------------- ### Environment Variable Operations Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/AppLifecycle/EnvironmentVariables/AppLifecycle - Environment Variables (EV).md Examples of how to get, set, and manipulate environment variables using the EnvironmentManager. ```APIDOC ## Environment Variable Operations ### Get Environment Variable #### Method GET #### Endpoint `/environment/variable/{name}` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Path Parameters - **name** (string) - Required - The name of the environment variable to retrieve. #### Response ##### Success Response (200) - **value** (string) - The value of the environment variable. ### Set Environment Variable #### Method POST #### Endpoint `/environment/variable/{name}` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Path Parameters - **name** (string) - Required - The name of the environment variable to set. ##### Request Body - **value** (string) - Required - The value to set for the environment variable. ### Append to PATH #### Method POST #### Endpoint `/environment/path/append` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Request Body - **path** (string) - Required - The path to append to the PATH variable. ### Remove from PATH #### Method DELETE #### Endpoint `/environment/path/remove` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Request Body - **path** (string) - Required - The path to remove from the PATH variable. ### Add Executable File Extension #### Method POST #### Endpoint `/environment/pathext/add` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Request Body - **extension** (string) - Required - The file extension to add to the PATHEXT variable. ### Remove Executable File Extension #### Method DELETE #### Endpoint `/environment/pathext/remove` (Conceptual - actual usage via EnvironmentManager class) #### Parameters ##### Request Body - **extension** (string) - Required - The file extension to remove from the PATHEXT variable. ``` -------------------------------- ### Handle Battery Status Changes Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/AppLifecycle/StateNotifications/AppLifecycle StateNotifications.md Implement callback logic to react to battery status changes. This example demonstrates pausing non-critical work when the battery is discharging below 25% and starting power-intensive work when charging above 75%. ```cpp void OnBatteryStatusChanged() { BatteryStatus batteryStatus = PowerManager::BatteryStatus(); int remainingCharge = PowerManager::RemainingChargePercent(); if (batteryStatus == BatteryStatus::Discharging && remainingCharge < 25) { // We're in a bad battery state, we should pause any non-critical work. PauseNonCriticalWork(); } else if (batteryStatus == BatteryStatus::Charging && remainingCharge > 75) { // Battery is in great shape, let's kick of some high-power work. StartPowerIntensiveWork(); } } ``` -------------------------------- ### Instantiate MyExample class in C# Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/spec_template.md Demonstrates basic instantiation and member assignment for the MyExample class. ```c# void SampleMethod() { var show = new MyExample(); show.SomeMembers = AndWhyItMight(be, interesting) } ``` -------------------------------- ### Quickstart a new WinUI 3 App Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/Dotnet/README.md Creates a new WinUI 3 application with MSIX packaging and launches it. This command registers a loose-layout MSIX and provides package identity. ```powershell dotnet new winui -n MyApp cd MyApp # dotnet build dotnet run ``` -------------------------------- ### Install and Uninstall Package Dependencies (C++) Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/sample-4.md Provides functions to install and uninstall Win32 package dependencies. It's crucial to define dependencies before installing to avoid race conditions. ```cpp #include #include HRESULT SavePackageDependencyId(_In_ PCWSTR what, _In_ PCWSTR packageDependencyId); HRESULT DeletePackageDependencyId(_In_ PCWSTR what); HRESULT LoadPackageDependencyId(_In_ PCWSTR what, wil::unique_ptr& packageDependencyId); HRESULT DefinePackageDependencies(); HRESULT DefinePackageDependency_Muffins(); HRESULT DefinePackageDependency_Waffles(); PCWSTR GetMuffinsLifetimeAbsoluteFilename(); PCWSTR GetWafflesLifetimeRegistryKey(); HRESULT DeletePackageDependencyIds(); HRESULT Install() { // Define the package dependency before installing it, just in case we're the 1st to install it. // If we did the reverse order (Install then Define) and we're unlucky, Windows might check if // the framework package is needed after it's installed but before the package dependency is // defined, determine it's not needed and remove it, causing us much grief :-( RETURN_IF_FAILED(DefinePackageDependencies()); RETURN_IF_FAILED(InstallPackagesViaPackageManagerAddPackageAsync()); return S_OK; } HRESULT Uninstall() { RETURN_IF_FAILED(UndefinePackageDependency()); RETURN_IF_FAILED(UninstallPackageDependency()); return S_OK; } ``` -------------------------------- ### Package Dependency Graph Example Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/DynamicDependencies.md Illustrates a package dependency graph with Main, Optional, HostRuntime, and Framework packages. Demonstrates the expected order for traversal. ```text Main = [ H1, F1 ] Opt = [ H2, F2 ] H1 = [ F3 ] H2 = [ F4 ] where Main = Main package Opt = Optional package H* = Main package providing a HostRuntime F* = Framework package the package graph will be [Main, Opt, H1, F1, H2, F2, F3, F4] ``` -------------------------------- ### Initialize Windows App SDK in C# Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/sample-b.1.md Demonstrates initialization using the Bootstrap class with either exception-based or HRESULT-based error handling. ```c# using System; using Microsoft.Windows.ApplicationModel.DynamicDependency; namespace HelloWorldCS { class Program { static void Main(string[] args) { // Initialize access to Windows App SDK uint majorMinorVersion = 0x00010000; string versionTag = "preview1"; var minVersion = new PackageVersion(); try { Console.WriteLine($"Bootstrap.Initialize({majorMinorVersion:X08}, \"{versionTag}\", {minVersion.Major}.{minVersion.Minor}.{minVersion.Build}.{minVersion.Revision})..."); Bootstrap.Initialize(majorMinorVersion, versionTag, minVersion); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(e.HResult); } // Do interesting stuff... Console.WriteLine("Hello World!"); // Cleanup Bootstrap.Shutdown(); } } } ``` ```c# using System; using Microsoft.Windows.ApplicationModel.DynamicDependency; namespace HelloWorldCS_NoThrow { class Program { static void Main(string[] args) { // Initialize access to Windows App SDK uint majorMinorVersion = 0x00010000; string versionTag = "preview1"; var minVersion = new PackageVersion(); Console.WriteLine($"Bootstrap_NoThrow.Initialize({majorMinorVersion:X08}, \"{versionTag}\", {minVersion.Major}.{minVersion.Minor}.{minVersion.Build}.{minVersion.Revision})..."); int hr = 0; if (!Bootstrap.TryInitialize(majorMinorVersion, versionTag, minVersion, out hr)) { Console.WriteLine($"Error 0x{hr:X08} in Bootstrap_NoThrow.Initialize(0x{majorMinorVersion:X08}, \"{versionTag}\", {minVersion.Major}.{minVersion.Minor}.{minVersion.Build}.{minVersion.Revision})"); Environment.Exit(hr); } // Do interesting stuff... Console.WriteLine("Hello World!"); // Cleanup Bootstrap.Shutdown(); } } } ``` -------------------------------- ### Ensure Package Readiness Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md APIs to ensure packages are installed and available, downloading and installing them if necessary. ```APIDOC ## Package Deployment API - Ensure Readiness ### Description Ensures that the necessary packages are present and available for use. If not, it initiates the process to make them available (e.g., download, install). ### Methods #### EnsurePackageReadyAsync Ensures a specific package is ready for use. Installs or downloads if not present. - **Method**: POST - **Endpoint**: N/A (Method on PackageDeploymentManager) - **Parameters**: - **package** (String) - Required - The name or identifier of the package. - **options** (EnsureReadyOptions) - Optional - Options to control the readiness process. - **AddPackageOptions** (AddPackageOptions) - Options for adding packages. - **RegisterNewerIfAvailable** (Boolean) - Requires Windows >= 10.0.22000.0 (aka Win11 21H2). If true, registers a newer version if available. #### EnsurePackageReadyByUriAsync Ensures a package specified by its URI is ready for use. - **Method**: POST - **Endpoint**: N/A (Method on PackageDeploymentManager) - **Parameters**: - **packageUri** (Windows.Foundation.Uri) - Required - The URI of the package. - **options** (EnsureReadyOptions) - Optional - Options to control the readiness process. #### EnsurePackageSetReadyAsync Ensures all packages within a given package set are ready for use. - **Method**: POST - **Endpoint**: N/A (Method on PackageDeploymentManager) - **Parameters**: - **packageSet** (PackageSet) - Required - The set of packages to ensure readiness for. - **PackageUri** (Windows.Foundation.Uri) - Required - The URI of a package within the set. - **options** (EnsureReadyOptions) - Optional - Options to control the readiness process. ### Request Body Examples #### EnsurePackageReadyAsync Request Body ```json { "package": "Contoso.MyApp", "options": { "AddPackageOptions": { "DependencyPackageUris": [], "OptionalPackageFamilyNames": [], "ExternalLocationUri": null, "AllowUnsigned": false, "DeveloperMode": false, "ForceAppShutdown": false, "ForceTargetAppShutdown": false, "ForceUpdateFromAnyVersion": false, "InstallAllResources": false, "StageInPlace": false, "DeferRegistrationWhenPackagesAreInUse": false, "IsExpectedDigestsSupported": false, "ExpectedDigests": {} }, "RegisterNewerIfAvailable": true } } ``` #### EnsurePackageReadyByUriAsync Request Body ```json { "packageUri": "http://example.com/packages/Contoso.MyApp.msix", "options": { "AddPackageOptions": {}, "RegisterNewerIfAvailable": false } } ``` #### EnsurePackageSetReadyAsync Request Body ```json { "packageSet": { "Items": [ { "PackageUri": "http://example.com/packages/Contoso.MyApp.msix" } ] }, "options": { "AddPackageOptions": {}, "RegisterNewerIfAvailable": false } } ``` ### Response Examples #### Success Response (PackageDeploymentResult) - **Status** (PackageDeploymentStatus) - The overall status of the deployment operation. - **Error** (PackageDeploymentError) - Details about any error that occurred. - **Packages** (IVector) - Information about the deployed packages. #### Progress Response (PackageDeploymentProgress) - **State** (PackageDeploymentState) - The current state of the deployment operation. - **PackagesProgress** (UInt64) - The number of packages processed so far. - **TotalPackages** (UInt64) - The total number of packages to be processed. ``` -------------------------------- ### Example WinMain Implementation for Main Package Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Deployment/MSIXPackages.md Illustrates a minimal WinMain implementation for the Main package, exporting the actual functionality from a DLL in the Framework package. This approach minimizes the Main package's footprint. ```c int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { return MyFeatureWinMain(hInstance, hPrevInstance, pCmdLine, nCmdShow); } ``` -------------------------------- ### Build and Install VSIX Separately Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/VSIX/build-local-VSIX-package/build-local-VSIX-package.md Runs the VSIX build and local installation steps as separate commands. ```powershell .\Build-VSIX.ps1 # default = -Deployment LocalDev .\Install-LocalDev-VSIX.ps1 ``` -------------------------------- ### Notes on SuggestedFolder, SuggestedStartFolder, and SuggestedStartLocation Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Storage.Pickers/Microsoft.Windows.Storage.Pickers.md Clarifies the behavior and precedence of properties related to setting the initial folder or location in pickers. ```APIDOC ## Notes ### Understanding SuggestedFolder/SuggestedStartFolder/SuggestedStartLocation These properties influence the initial state of file and folder pickers with different behaviors: - **`SuggestedFolder`**: Sets the path that the picker will always attempt to open to, regardless of user history. This corresponds to the `IShellItemFilter::SetFolder` method in underlying COM APIs and takes precedence over other suggestions. - **`SuggestedStartFolder`**: Sets the path shown only on the *first* launch of the picker (e.g., for a new app installation). After the user makes a selection, subsequent launches will open to the last selected folder, and this property becomes inactive. This aligns with the `IShellItemFilter::SetDefaultFolder` COM method. - **`SuggestedStartLocation`**: Similar to `SuggestedStartFolder`, this property influences the initial location shown only on the first launch. Its effective duration is the same as `SuggestedStartFolder`. **Precedence:** - `SuggestedStartFolder` takes precedence over `SuggestedStartLocation` when both are specified. - `SuggestedFolder` takes precedence over both `SuggestedStartFolder` and `SuggestedStartLocation`. ``` -------------------------------- ### Get PrimaryLanguageOverride Property Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/mrtcore/PrimaryLanguageOverride/PrimaryLanguageOverride.md This C# code snippet shows the signature for getting or setting the PrimaryLanguageOverride property. ```csharp public static string PrimaryLanguageOverride { get; set; } ``` -------------------------------- ### Provisioning a Package Set in C# Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md Demonstrates checking for provisioned packages and staging/provisioning them if necessary, including user confirmation. ```c# void Install() { // We want to check what's provisioned by PackageFamilyName. If something's // not provisioned we'll also need MinVersion and PackageUri to Stage and // Provision. But checking if a family is provisioned only supports some // URI schemes (notably, not the one we need for our staging work). So we'll // define the PackageSet with the families we want checked and if something's // not provisioned we'll add the additional properties needed. var packageSet = new PackageSet() { Items = { new PackageSetItem() { PackageFamilyName = "contoso.muffin_1234567890abc" }, { new PackageSetItem() { PackageFamilyName = "contoso.waffle_1234567890abc" } } }; var packageDeploymentManager = PackageDeploymentManager.GetDefault(); if (packageDeploymentManager.IsPackageSetProvisioned(packageSet)) { return; } bool ok = PromptUserForConfirmation(); if (!ok) { return; } packageSet.Items()[0].MinVersion(ToVersion(1, 2, 3, 4)); packageSet.Items()[0].PackageUri(new Uri("c:\\contoso\\muffin-1.2.3.4.msix")); packageSet.Items()[1].MinVersion(ToVersion(2, 4, 6, 8)); packageSet.Items()[1].PackageUri(new Uri("https://contoso.com/waffle-2.4.6.8.msix")); var stageOptions = new StagePackageOptions(); var deploymentResult = await packageDeploymentManager.StagePackageSetReadyAsync(packageSet, options); if (deplymentResult.Status == PackageDeploymentStatus.CompletedSuccess) { Console.WriteLine("Staged"); } else { Console.WriteLine("Error:{} ExtendedError:{} {}", deploymentResult.Error.HResult, deploymentResult.ExtendedError.HResult, deploymentResult.ErrorText); return; } var options = new ProvisionPackageOptions(); var deploymentResult = await packageDeploymentManager.ProvisionPackageSetReadyAsync(packageSet, options); if (deplymentResult.Status == PackageDeploymentStatus.CompletedSuccess) { Console.WriteLine("Provisioned"); } else { Console.WriteLine("Error:{} ExtendedError:{} {}", deploymentResult.Error.HResult, deploymentResult.ExtendedError.HResult, deploymentResult.ErrorText); } } PackageVersion ToVersion(uint major, uint minor, uint build, uint revision) => new PackageVersion { Major = checked((ushort)major), Minor = checked((ushort)minor), Build = checked((ushort)build), Revision = checked((ushort)revision) }; ``` -------------------------------- ### Configure FolderPicker in C# and C++ Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Storage.Pickers/FolderPicker.md Demonstrates how to initialize a FolderPicker instance and configure its optional properties such as start folders, button text, and settings identifiers. ```C# using Microsoft.Windows.Storage.Pickers; var folderPicker = new FolderPicker(this.AppWindow.Id) { // (Optional) Sets the folder that the folder dialog always tries to display when it opens. // SuggestedFolder will not be overriden by the last picked folder. // If not specified, or the specified path doesn't exist, defaults to the last folder the user picked. // On first launch of the picker, SuggestedFolder takes precedence over the SuggestedStartFolder if both set. SuggestedFolder = @"C:\MyFiles", // (Optional) Sets an initial folder path shown when the picker is first launched. // Once the user has picked from a directory, SuggestedStartFolder will be silently ignored. // Takes precedence over SuggestedStartLocation when both defined. // If this folder is not found, falls back to SuggestedStartLocation. SuggestedStartFolder = @"C:\MyFiles", // (Optional) Specify the initial location for the picker. // If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary. // If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location. SuggestedStartLocation = PickerLocationId.DocumentsLibrary, // (Optional) specify the text displayed on the commit button. // If not specified, the system uses a default label of "Open" (suitably translated). CommitButtonText = "Select Folder", // (Optional) specify the title of the picker. // If not specified, the system uses a default title. Title = "Select Folder", // (Optional) allows customization of the settings name, to distinguish picker instances. // Without the SettingsIdentifier specified, pickers in one app share the state together. // Only specify this when a picker needs to track its own state (e.g. size, location, etc). SettingsIdentifier = "BookContents", // (Optional) specify the view mode of the picker dialog. If not specified, default to List. ViewMode = PickerViewMode.List, }; ``` ```C++ #include using namespace winrt::Microsoft::Windows::Storage::Pickers; FolderPicker folderPicker(AppWindow().Id()); // (Optional) Sets the folder that the folder dialog always tries to display when it opens. // SuggestedFolder will not be overriden by the last picked folder. // If not specified, or the specified path doesn't exist, defaults to the last folder the user picked. // On first launch of the picker, SuggestedFolder takes precedence over the SuggestedStartFolder if both set. folderPicker.SuggestedFolder(L"C:\\MyFiles"); // (Optional) Sets an initial folder path shown when the picker is first launched. // Once the user has picked from a directory, SuggestedStartFolder will be silently ignored. // Takes precedence over SuggestedStartLocation when both defined. // If this folder is not found, falls back to SuggestedStartLocation. folderPicker.SuggestedStartFolder(L"C:\\MyFiles"); // (Optional) Specify the initial location for the picker. // If the specified location doesn't exist on the user's machine, it falls back to the DocumentsLibrary. // If not set, it defaults to PickerLocationId.Unspecified, and the system will use its default location. folderPicker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary); // (Optional) specify the text displayed on the commit button. // If not specified, the system uses a default label of "Open" (suitably translated). folderPicker.CommitButtonText(L"Select Folder"); // (Optional) specify the title of the picker. // If not specified, the system uses a default title. folderPicker.Title(L"Select Folder"); // (Optional) allows customization of the settings name, to distinguish picker instances. // Without the SettingsIdentifier specified, pickers in one app share the state together. // Only specify this when a picker needs to track its own state (e.g. size, location, etc). folderPicker.SettingsIdentifier(L"BookContents"); // (Optional) specify the view mode of the picker dialog. If not specified, default to List. folderPicker.ViewMode(PickerViewMode::List); ``` -------------------------------- ### Get Help for TerminalVelocity Generator Source: https://github.com/microsoft/windowsappsdk/blob/main/docs/Coding-Guidelines/TerminalVelocity.md To view the supported parameters and get help for the TerminalVelocity generator, run the command with the -? argument. ```cmd tools\TerminalVelocity\Generate-TerminalVelocityFeatures.cmd -? ``` -------------------------------- ### MSBuild ProjectTemplate Entry Example Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/how-to-create-a-new-csharp-template.md An example of an MSBuild item element for a ProjectTemplate, detailing required metadata for template configuration. ```xml WinUI.Desktop.Cs.SomeName $(MSBuildThisFileDirectory)Source\ProjectTemplates\Desktop\CSharp\SomeName $(MSBuildThisFileDirectory)Dotnet\templates\some-name Package-managed.appxmanifest ``` -------------------------------- ### Pick a Folder and Convert to StorageFolder Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Storage.Pickers/PickFolderResult.md Demonstrates picking a folder and converting the result to a StorageFolder object for use with existing business logic. ```C# using Microsoft.Windows.Storage.Pickers; // In a method of a window class var picker = new FolderPicker(this.AppWindow.Id); var result = await picker.PickSingleFolderAsync(); if (result != null) { // Perform this conversion if you have business logic that uses StorageFolder var storageFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(result.Path); // Continue your business logic with storageFolder } else { // error handling. } ``` ```C++ #include using namespace winrt::Microsoft::Windows::Storage::Pickers; // In a coroutine method of a window class FolderPicker picker{ AppWindow().Id() }; auto result{ co_await picker.PickSingleFolderAsync() }; if (result) { // Perform this conversion if you have business logic that uses StorageFolder auto storageFolder{ co_await winrt::Windows::Storage::StorageFolder::GetFolderFromPathAsync(result.Path()) }; // Continue your business logic with storageFolder } else { // error handling. } ``` -------------------------------- ### TryInitialize Methods Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/DynamicDependencies.md These methods attempt to initialize the calling process to use the Windows App SDK's framework package. They return a boolean indicating success or failure and provide an HRESULT for error details. They find a suitable framework package based on the provided criteria and make it available to the current process. If multiple packages match, the best candidate is selected. ```APIDOC ## TryInitialize(uint majorMinorVersion, out int hresult) ### Description Attempts to initialize the calling process to use the Windows App SDK's framework package. Failure returns false with the failure HRESULT in the hresult parameter. ### Method `public static bool TryInitialize(uint majorMinorVersion, out int hresult)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (true) - **hresult** (int) - The HRESULT indicating success (typically 0) or failure. #### Response Example None ``` ```APIDOC ## TryInitialize(uint majorMinorVersion, string versionTag, out int hresult) ### Description Attempts to initialize the calling process to use the Windows App SDK's framework package with a specified version tag. Failure returns false with the failure HRESULT in the hresult parameter. ### Method `public static bool TryInitialize(uint majorMinorVersion, string versionTag, out int hresult)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (true) - **hresult** (int) - The HRESULT indicating success (typically 0) or failure. #### Response Example None ``` ```APIDOC ## TryInitialize(uint majorMinorVersion, string versionTag, PackageVersion minVersion, out int hresult) ### Description Attempts to initialize the calling process to use the Windows App SDK's framework package with a specified version tag and minimum version. Failure returns false with the failure HRESULT in the hresult parameter. ### Method `public static bool TryInitialize(uint majorMinorVersion, string versionTag, PackageVersion minVersion, out int hresult)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (true) - **hresult** (int) - The HRESULT indicating success (typically 0) or failure. #### Response Example None ``` ```APIDOC ## TryInitialize(uint majorMinorVersion, string versionTag, PackageVersion minVersion, InitializeOptions options, out int hresult) ### Description Attempts to initialize the calling process to use the Windows App SDK's framework package with a specified version tag, minimum version, and optional behavior. Failure returns false with the failure HRESULT in the hresult parameter. ### Method `public static bool TryInitialize(uint majorMinorVersion, string versionTag, PackageVersion minVersion, InitializeOptions options, out int hresult)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (true) - **hresult** (int) - The HRESULT indicating success (typically 0) or failure. #### Response Example None ``` -------------------------------- ### dotnet pack and install command Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/how-to-create-a-new-csharp-template.md Commands to pack the C# dotnet-new templates and install the generated NuGet package locally for testing. ```powershell # dotnet-new NuGet (inspect produced .nupkg under localpackages\) dotnet pack dev\Templates\Dotnet\WinAppSdk.CSharp.DotnetNewTemplates.csproj -c Debug # dotnet new uninstall Microsoft.WindowsAppSDK.WinUI.CSharp.Templates dotnet new install localpackages\Microsoft.WindowsAppSDK.WinUI.CSharp.Templates.*.nupkg ``` -------------------------------- ### Install a package from a URI using AddPackageByUriAsync Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md Installs a package from an https URI source. Uses the AddPackageByUriAsync method instead of AddPackageAsync. ```c# void Install() { var package = new Uri("https://contoso.com/muffin.msix"); var packageDeploymentManager = PackageDeploymentManager.GetDefault(); var options = new AddPackageOptions(); var deploymentResult = await packageDeploymentManager.AddPackageByUriAsync(package, options); if (deplymentResult.Status == PackageDeploymentStatus.CompletedSuccess) { Console.WriteLine("OK"); } else { Console.WriteLine("Error:{} ExtendedError:{} {}", deploymentResult.Error.HResult, deploymentResult.ExtendedError.HResult, deploymentResult.ErrorText); } } ``` -------------------------------- ### Register for rich activation in a Win32 app Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/AppLifecycle/Activation/AppLifecycle Activation.md Demonstrates initializing COM, registering for activation kinds, and setting up the message pump in a wWinMain function. ```c++ int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int nCmdShow) { // Initialize COM. winrt::init_apartment(); // Registering for rich activation kinds can be done in the // app's installer or in the app itself. RegisterForActivation(); // When the app starts, it can get its activated eventargs, and perform // any required operations based on the activation kind and payload. RespondToActivation(); /////////////////////////////////////////////////////////////////////////// // Standard Win32 window configuration/creation and message pump: // ie, whatever the app would normally do - nothing new here. RegisterClassAndStartMessagePump(hInstance, nCmdShow); return 1; } void RegisterForActivation() { // Register one or more supported filetypes, specifying // an icon (specified by binary file path plus resource index), // a display name to use in Shell and Settings, // zero or more verbs for the File Explorer context menu, // and the path to the EXE to register for activation. hstring myFileTypes[3] = { L".foo", L".foo2", L".foo3" }; hstring verbs[2] = { L"view", L"edit" }; ActivationRegistrationManager::RegisterForFileTypeActivation( myFileTypes, exePathAndIconIndex, L"Contoso File Types", verbs, exePath ); // Register a URI scheme for protocol activation, // specifying the scheme name, icon, display name and EXE path. ActivationRegistrationManager::RegisterForProtocolActivation( L"foo", exePathAndIconIndex, L"Contoso Foo Protocol", exePath ); // Register for startup activation. // As we're registering for startup activation multiple times, // and this is a multi-instance app, we'll get multiple instances // activated at startup. ActivationRegistrationManager::RegisterForStartupActivation( L"ContosoStartupId", exePath ); // If we don't specify the EXE, it will default to this EXE. ActivationRegistrationManager::RegisterForStartupActivation( L"ContosoStartupId2", L"" ); } ``` -------------------------------- ### Build and Install Local VSIX Package Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/how-to-create-a-new-csharp-template.md PowerShell script command to build and install the local development VSIX package for Visual Studio. ```powershell dev\Templates\VSIX\build-local-VSIX-package\build-install-localdev-vsix.ps1 ``` -------------------------------- ### Pick a File and Convert to StorageFile Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Storage.Pickers/PickFileResult.md Demonstrates using FileOpenPicker to select a file and converting the resulting path to a StorageFile object. ```C# using Microsoft.Windows.Storage.Pickers; // In a coroutine method of a window class var picker = new FileOpenPicker(this.AppWindow.Id); var result = await picker.PickSingleFileAsync(); if (result != null) { // Perform this conversion if you have business logic that uses StorageFile var storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(result.Path); // Continue your business logic with storageFile } else { // error handling. } ``` ```C++ #include using namespace winrt::Microsoft::Windows::Storage::Pickers; // In a coroutine method of a window class FileOpenPicker picker{ AppWindow().Id() }; auto result{ co_await picker.PickSingleFileAsync() }; if (result) { // Perform this conversion if you have business logic that uses StorageFile auto storageFile{ co_await winrt::Windows::Storage::StorageFile::GetFileFromPathAsync(result.Path()) }; // Continue your business logic with storageFile } else { // error handling. } ``` -------------------------------- ### Initialize Windows App SDK Runtime (C++) Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/Deployment/BuildInformation.md Include the WindowsAppSDK-VersionInfo.h header to access version constants for initializing the Windows App SDK runtime. This example demonstrates using the SDK constants. ```cpp #include int main() { const uint32_t c_majorMinorRelease{ WINDOWSAPPSDK_RELEASE_MAJOR_MINOR }; auto c_versionTag{ WINDOWSAPPSDK_RELEASE_VERSION_TAG_W }; const PACKAGE_VERSION c_minVersion{ WINDOWSAPPSDK_RUNTIME_VERSION_UINT64 }; RETURN_IF_FAILED(MddBootstrapInitialize(c_majorMinorRelease, c_versionTag, minVersion)); ... ``` -------------------------------- ### C# Decimal Implementation Example Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/decimal/decimal.md A canonical example demonstrating decimal arithmetic operations using C#'s native Decimal type. ```csharp Using System; Using System.IO; class Program { static void Main() { var a = new Decimal(1); var b = new Decimal(0.5); var c = Decimal.Parse("-6.66"); var d = Decimal.Parse("1.23"); var e = Decimal.Parse("4567.089"); var f = new Decimal((long)-4); var g = new Decimal((uint)1967); var h = new Decimal(1001.0); var x = Decimal.Round(((a - b) + (c % d)) * e, 5) / f; var y = Math.Clamp(Decimal.Round(x++, 3), f, g); var z = (Decimal.Floor(y) - 1) * (Decimal.Ceiling(x) + 1) * -Decimal.Truncate(y); Console.WriteLine($"x = {x}"); Console.WriteLine($"y = {y}"); Console.WriteLine($"z = {z}"); Environment.Exit((int)z); } } ``` -------------------------------- ### Remove Installed WinAppSDK Packages Source: https://github.com/microsoft/windowsappsdk/blob/main/test/DynamicDependency/ManualTest/README.md Removes all installed Windows App SDK runtime packages for the current user. This command requires careful execution. ```powershell powershell -c "$(get-appxpackage micro*win*apprun*).packagefullname | remove-appxpackage" ``` ```powershell powershell -c "$(get-appxpackage micro*win*apprun*).packagefullname" ``` -------------------------------- ### TryInitialize Method Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/DynamicDependencies.md Attempts to find and make a Windows App SDK framework package available for the current process. It selects the best candidate if multiple packages match the criteria. ```APIDOC ## TryInitialize ### Description Find a Windows App SDK framework package meeting the criteria and make it available for use by the current process. If multiple packages meet the criteria the best candidate is selected. ### Method `public static bool TryInitialize(uint majorMinorVersion, string versionTag, PackageVersion minVersion, InitializeOptions options, out int hresult)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // Example usage (conceptual, actual types may vary) uint majorMinorVersion = 0x00010002; // Represents 1.2 string versionTag = "preview1"; PackageVersion minVersion = new PackageVersion(1, 0, 0, 0); InitializeOptions options = InitializeOptions.None; int hresult; bool success = DynamicDependencyApi.TryInitialize(majorMinorVersion, versionTag, minVersion, options, out hresult); if (success) { // Initialization successful } else { // Initialization failed, check hresult } ``` ### Response #### Success Response (true) Returns `true` if the framework package was successfully found and made available. #### Failure Response (false) Returns `false` if an error occurred. The failure HRESULT is provided in the `hresult` parameter. #### Response Example `true` or `false` (for the return value), and `hresult` will contain the error code on failure. ``` -------------------------------- ### Build and Install LocalDev VSIX Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/VSIX/build-local-VSIX-package/build-local-VSIX-package.md Builds and installs the LocalDev VSIX into all VS 17+ instances on the machine without requiring admin privileges or modifying setup.exe. ```powershell # Build + install the LocalDev VSIX into every VS 17+ instance on the machine. # No admin required. No setup.exe modify. No workload removal. .\build-install-localdev-vsix.ps1 # Then in Visual Studio: File -> New -> Project -> filter C# -> search "WinUI" ``` -------------------------------- ### Build Installer Test Packages via Command Line Source: https://github.com/microsoft/windowsappsdk/blob/main/installer/test/CreateTestPackages/README.md Commands to build test packages for x86, x64, and arm64 architectures using MSBuild. ```batch cd installer\test\CreateTestPackages msbuild CreateTestPackages.sln -p:Configuration=Release -p:Platform=x86 msbuild CreateTestPackages.sln -p:Configuration=Release -p:Platform=x64 msbuild CreateTestPackages.sln -p:Configuration=Release -p:Platform=arm64 ``` -------------------------------- ### Implement File Activation Redirection Logic in C++ Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/AppLifecycle/Instancing/AppLifecycle SingleMulti-Instancing.md This snippet shows how to get activation arguments, check if the activation is file-related, and then use AppInstance.FindOrRegisterForKey to manage multiple instances working with the same file. It handles both successful registration and redirection to an existing instance. ```cpp int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { // Initialize COM. winrt::init_apartment(); // First, we'll get our rich activation event args. AppActivationArguments activationArgs = AppInstance::GetCurrent().GetActivatedEventArgs(); // An app might want to set itself up for possible redirection in // the case where it opens files - for example, to prevent multiple // instances from working on the same file. ExtendedActivationKind kind = activationArgs.Kind(); if (kind == ExtendedActivationKind::File) { auto fileArgs = activationArgs.Data().as(); IStorageItem file = fileArgs.Files().GetAt(0); // Let's try to register this instance for this file. AppInstance instance = AppInstance::FindOrRegisterForKey(file.Name()); if (instance.IsCurrent()) { // If we successfully registered this instance, we can now just // go ahead and do normal initialization. RegisterClassAndStartMessagePump(hInstance, nCmdShow); } else { // Some other instance has already registered for this file, // so we'll redirect this activation to that instance instead. // This is an async operation: to ensure the target can get // the payload before this instance terminates, we should // wait for the call to complete. instance.RedirectActivationToAsync(activationArgs).get(); } } return 1; } ``` -------------------------------- ### List Installed WinAppSDK Packages Source: https://github.com/microsoft/windowsappsdk/blob/main/test/DynamicDependency/ManualTest/README.md Lists all installed Windows App SDK runtime packages for the current user. Ensure no undesired packages are registered before testing. ```powershell powershell -c "$(get-appxpackage micro*win*apprun*).packagefullname | sort" ``` -------------------------------- ### Initialize Windows App SDK with MddBootstrap Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/dynamicdependencies/DynamicDependencies.md Demonstrates initializing the Windows App SDK framework package using MddBootstrap::InitializeNoThrow. This setup is required before using Windows App SDK features in a process. ```cpp #include #include #include #include using MddBootstrap = Microsoft::Windows::ApplicationModel::DynamicDependency::Bootstrap; int main() { const auto hr{ MddBootstrap::InitializeNoThrow() }; if (FAILED(hr)) { std::cout << "Error 0x" << std::hex << hr << " in Bootstrap initialization"; return hr; } auto mddBootstrapShutdown{ MddBootstrap::unique_mddbootstrapshutdown(reinterpret_cast(1)) }; std::cout << "hello world"; return 0; } ``` -------------------------------- ### Install multiple packages using AddPackageSetAsync Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md Installs multiple packages defined within a PackageSet object. The set can contain a mix of local and remote URIs. ```c# void Install() { var packageSet = new PackageSet() { Items = { new PackageSetItem() { PackageUri = new Uri("c:\\contoso\\muffin-1.2.3.4.msix") }, { new PackageSetItem() { PackageUri = new Uri("https://contoso.com/waffle-2.4.6.8.msix") } }; var packageDeploymentManager = PackageDeploymentManager.GetDefault(); var options = new AddPackageOptions(); var deploymentResult = await packageDeploymentManager.AddPackageByUriAsync(packageSet, options); if (deplymentResult.Status == PackageDeploymentStatus.CompletedSuccess) { Console.WriteLine("OK"); } else { Console.WriteLine("Error:{} ExtendedError:{} {}", deploymentResult.Error.HResult, deploymentResult.ExtendedError.HResult, deploymentResult.ErrorText); } } ``` -------------------------------- ### Run HelloWorld Tests - Success Expected Source: https://github.com/microsoft/windowsappsdk/blob/main/test/DynamicDependency/ManualTest/README.md Executes HelloWorld tests with specified parameters to verify successful Dynamic Dependencies initialization. The target version is set via the R variable. ```batch SET D=BuildOutput\Debug\x64 SET HWA=HelloWorldAdvancedC HelloWorldAdvancedCPP HelloWorldAdvancedCS SET R=0x00010001 "" 1000.516.2156.0 FOR %f IN (%HWA%) DO %D%\%f\%f.exe %R% ``` ```text Bootstrap.Initialize(00010001, "", 1000.516.2156.0)... Hello World! ``` -------------------------------- ### Uninstall Previous Windows App SDK Templates Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/Dotnet/README.md Removes any previously installed version of the Windows App SDK .NET templates. This ensures a clean installation of the new local package. ```shell dotnet new uninstall Microsoft.WindowsAppSDK.WinUI.CSharp.Templates ``` -------------------------------- ### Is*Ready() Methods Source: https://github.com/microsoft/windowsappsdk/blob/main/specs/packagemanager/PackageManagement.md Explains the purpose and conditions for using the Is*Ready() methods in the deployment API. ```APIDOC ## Is*Ready() Methods ### Description Is*Ready() methods determine if the target is installed (registered) and ready for use. Reasons why a package is not ready can include: * The package is not present on the machine * The package is present on the machine but not registered for the user * The package is registered for the user but is not in a healthy status e.g. its Package.Status=Tampered Is*Ready() methods are a quick test to determine if more (costly) work is needed before the target can be used. ``` -------------------------------- ### Build and Install LocalDev VSIX with Specific Windows App SDK Version Source: https://github.com/microsoft/windowsappsdk/blob/main/dev/Templates/VSIX/build-local-VSIX-package/build-local-VSIX-package.md Builds the LocalDev VSIX package and installs it, while also specifying a particular Windows App SDK version for package-realistic testing. ```powershell .\Build-VSIX.ps1 -Deployment LocalDev -WindowsAppSDKVersion "1.8.260317003" ```