From cc9831c137c1eae02e541cfd81da7797f7a56419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Mon, 27 Jan 2025 10:01:05 +0100 Subject: [PATCH 001/128] Add Appium capabilities to speed up tests --- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 8 ++++++++ src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 3 +++ 2 files changed, 11 insertions(+) diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index d41c5027294f..6a1a99267768 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -96,6 +96,14 @@ private static AppiumOptions GetOptions(IConfig config) options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppActivity, $"{appId}.MainActivity"); } + // The UiAutomator2 driver continuously checks for toast messages, consuming valuable CPU cycles. + // Because our tests don’t require this feature, disable it to improve performance and consistency, especially in scrolling actions. + options.AddAdditionalAppiumOption("disableAndroidWatchers", "true"); + + // Compresses the Android layout hierarchy, simplifying the XML structure and speeding up XPath queries. + // This reduces the time it takes to retrieve page sources, improving overall test speed. + options.AddAdditionalAppiumOption("ignoreUnimportantViews", "true"); + return options; } } diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index b184b38e11b2..dfa26ea755ea 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -77,6 +77,9 @@ private static AppiumOptions GetOptions(IConfig config) { "env", args! } }); + // It can be faster for Appium to deal with the app hierarchy internally as JSON, rather than XML. + config.SetProperty("useJSONSource", "true"); + return options; } } From d77005017740b1f6aaf691313bb03249f7b5aa16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Tue, 28 Jan 2025 12:59:08 +0100 Subject: [PATCH 002/128] By current queries, cannot compresses the Android layout hierarchy --- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index 6a1a99267768..e51fbffa007e 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -100,10 +100,6 @@ private static AppiumOptions GetOptions(IConfig config) // Because our tests don’t require this feature, disable it to improve performance and consistency, especially in scrolling actions. options.AddAdditionalAppiumOption("disableAndroidWatchers", "true"); - // Compresses the Android layout hierarchy, simplifying the XML structure and speeding up XPath queries. - // This reduces the time it takes to retrieve page sources, improving overall test speed. - options.AddAdditionalAppiumOption("ignoreUnimportantViews", "true"); - return options; } } From cb62ca22c65dfeac43c4f3e460c40b2cd9cf4c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Thu, 30 Jan 2025 14:58:42 +0100 Subject: [PATCH 003/128] Added headless capability to Android and iOS --- eng/devices/android.cake | 3 +++ eng/devices/ios.cake | 1 + src/Controls/tests/TestCases.Shared.Tests/UITest.cs | 2 ++ src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 8 ++++++++ src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 8 ++++++++ 5 files changed, 22 insertions(+) diff --git a/eng/devices/android.cake b/eng/devices/android.cake index 6010f4aff5c3..654d713afb2b 100644 --- a/eng/devices/android.cake +++ b/eng/devices/android.cake @@ -600,6 +600,9 @@ void InstallApk(string testApp, string testAppPackageName, string testResultsDir } }; + Information("Use the Android emulators in a headless mode:"); + SetEnvironmentVariable("HEADLESS", true); + Information("The platform version to run tests:"); SetEnvironmentVariable("DEVICE_SKIN", skin); diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake index ca99cc177447..887bce90f73a 100644 --- a/eng/devices/ios.cake +++ b/eng/devices/ios.cake @@ -430,6 +430,7 @@ void InstallIpa(string testApp, string testAppPackageName, string testDevice, st SetEnvironmentVariable("DEVICE_UDID", deviceToRun); SetEnvironmentVariable("DEVICE_NAME", DEVICE_NAME); SetEnvironmentVariable("PLATFORM_VERSION", iosVersionToRun); + SetEnvironmentVariable("HEADLESS", true); } } diff --git a/src/Controls/tests/TestCases.Shared.Tests/UITest.cs b/src/Controls/tests/TestCases.Shared.Tests/UITest.cs index 96e54b368181..8061189ecacf 100644 --- a/src/Controls/tests/TestCases.Shared.Tests/UITest.cs +++ b/src/Controls/tests/TestCases.Shared.Tests/UITest.cs @@ -60,11 +60,13 @@ public override IConfig GetTestConfig() config.SetProperty("DeviceName", Environment.GetEnvironmentVariable("DEVICE_SKIN") ?? ""); config.SetProperty("PlatformVersion", Environment.GetEnvironmentVariable("PLATFORM_VERSION") ?? ""); config.SetProperty("Udid", Environment.GetEnvironmentVariable("DEVICE_UDID") ?? ""); + config.SetProperty("Headless", Environment.GetEnvironmentVariable("HEADLESS") ?? ""); break; case TestDevice.iOS: config.SetProperty("DeviceName", Environment.GetEnvironmentVariable("DEVICE_NAME") ?? "iPhone Xs"); config.SetProperty("PlatformVersion", Environment.GetEnvironmentVariable("PLATFORM_VERSION") ?? "18.0"); config.SetProperty("Udid", Environment.GetEnvironmentVariable("DEVICE_UDID") ?? ""); + config.SetProperty("Headless", Environment.GetEnvironmentVariable("HEADLESS") ?? ""); break; case TestDevice.Windows: var appProjectFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "..\\..\\..\\Controls.TestCases.HostApp"); diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index e51fbffa007e..5586fe37ef6d 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -95,6 +95,14 @@ private static AppiumOptions GetOptions(IConfig config) options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppPackage, appId); options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppActivity, $"{appId}.MainActivity"); } + + var headless = config.GetProperty("Headless"); + if (!string.IsNullOrWhiteSpace(headless)) + { + // Appium has the ability to start Android emulators in a "headless" mode. + // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. + options.AddAdditionalAppiumOption("isHeadless", true); + } // The UiAutomator2 driver continuously checks for toast messages, consuming valuable CPU cycles. // Because our tests don’t require this feature, disable it to improve performance and consistency, especially in scrolling actions. diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index dfa26ea755ea..695d511fc0e5 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -79,6 +79,14 @@ private static AppiumOptions GetOptions(IConfig config) // It can be faster for Appium to deal with the app hierarchy internally as JSON, rather than XML. config.SetProperty("useJSONSource", "true"); + + var headless = config.GetProperty("Headless"); + if (!string.IsNullOrWhiteSpace(headless)) + { + // Appium has the ability to start iOS simulators in a "headless" mode. + // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. + options.AddAdditionalAppiumOption("isHeadless", true); + } return options; } From 9b970bdcdae846195ae6e960df05c6093893b7ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Thu, 30 Jan 2025 16:33:34 +0100 Subject: [PATCH 004/128] Fix the build --- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 5 +++-- src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index 5586fe37ef6d..c308afd5d133 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -96,8 +96,9 @@ private static AppiumOptions GetOptions(IConfig config) options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppActivity, $"{appId}.MainActivity"); } - var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(headless)) + var headless = config.GetProperty("Headless"); + + if (headless) { // Appium has the ability to start Android emulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index 695d511fc0e5..164932cf3644 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -80,8 +80,9 @@ private static AppiumOptions GetOptions(IConfig config) // It can be faster for Appium to deal with the app hierarchy internally as JSON, rather than XML. config.SetProperty("useJSONSource", "true"); - var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(headless)) + var headless = config.GetProperty("Headless"); + + if (headless) { // Appium has the ability to start iOS simulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. From bafb48a97da33300146e177b76728d82b273a266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Thu, 30 Jan 2025 23:01:02 +0100 Subject: [PATCH 005/128] More changes --- eng/devices/android.cake | 2 +- eng/devices/ios.cake | 2 +- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 3 +-- src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 5 ++--- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/eng/devices/android.cake b/eng/devices/android.cake index 654d713afb2b..a6598aa1063a 100644 --- a/eng/devices/android.cake +++ b/eng/devices/android.cake @@ -601,7 +601,7 @@ void InstallApk(string testApp, string testAppPackageName, string testResultsDir }; Information("Use the Android emulators in a headless mode:"); - SetEnvironmentVariable("HEADLESS", true); + SetEnvironmentVariable("HEADLESS", "enabled"); Information("The platform version to run tests:"); SetEnvironmentVariable("DEVICE_SKIN", skin); diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake index 887bce90f73a..2db81fb3ddbf 100644 --- a/eng/devices/ios.cake +++ b/eng/devices/ios.cake @@ -430,7 +430,7 @@ void InstallIpa(string testApp, string testAppPackageName, string testDevice, st SetEnvironmentVariable("DEVICE_UDID", deviceToRun); SetEnvironmentVariable("DEVICE_NAME", DEVICE_NAME); SetEnvironmentVariable("PLATFORM_VERSION", iosVersionToRun); - SetEnvironmentVariable("HEADLESS", true); + SetEnvironmentVariable("HEADLESS", "enabled"); } } diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index c308afd5d133..49776de20c12 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -97,8 +97,7 @@ private static AppiumOptions GetOptions(IConfig config) } var headless = config.GetProperty("Headless"); - - if (headless) + if (!string.IsNullOrWhiteSpace(appId)) { // Appium has the ability to start Android emulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index 164932cf3644..22050b93ebfa 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -80,9 +80,8 @@ private static AppiumOptions GetOptions(IConfig config) // It can be faster for Appium to deal with the app hierarchy internally as JSON, rather than XML. config.SetProperty("useJSONSource", "true"); - var headless = config.GetProperty("Headless"); - - if (headless) + var headless = config.GetProperty("Headless"); + if (!string.IsNullOrWhiteSpace(appId)) { // Appium has the ability to start iOS simulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. From b3a7bb39d1bff66f5005ed23f564c18b261861ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Thu, 30 Jan 2025 23:24:38 +0100 Subject: [PATCH 006/128] More fixes --- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 2 +- src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index 49776de20c12..fe56a02d794b 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -97,7 +97,7 @@ private static AppiumOptions GetOptions(IConfig config) } var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(appId)) + if (!string.IsNullOrWhiteSpace(headless)) { // Appium has the ability to start Android emulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index 22050b93ebfa..695d511fc0e5 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -81,7 +81,7 @@ private static AppiumOptions GetOptions(IConfig config) config.SetProperty("useJSONSource", "true"); var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(appId)) + if (!string.IsNullOrWhiteSpace(headless)) { // Appium has the ability to start iOS simulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. From 59828a9a9304f274c815a075454d94618ae51662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Fri, 31 Jan 2025 00:40:33 +0100 Subject: [PATCH 007/128] More changes --- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index fe56a02d794b..5586fe37ef6d 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -96,7 +96,7 @@ private static AppiumOptions GetOptions(IConfig config) options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppActivity, $"{appId}.MainActivity"); } - var headless = config.GetProperty("Headless"); + var headless = config.GetProperty("Headless"); if (!string.IsNullOrWhiteSpace(headless)) { // Appium has the ability to start Android emulators in a "headless" mode. From c07103458ae2b043d663fcedb720116c0780459a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Mon, 10 Feb 2025 13:38:05 +0100 Subject: [PATCH 008/128] More changes based on feedback --- eng/devices/android.cake | 2 +- eng/devices/ios.cake | 2 +- eng/pipelines/common/ui-tests-build-sample.yml | 1 + eng/pipelines/common/ui-tests-steps.yml | 6 ++++++ eng/pipelines/common/ui-tests.yml | 4 ++++ src/Controls/tests/TestCases.Shared.Tests/UITest.cs | 4 ++-- src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs | 4 ++-- src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 6 +++--- 8 files changed, 20 insertions(+), 9 deletions(-) diff --git a/eng/devices/android.cake b/eng/devices/android.cake index a6598aa1063a..654d713afb2b 100644 --- a/eng/devices/android.cake +++ b/eng/devices/android.cake @@ -601,7 +601,7 @@ void InstallApk(string testApp, string testAppPackageName, string testResultsDir }; Information("Use the Android emulators in a headless mode:"); - SetEnvironmentVariable("HEADLESS", "enabled"); + SetEnvironmentVariable("HEADLESS", true); Information("The platform version to run tests:"); SetEnvironmentVariable("DEVICE_SKIN", skin); diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake index 2db81fb3ddbf..887bce90f73a 100644 --- a/eng/devices/ios.cake +++ b/eng/devices/ios.cake @@ -430,7 +430,7 @@ void InstallIpa(string testApp, string testAppPackageName, string testDevice, st SetEnvironmentVariable("DEVICE_UDID", deviceToRun); SetEnvironmentVariable("DEVICE_NAME", DEVICE_NAME); SetEnvironmentVariable("PLATFORM_VERSION", iosVersionToRun); - SetEnvironmentVariable("HEADLESS", "enabled"); + SetEnvironmentVariable("HEADLESS", true); } } diff --git a/eng/pipelines/common/ui-tests-build-sample.yml b/eng/pipelines/common/ui-tests-build-sample.yml index 33053c23cbbd..0d22512b598a 100644 --- a/eng/pipelines/common/ui-tests-build-sample.yml +++ b/eng/pipelines/common/ui-tests-build-sample.yml @@ -10,6 +10,7 @@ parameters: skipProvisioning: true configuration : "Release" testFilter: '' + headless: true runtimeVariant: 'Mono' steps: diff --git a/eng/pipelines/common/ui-tests-steps.yml b/eng/pipelines/common/ui-tests-steps.yml index 6a71d5fa9275..2a37016176cf 100644 --- a/eng/pipelines/common/ui-tests-steps.yml +++ b/eng/pipelines/common/ui-tests-steps.yml @@ -10,6 +10,7 @@ parameters: configuration : "Release" runtimeVariant : "Mono" testFilter: '' + headless: true testConfigurationArgs: '' skipProvisioning: true @@ -126,6 +127,11 @@ steps: $command += " --test-filter ""$testFilter""" } + $headless = ${{ parameters.$headless }} + if ($headless) { + $command += " --headless ""$headless""" + } + Write-Host "Running command: $command" Invoke-Expression $command diff --git a/eng/pipelines/common/ui-tests.yml b/eng/pipelines/common/ui-tests.yml index 23ac76bde0a6..9a2f4cb337e2 100644 --- a/eng/pipelines/common/ui-tests.yml +++ b/eng/pipelines/common/ui-tests.yml @@ -126,6 +126,7 @@ stages: provisionatorChannel: ${{ parameters.provisionatorChannel }} agentPoolAccessToken: ${{ parameters.agentPoolAccessToken }} testFilter: $(CATEGORYGROUP) + headless: ${{ parameters.headless }} skipProvisioning: ${{ parameters.skipProvisioning }} - stage: ios_ui_tests_mono @@ -168,6 +169,7 @@ stages: agentPoolAccessToken: ${{ parameters.agentPoolAccessToken }} runtimeVariant : "Mono" testFilter: $(CATEGORYGROUP) + headless: ${{ parameters.headless }} skipProvisioning: ${{ parameters.skipProvisioning }} - stage: ios_ui_tests_mono_cv2 @@ -205,6 +207,7 @@ stages: agentPoolAccessToken: ${{ parameters.agentPoolAccessToken }} runtimeVariant : "Mono" testFilter: "CollectionView" + headless: ${{ parameters.headless }} testConfigurationArgs: "CollectionView2" skipProvisioning: ${{ parameters.skipProvisioning }} @@ -249,6 +252,7 @@ stages: agentPoolAccessToken: ${{ parameters.agentPoolAccessToken }} runtimeVariant : "NativeAOT" testFilter: $(CATEGORYGROUP) + headless: ${{ parameters.headless }} skipProvisioning: ${{ parameters.skipProvisioning }} - stage: winui_ui_tests diff --git a/src/Controls/tests/TestCases.Shared.Tests/UITest.cs b/src/Controls/tests/TestCases.Shared.Tests/UITest.cs index 8061189ecacf..d18b3b3891bd 100644 --- a/src/Controls/tests/TestCases.Shared.Tests/UITest.cs +++ b/src/Controls/tests/TestCases.Shared.Tests/UITest.cs @@ -60,13 +60,13 @@ public override IConfig GetTestConfig() config.SetProperty("DeviceName", Environment.GetEnvironmentVariable("DEVICE_SKIN") ?? ""); config.SetProperty("PlatformVersion", Environment.GetEnvironmentVariable("PLATFORM_VERSION") ?? ""); config.SetProperty("Udid", Environment.GetEnvironmentVariable("DEVICE_UDID") ?? ""); - config.SetProperty("Headless", Environment.GetEnvironmentVariable("HEADLESS") ?? ""); + config.SetProperty("Headless", bool.Parse(Environment.GetEnvironmentVariable("HEADLESS") ?? "false")); break; case TestDevice.iOS: config.SetProperty("DeviceName", Environment.GetEnvironmentVariable("DEVICE_NAME") ?? "iPhone Xs"); config.SetProperty("PlatformVersion", Environment.GetEnvironmentVariable("PLATFORM_VERSION") ?? "18.0"); config.SetProperty("Udid", Environment.GetEnvironmentVariable("DEVICE_UDID") ?? ""); - config.SetProperty("Headless", Environment.GetEnvironmentVariable("HEADLESS") ?? ""); + config.SetProperty("Headless", bool.Parse(Environment.GetEnvironmentVariable("HEADLESS") ?? "false")); break; case TestDevice.Windows: var appProjectFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "..\\..\\..\\Controls.TestCases.HostApp"); diff --git a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs index 5586fe37ef6d..6fc7892da896 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumAndroidApp.cs @@ -96,8 +96,8 @@ private static AppiumOptions GetOptions(IConfig config) options.AddAdditionalAppiumOption(AndroidMobileCapabilityType.AppActivity, $"{appId}.MainActivity"); } - var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(headless)) + var headless = config.GetProperty("Headless"); + if (headless) { // Appium has the ability to start Android emulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index 695d511fc0e5..f739c0fe66e6 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -79,9 +79,9 @@ private static AppiumOptions GetOptions(IConfig config) // It can be faster for Appium to deal with the app hierarchy internally as JSON, rather than XML. config.SetProperty("useJSONSource", "true"); - - var headless = config.GetProperty("Headless"); - if (!string.IsNullOrWhiteSpace(headless)) + + var headless = config.GetProperty("Headless"); + if (headless) { // Appium has the ability to start iOS simulators in a "headless" mode. // This means that the devices won't have any graphical user interface; but they will still be running silently, testing the app. From 339f3810cda08c0da384f8eb7189f274419ce286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Mon, 10 Feb 2025 13:48:58 +0100 Subject: [PATCH 009/128] More changes --- eng/devices/android.cake | 11 ++++++----- eng/devices/ios.cake | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/eng/devices/android.cake b/eng/devices/android.cake index 654d713afb2b..2bbd828464a6 100644 --- a/eng/devices/android.cake +++ b/eng/devices/android.cake @@ -29,6 +29,7 @@ var androidAvd = "DEVICE_TESTS_EMULATOR"; var androidAvdImage = ""; var deviceArch = ""; var androidVersion = Argument("apiversion", EnvironmentVariable("ANDROID_PLATFORM_VERSION") ?? DefaultApiLevel.ToString()); +var headless = Argument("headless", EnvironmentVariable("HEADLESS") ?? false); // Directory setup var binlogDirectory = DetermineBinlogDirectory(projectPath, binlogArg)?.FullPath; @@ -114,7 +115,7 @@ Task("uitest-prepare") .IsDependentOn("Setup") .Does(() => { - ExecutePrepareUITests(projectPath, testAppProjectPath, testAppPackageName, testDevice, testResultsPath, binlogDirectory, configuration, targetFramework, "", androidVersion, dotnetToolPath, testAppInstrumentation); + ExecutePrepareUITests(projectPath, testAppProjectPath, testAppPackageName, testDevice, testResultsPath, binlogDirectory, configuration, targetFramework, "", androidVersion, dotnetToolPath, testAppInstrumentation, headless); }); Task("uitest") @@ -254,7 +255,7 @@ void ExecuteBuildUITestApp(string appProject, string device, string binDir, stri Information("UI Test app build completed."); } -void ExecutePrepareUITests(string project, string app, string appPackageName, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath, string instrumentation) +void ExecutePrepareUITests(string project, string app, string appPackageName, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath, string instrumentation, bool headless) { string platform = "android"; Information("Preparing UI Tests..."); @@ -284,7 +285,7 @@ void ExecutePrepareUITests(string project, string app, string appPackageName, st Information($"Testing App: {testApp}"); Information($"Results Directory: {resultsDir}"); - InstallApk(testApp, appPackageName, resultsDir, deviceSkin); + InstallApk(testApp, appPackageName, resultsDir, deviceSkin, headless); } void ExecuteUITests(string project, string app, string appPackageName, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath, string instrumentation) @@ -547,7 +548,7 @@ void WriteLogCat(string filename = null) Information("Logcat written to {0}", location); } -void InstallApk(string testApp, string testAppPackageName, string testResultsDirectory, string skin) +void InstallApk(string testApp, string testAppPackageName, string testResultsDirectory, string skin, bool headless) { var installadbSettings = new AdbToolSettings { SdkRoot = androidSdkRoot }; if (!string.IsNullOrEmpty(DEVICE_UDID)) @@ -601,7 +602,7 @@ void InstallApk(string testApp, string testAppPackageName, string testResultsDir }; Information("Use the Android emulators in a headless mode:"); - SetEnvironmentVariable("HEADLESS", true); + SetEnvironmentVariable("HEADLESS", headless); Information("The platform version to run tests:"); SetEnvironmentVariable("DEVICE_SKIN", skin); diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake index 887bce90f73a..ab73c26dd1d2 100644 --- a/eng/devices/ios.cake +++ b/eng/devices/ios.cake @@ -20,6 +20,7 @@ var deviceCleanupEnabled = Argument("cleanup", true); // Device details var udid = Argument("udid", EnvironmentVariable("IOS_SIMULATOR_UDID") ?? ""); var iosVersion = Argument("apiversion", EnvironmentVariable("IOS_PLATFORM_VERSION") ?? DefaultVersion); +var headless = Argument("headless", EnvironmentVariable("HEADLESS") ?? false); // Directory setup var binlogDirectory = DetermineBinlogDirectory(projectPath, binlogArg)?.FullPath; @@ -103,7 +104,7 @@ Task("uitest-build") Task("uitest-prepare") .Does(() => { - ExecutePrepareUITests(projectPath, testAppProjectPath, testDevice, testResultsPath, binlogDirectory, configuration, targetFramework, runtimeIdentifier, iosVersion, dotnetToolPath); + ExecutePrepareUITests(projectPath, testAppProjectPath, testDevice, testResultsPath, binlogDirectory, configuration, targetFramework, runtimeIdentifier, iosVersion, dotnetToolPath, headless); }); Task("uitest") @@ -200,7 +201,7 @@ void ExecuteTests(string project, string device, string resultsDir, string confi Information("Testing completed."); } -void ExecutePrepareUITests(string project, string app, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath) +void ExecutePrepareUITests(string project, string app, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath, bool headless) { Information("Preparing UI Tests..."); Information($"Testing Device: {device}"); @@ -216,7 +217,7 @@ void ExecutePrepareUITests(string project, string app, string device, string res throw new Exception("UI Test application path not specified."); } - InstallIpa(testApp, "", device, resultsDir, ver, toolPath); + InstallIpa(testApp, "", device, resultsDir, ver, toolPath, headless); } void ExecuteUITests(string project, string app, string device, string resultsDir, string binDir, string config, string tfm, string rid, string ver, string toolPath) @@ -359,7 +360,7 @@ string GetDefaultRuntimeIdentifier(string testDeviceIdentifier) : $"ios-arm64"; } -void InstallIpa(string testApp, string testAppPackageName, string testDevice, string testResultsDirectory, string version, string toolPath) +void InstallIpa(string testApp, string testAppPackageName, string testDevice, string testResultsDirectory, string version, string toolPath, bool headless) { Information("Install with xharness: {0} testDevice:{1}", testApp, testDevice); var settings = new DotNetToolSettings @@ -430,7 +431,7 @@ void InstallIpa(string testApp, string testAppPackageName, string testDevice, st SetEnvironmentVariable("DEVICE_UDID", deviceToRun); SetEnvironmentVariable("DEVICE_NAME", DEVICE_NAME); SetEnvironmentVariable("PLATFORM_VERSION", iosVersionToRun); - SetEnvironmentVariable("HEADLESS", true); + SetEnvironmentVariable("HEADLESS", headless); } } From 2ca3d14d72b7084350473423ccc4e2aa419c3eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Mon, 10 Feb 2025 14:04:02 +0100 Subject: [PATCH 010/128] More changes --- eng/devices/android.cake | 4 ++-- eng/devices/ios.cake | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/eng/devices/android.cake b/eng/devices/android.cake index 2bbd828464a6..910b1671d488 100644 --- a/eng/devices/android.cake +++ b/eng/devices/android.cake @@ -29,7 +29,7 @@ var androidAvd = "DEVICE_TESTS_EMULATOR"; var androidAvdImage = ""; var deviceArch = ""; var androidVersion = Argument("apiversion", EnvironmentVariable("ANDROID_PLATFORM_VERSION") ?? DefaultApiLevel.ToString()); -var headless = Argument("headless", EnvironmentVariable("HEADLESS") ?? false); +var headless = Argument("headless", EnvironmentVariable("HEADLESS", false)); // Directory setup var binlogDirectory = DetermineBinlogDirectory(projectPath, binlogArg)?.FullPath; @@ -602,7 +602,7 @@ void InstallApk(string testApp, string testAppPackageName, string testResultsDir }; Information("Use the Android emulators in a headless mode:"); - SetEnvironmentVariable("HEADLESS", headless); + SetEnvironmentVariable("HEADLESS", headless.ToString()); Information("The platform version to run tests:"); SetEnvironmentVariable("DEVICE_SKIN", skin); diff --git a/eng/devices/ios.cake b/eng/devices/ios.cake index ab73c26dd1d2..62d9b63c9fec 100644 --- a/eng/devices/ios.cake +++ b/eng/devices/ios.cake @@ -20,7 +20,7 @@ var deviceCleanupEnabled = Argument("cleanup", true); // Device details var udid = Argument("udid", EnvironmentVariable("IOS_SIMULATOR_UDID") ?? ""); var iosVersion = Argument("apiversion", EnvironmentVariable("IOS_PLATFORM_VERSION") ?? DefaultVersion); -var headless = Argument("headless", EnvironmentVariable("HEADLESS") ?? false); +var headless = Argument("headless", EnvironmentVariable("HEADLESS", false)); // Directory setup var binlogDirectory = DetermineBinlogDirectory(projectPath, binlogArg)?.FullPath; @@ -431,7 +431,7 @@ void InstallIpa(string testApp, string testAppPackageName, string testDevice, st SetEnvironmentVariable("DEVICE_UDID", deviceToRun); SetEnvironmentVariable("DEVICE_NAME", DEVICE_NAME); SetEnvironmentVariable("PLATFORM_VERSION", iosVersionToRun); - SetEnvironmentVariable("HEADLESS", headless); + SetEnvironmentVariable("HEADLESS", headless.ToString()); } } From 47e4d5fe026cb2439c0ae007fea8f6414ed6b0b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Su=C3=A1rez?= Date: Tue, 17 Jun 2025 14:15:34 +0200 Subject: [PATCH 011/128] Fix mistake --- eng/pipelines/common/ui-tests-steps.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/common/ui-tests-steps.yml b/eng/pipelines/common/ui-tests-steps.yml index e4dffd5c0556..a9a7b2b7a27e 100644 --- a/eng/pipelines/common/ui-tests-steps.yml +++ b/eng/pipelines/common/ui-tests-steps.yml @@ -131,7 +131,7 @@ steps: $command += " --test-filter ""$testFilter""" } - $headless = ${{ parameters.$headless }} + $headless = ${{ parameters.headless }} if ($headless) { $command += " --headless ""$headless""" } From 5b30e6e67c7eb02bbff76daebf174ca87c49e4e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Sua=CC=81rez?= Date: Wed, 22 Oct 2025 13:55:28 +0200 Subject: [PATCH 012/128] Added capabilities to get Xcode logs in the Appium server output --- src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs index 3e65dac2e410..beeb931c4bf1 100644 --- a/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs +++ b/src/TestUtils/src/UITest.Appium/AppiumIOSApp.cs @@ -89,7 +89,13 @@ private static AppiumOptions GetOptions(IConfig config) // XCTest requires the app's main thread to be idling in order to execute any action on it, so WDA might not even start/freeze if the app under test is constantly hogging the main thread. // The default value is 10 (seconds). options.AddAdditionalAppiumOption("appium:waitForIdleTimeout", 5); - + + // Shows the Xcode build logs in the Appium server output. + options.AddAdditionalAppiumOption("showXcodeLog", true); + + // Shows device/system logs from the iOS simulator or real device. + options.AddAdditionalAppiumOption("showIOSLog", true); + return options; } } From 0811e86bfb2590a8d67ef6c2fd1a47027e355e0d Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 16:47:53 +0000 Subject: [PATCH 013/128] [ci] Update net10 arcade (#32574) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update net10 arcade * [ci]Don´t bump sdk --- NuGet.config | 3 +++ eng/common/PSScriptAnalyzerSettings.psd1 | 2 +- eng/common/SetupNugetSources.ps1 | 17 +++++++++++++++-- eng/common/SetupNugetSources.sh | 17 +++++++++++++++-- .../core-templates/job/source-index-stage1.yml | 2 +- .../steps/enable-internal-runtimes.yml | 2 +- .../steps/get-federated-access-token.yml | 2 +- .../core-templates/steps/install-microbuild.yml | 15 +++++++-------- .../steps/publish-build-artifacts.yml | 2 +- .../core-templates/steps/retain-build.yml | 2 +- .../core-templates/steps/source-build.yml | 2 +- .../core-templates/variables/pool-providers.yml | 2 +- eng/common/darc-init.ps1 | 2 +- eng/common/dotnet-install.cmd | 2 +- eng/common/init-tools-native.cmd | 2 +- eng/common/loc/P22DotNetHtmlLocalization.lss | 2 +- eng/common/msbuild.ps1 | 2 +- eng/common/sdl/NuGet.config | 2 +- eng/common/sdl/sdl.ps1 | 2 +- .../templates-official/jobs/source-build.yml | 2 +- .../post-build/common-variables.yml | 2 +- .../post-build/setup-maestro-vars.yml | 2 +- .../steps/enable-internal-sources.yml | 2 +- .../steps/get-federated-access-token.yml | 2 +- .../variables/pool-providers.yml | 2 +- .../variables/sdl-variables.yml | 2 +- eng/common/templates/jobs/source-build.yml | 2 +- .../templates/post-build/common-variables.yml | 2 +- eng/common/templates/post-build/post-build.yml | 2 +- .../templates/post-build/setup-maestro-vars.yml | 2 +- .../templates/steps/enable-internal-sources.yml | 2 +- .../steps/get-federated-access-token.yml | 2 +- .../steps/publish-pipeline-artifacts.yml | 2 +- global.json | 4 ++-- 34 files changed, 71 insertions(+), 43 deletions(-) diff --git a/NuGet.config b/NuGet.config index 17735bc3020c..752fe77e3232 100644 --- a/NuGet.config +++ b/NuGet.config @@ -4,6 +4,9 @@ + + + diff --git a/eng/common/PSScriptAnalyzerSettings.psd1 b/eng/common/PSScriptAnalyzerSettings.psd1 index fc7eafc265b7..4c1ea7c98ea4 100644 --- a/eng/common/PSScriptAnalyzerSettings.psd1 +++ b/eng/common/PSScriptAnalyzerSettings.psd1 @@ -8,4 +8,4 @@ 'PSStandardDSCFunctionsInResource', 'PSUseIdenticalMandatoryParametersForDSC', 'PSUseIdenticalParametersForDSC') -} +} \ No newline at end of file diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index fc8d618014e0..65ed3a8adef0 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -1,6 +1,7 @@ # This script adds internal feeds required to build commits that depend on internal package sources. For instance, -# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables -# disabled internal Maestro (darc-int*) feeds. +# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. Similarly, +# dotnet-eng-internal and dotnet-tools-internal are added if dotnet-eng and dotnet-tools are present. +# In addition, this script also enables disabled internal Maestro (darc-int*) feeds. # # Optionally, this script also adds a credential entry for each of the internal feeds if supplied. # @@ -173,4 +174,16 @@ foreach ($dotnetVersion in $dotnetVersions) { } } +# Check for dotnet-eng and add dotnet-eng-internal if present +$dotnetEngSource = $sources.SelectSingleNode("add[@key='dotnet-eng']") +if ($dotnetEngSource -ne $null) { + AddOrEnablePackageSource -Sources $sources -DisabledPackageSources $disabledSources -SourceName "dotnet-eng-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-eng-internal/nuget/$feedSuffix" -Creds $creds -Username $userName -pwd $Password +} + +# Check for dotnet-tools and add dotnet-tools-internal if present +$dotnetToolsSource = $sources.SelectSingleNode("add[@key='dotnet-tools']") +if ($dotnetToolsSource -ne $null) { + AddOrEnablePackageSource -Sources $sources -DisabledPackageSources $disabledSources -SourceName "dotnet-tools-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-tools-internal/nuget/$feedSuffix" -Creds $creds -Username $userName -pwd $Password +} + $doc.Save($filename) diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index b97cc536379d..b2163abbe71b 100755 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -1,8 +1,9 @@ #!/usr/bin/env bash # This script adds internal feeds required to build commits that depend on internal package sources. For instance, -# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables -# disabled internal Maestro (darc-int*) feeds. +# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. Similarly, +# dotnet-eng-internal and dotnet-tools-internal are added if dotnet-eng and dotnet-tools are present. +# In addition, this script also enables disabled internal Maestro (darc-int*) feeds. # # Optionally, this script also adds a credential entry for each of the internal feeds if supplied. # @@ -173,6 +174,18 @@ for DotNetVersion in ${DotNetVersions[@]} ; do fi done +# Check for dotnet-eng and add dotnet-eng-internal if present +grep -i " /dev/null +if [ "$?" == "0" ]; then + AddOrEnablePackageSource "dotnet-eng-internal" "https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-eng-internal/nuget/$FeedSuffix" +fi + +# Check for dotnet-tools and add dotnet-tools-internal if present +grep -i " /dev/null +if [ "$?" == "0" ]; then + AddOrEnablePackageSource "dotnet-tools-internal" "https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-tools-internal/nuget/$FeedSuffix" +fi + # I want things split line by line PrevIFS=$IFS IFS=$'\n' diff --git a/eng/common/core-templates/job/source-index-stage1.yml b/eng/common/core-templates/job/source-index-stage1.yml index 95d697597aca..30530359a5d6 100644 --- a/eng/common/core-templates/job/source-index-stage1.yml +++ b/eng/common/core-templates/job/source-index-stage1.yml @@ -41,4 +41,4 @@ jobs: - template: /eng/common/core-templates/steps/source-index-stage1-publish.yml parameters: - binLogPath: ${{ parameters.binLogPath }} + binLogPath: ${{ parameters.binLogPath }} \ No newline at end of file diff --git a/eng/common/core-templates/steps/enable-internal-runtimes.yml b/eng/common/core-templates/steps/enable-internal-runtimes.yml index 2f9cf60ede61..6bdbf62ac500 100644 --- a/eng/common/core-templates/steps/enable-internal-runtimes.yml +++ b/eng/common/core-templates/steps/enable-internal-runtimes.yml @@ -29,4 +29,4 @@ steps: storageAccount: dotnetbuilds container: internal permissions: rl - is1ESPipeline: ${{ parameters.is1ESPipeline }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} \ No newline at end of file diff --git a/eng/common/core-templates/steps/get-federated-access-token.yml b/eng/common/core-templates/steps/get-federated-access-token.yml index 5307395f5981..3a4d4410c482 100644 --- a/eng/common/core-templates/steps/get-federated-access-token.yml +++ b/eng/common/core-templates/steps/get-federated-access-token.yml @@ -39,4 +39,4 @@ steps: exit 1 } Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" + Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" \ No newline at end of file diff --git a/eng/common/core-templates/steps/install-microbuild.yml b/eng/common/core-templates/steps/install-microbuild.yml index d6b9878f54db..f2248ebfd730 100644 --- a/eng/common/core-templates/steps/install-microbuild.yml +++ b/eng/common/core-templates/steps/install-microbuild.yml @@ -11,23 +11,22 @@ parameters: # Unfortunately, _SignType can't be used to exclude the use of the service connection in non-real sign scenarios. The # variable is not available in template expression. _SignType has a very large proliferation across .NET, so replacing it is tough. microbuildUseESRP: true - # Location of the MicroBuild output folder - # NOTE: There's something that relies on this being in the "default" source directory for tasks such as Signing to work properly. - microBuildOutputFolder: '$(Build.SourcesDirectory)' continueOnError: false steps: - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if eq(parameters.enableMicrobuildForMacAndLinux, 'true') }}: - # Needed to download the MicroBuild plugin nupkgs on Mac and Linux when nuget.exe is unavailable + # Installing .NET 8 is required to use the MicroBuild signing plugin on non-Windows platforms - task: UseDotNet@2 displayName: Install .NET 8.0 SDK for MicroBuild Plugin inputs: packageType: sdk version: 8.0.x - installationPath: ${{ parameters.microBuildOutputFolder }}/.dotnet - workingDirectory: ${{ parameters.microBuildOutputFolder }} + # Installing the SDK in a '.dotnet-microbuild' directory is required for signing. + # See target FindDotNetPathForMicroBuild in arcade/src/Microsoft.DotNet.Arcade.Sdk/tools/Sign.proj + # Do not remove '.dotnet-microbuild' from the path without changing the corresponding logic. + installationPath: $(Agent.TempDirectory)/.dotnet-microbuild condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT')) - script: | @@ -65,7 +64,7 @@ steps: ConnectedPMEServiceName: 248d384a-b39b-46e3-8ad5-c2c210d5e7ca env: TeamName: $(_TeamName) - MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} + MicroBuildOutputFolderOverride: $(Agent.TempDirectory)/MicroBuild SYSTEM_ACCESSTOKEN: $(System.AccessToken) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), eq(variables['Agent.Os'], 'Windows_NT'), in(variables['_SignType'], 'real', 'test')) @@ -85,7 +84,7 @@ steps: ConnectedPMEServiceName: c24de2a5-cc7a-493d-95e4-8e5ff5cad2bc env: TeamName: $(_TeamName) - MicroBuildOutputFolderOverride: ${{ parameters.microBuildOutputFolder }} + MicroBuildOutputFolderOverride: $(Agent.TempDirectory)/MicroBuild SYSTEM_ACCESSTOKEN: $(System.AccessToken) continueOnError: ${{ parameters.continueOnError }} condition: and(succeeded(), ne(variables['Agent.Os'], 'Windows_NT'), eq(variables['_SignType'], 'real')) diff --git a/eng/common/core-templates/steps/publish-build-artifacts.yml b/eng/common/core-templates/steps/publish-build-artifacts.yml index 72c1c6be0145..f24ce346684e 100644 --- a/eng/common/core-templates/steps/publish-build-artifacts.yml +++ b/eng/common/core-templates/steps/publish-build-artifacts.yml @@ -17,4 +17,4 @@ steps: parameters: is1ESPipeline: ${{ parameters.is1ESPipeline }} ${{ each parameter in parameters.args }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/core-templates/steps/retain-build.yml b/eng/common/core-templates/steps/retain-build.yml index 28f66b2a9f01..83d97a26a01f 100644 --- a/eng/common/core-templates/steps/retain-build.yml +++ b/eng/common/core-templates/steps/retain-build.yml @@ -25,4 +25,4 @@ steps: displayName: Enable permanent build retention env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - BUILD_ID: $(Build.BuildId) + BUILD_ID: $(Build.BuildId) \ No newline at end of file diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml index f828f49b8981..acf16ed34963 100644 --- a/eng/common/core-templates/steps/source-build.yml +++ b/eng/common/core-templates/steps/source-build.yml @@ -24,7 +24,7 @@ steps: # in the default public locations. internalRuntimeDownloadArgs= if [ '$(dotnetbuilds-internal-container-read-token-base64)' != '$''(dotnetbuilds-internal-container-read-token-base64)' ]; then - internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://ci.dot.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://ci.dot.net/internal --runtimesourcefeedkey '$(dotnetbuilds-internal-container-read-token-base64)' + internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://ci.dot.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://ci.dot.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' fi buildConfig=Release diff --git a/eng/common/core-templates/variables/pool-providers.yml b/eng/common/core-templates/variables/pool-providers.yml index d87b1bad60fe..41053d382a2e 100644 --- a/eng/common/core-templates/variables/pool-providers.yml +++ b/eng/common/core-templates/variables/pool-providers.yml @@ -5,4 +5,4 @@ variables: - ${{ if eq(parameters.is1ESPipeline, 'true') }}: - template: /eng/common/templates-official/variables/pool-providers.yml - ${{ else }}: - - template: /eng/common/templates/variables/pool-providers.yml + - template: /eng/common/templates/variables/pool-providers.yml \ No newline at end of file diff --git a/eng/common/darc-init.ps1 b/eng/common/darc-init.ps1 index 4978a8b01026..e33743105635 100644 --- a/eng/common/darc-init.ps1 +++ b/eng/common/darc-init.ps1 @@ -44,4 +44,4 @@ catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'Darc' -Message $_ ExitWithExitCode 1 -} +} \ No newline at end of file diff --git a/eng/common/dotnet-install.cmd b/eng/common/dotnet-install.cmd index f74c16cc8a89..b1c2642e76f7 100644 --- a/eng/common/dotnet-install.cmd +++ b/eng/common/dotnet-install.cmd @@ -1,2 +1,2 @@ @echo off -powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0dotnet-install.ps1""" %*" +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0dotnet-install.ps1""" %*" \ No newline at end of file diff --git a/eng/common/init-tools-native.cmd b/eng/common/init-tools-native.cmd index 10938a23c528..438cd548c452 100644 --- a/eng/common/init-tools-native.cmd +++ b/eng/common/init-tools-native.cmd @@ -1,3 +1,3 @@ @echo off powershell -NoProfile -NoLogo -ExecutionPolicy ByPass -command "& """%~dp0init-tools-native.ps1""" %*" -exit /b %ErrorLevel% +exit /b %ErrorLevel% \ No newline at end of file diff --git a/eng/common/loc/P22DotNetHtmlLocalization.lss b/eng/common/loc/P22DotNetHtmlLocalization.lss index 729c2b3ce9e9..5d892d619398 100644 --- a/eng/common/loc/P22DotNetHtmlLocalization.lss +++ b/eng/common/loc/P22DotNetHtmlLocalization.lss @@ -26,4 +26,4 @@ - + \ No newline at end of file diff --git a/eng/common/msbuild.ps1 b/eng/common/msbuild.ps1 index c8a6c47e28ad..f041e5ddd958 100644 --- a/eng/common/msbuild.ps1 +++ b/eng/common/msbuild.ps1 @@ -25,4 +25,4 @@ catch { ExitWithExitCode 1 } -ExitWithExitCode 0 +ExitWithExitCode 0 \ No newline at end of file diff --git a/eng/common/sdl/NuGet.config b/eng/common/sdl/NuGet.config index 1c2d223d4fae..3849bdb3cf51 100644 --- a/eng/common/sdl/NuGet.config +++ b/eng/common/sdl/NuGet.config @@ -1,4 +1,4 @@ - + diff --git a/eng/common/sdl/sdl.ps1 b/eng/common/sdl/sdl.ps1 index f356d4d50c41..648c5068d7d6 100644 --- a/eng/common/sdl/sdl.ps1 +++ b/eng/common/sdl/sdl.ps1 @@ -35,4 +35,4 @@ function Install-Gdn { } return $gdnCliPath.FullName -} +} \ No newline at end of file diff --git a/eng/common/templates-official/jobs/source-build.yml b/eng/common/templates-official/jobs/source-build.yml index abd48a0c7f4c..483e7b611f34 100644 --- a/eng/common/templates-official/jobs/source-build.yml +++ b/eng/common/templates-official/jobs/source-build.yml @@ -4,4 +4,4 @@ jobs: is1ESPipeline: true ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/post-build/common-variables.yml b/eng/common/templates-official/post-build/common-variables.yml index fbeca86bd4cd..c32fc49233f8 100644 --- a/eng/common/templates-official/post-build/common-variables.yml +++ b/eng/common/templates-official/post-build/common-variables.yml @@ -5,4 +5,4 @@ variables: is1ESPipeline: true ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/post-build/setup-maestro-vars.yml b/eng/common/templates-official/post-build/setup-maestro-vars.yml index 5b48810c1deb..024397d87864 100644 --- a/eng/common/templates-official/post-build/setup-maestro-vars.yml +++ b/eng/common/templates-official/post-build/setup-maestro-vars.yml @@ -5,4 +5,4 @@ steps: is1ESPipeline: true ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/steps/enable-internal-sources.yml b/eng/common/templates-official/steps/enable-internal-sources.yml index 628ea09704f6..e6d57182284d 100644 --- a/eng/common/templates-official/steps/enable-internal-sources.yml +++ b/eng/common/templates-official/steps/enable-internal-sources.yml @@ -4,4 +4,4 @@ steps: is1ESPipeline: true ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/steps/get-federated-access-token.yml b/eng/common/templates-official/steps/get-federated-access-token.yml index fa899fc98c2a..c8dcf6b81392 100644 --- a/eng/common/templates-official/steps/get-federated-access-token.yml +++ b/eng/common/templates-official/steps/get-federated-access-token.yml @@ -4,4 +4,4 @@ steps: is1ESPipeline: true ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/variables/pool-providers.yml b/eng/common/templates-official/variables/pool-providers.yml index 426ee65a90f7..1f308b24efc4 100644 --- a/eng/common/templates-official/variables/pool-providers.yml +++ b/eng/common/templates-official/variables/pool-providers.yml @@ -42,4 +42,4 @@ variables: False, 'NetCore1ESPool-Internal' ) - ] + ] \ No newline at end of file diff --git a/eng/common/templates-official/variables/sdl-variables.yml b/eng/common/templates-official/variables/sdl-variables.yml index b09ed50541f6..f1311bbb1b33 100644 --- a/eng/common/templates-official/variables/sdl-variables.yml +++ b/eng/common/templates-official/variables/sdl-variables.yml @@ -4,4 +4,4 @@ variables: - name: DefaultGuardianVersion value: 0.109.0 - name: GuardianPackagesConfigFile - value: $(System.DefaultWorkingDirectory)\eng\common\sdl\packages.config + value: $(System.DefaultWorkingDirectory)\eng\common\sdl\packages.config \ No newline at end of file diff --git a/eng/common/templates/jobs/source-build.yml b/eng/common/templates/jobs/source-build.yml index 81e6c4d346a2..818d4c326dbb 100644 --- a/eng/common/templates/jobs/source-build.yml +++ b/eng/common/templates/jobs/source-build.yml @@ -4,4 +4,4 @@ jobs: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/common-variables.yml b/eng/common/templates/post-build/common-variables.yml index f12f7d5cf432..7fa105875592 100644 --- a/eng/common/templates/post-build/common-variables.yml +++ b/eng/common/templates/post-build/common-variables.yml @@ -5,4 +5,4 @@ variables: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/post-build.yml b/eng/common/templates/post-build/post-build.yml index ef8cf5491137..53ede714bdd2 100644 --- a/eng/common/templates/post-build/post-build.yml +++ b/eng/common/templates/post-build/post-build.yml @@ -5,4 +5,4 @@ stages: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/setup-maestro-vars.yml b/eng/common/templates/post-build/setup-maestro-vars.yml index 37b173a8c269..a79fab5b441e 100644 --- a/eng/common/templates/post-build/setup-maestro-vars.yml +++ b/eng/common/templates/post-build/setup-maestro-vars.yml @@ -5,4 +5,4 @@ steps: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/steps/enable-internal-sources.yml b/eng/common/templates/steps/enable-internal-sources.yml index d8876717f855..5f87e9abb8aa 100644 --- a/eng/common/templates/steps/enable-internal-sources.yml +++ b/eng/common/templates/steps/enable-internal-sources.yml @@ -4,4 +4,4 @@ steps: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/steps/get-federated-access-token.yml b/eng/common/templates/steps/get-federated-access-token.yml index 44aab941f3c6..31e151d9d9e7 100644 --- a/eng/common/templates/steps/get-federated-access-token.yml +++ b/eng/common/templates/steps/get-federated-access-token.yml @@ -4,4 +4,4 @@ steps: is1ESPipeline: false ${{ each parameter in parameters }}: - ${{ parameter.key }}: ${{ parameter.value }} + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/steps/publish-pipeline-artifacts.yml b/eng/common/templates/steps/publish-pipeline-artifacts.yml index 8ffa22b80ad8..5dd698b212fc 100644 --- a/eng/common/templates/steps/publish-pipeline-artifacts.yml +++ b/eng/common/templates/steps/publish-pipeline-artifacts.yml @@ -31,4 +31,4 @@ steps: ${{ if parameters.args.parallelCount }}: parallelCount: ${{ parameters.args.parallelCount }} ${{ if parameters.args.properties }}: - properties: ${{ parameters.args.properties }} + properties: ${{ parameters.args.properties }} \ No newline at end of file diff --git a/global.json b/global.json index 34e357aaf077..81b639ab6cd5 100644 --- a/global.json +++ b/global.json @@ -5,7 +5,7 @@ "msbuild-sdks": { "MSBuild.Sdk.Extras": "3.0.44", "Microsoft.Build.NoTargets": "3.7.0", - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25523.113", - "Microsoft.DotNet.Helix.Sdk": "10.0.0-beta.25523.113" + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.25555.106", + "Microsoft.DotNet.Helix.Sdk": "10.0.0-beta.25555.106" } } From bf96ba698d8abb3b5b69396c905abc0078280b20 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 17:31:55 +0000 Subject: [PATCH 014/128] Add a new pipeline for uitests (#32592) --- eng/pipelines/ci-uitests.yml | 138 +++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 eng/pipelines/ci-uitests.yml diff --git a/eng/pipelines/ci-uitests.yml b/eng/pipelines/ci-uitests.yml new file mode 100644 index 000000000000..08804d07dd6e --- /dev/null +++ b/eng/pipelines/ci-uitests.yml @@ -0,0 +1,138 @@ +trigger: + branches: + include: + - main + - release/* + - net10.0 + tags: + include: + - '*' + paths: + include: + - '*' + exclude: + - .github/* + - docs/* + - src/Templates/* + - CODE-OF-CONDUCT.md + - CONTRIBUTING.md + - LICENSE.TXT + - PATENTS.TXT + - README.md + - THIRD-PARTY-NOTICES.TXT + +pr: + branches: + include: + - main + - release/* + - net10.0 + paths: + include: + - '*' + exclude: + - .github/* + - docs/* + - src/Templates/* + - CODE-OF-CONDUCT.md + - CONTRIBUTING.md + - LICENSE.TXT + - PATENTS.TXT + - README.md + - THIRD-PARTY-NOTICES.TXT + +variables: + - template: /eng/pipelines/common/variables.yml@self + +parameters: + + - name: UseProvisionator + type: boolean + default: false + + - name: BuildEverything + type: boolean + default: false + + - name: BuildNativeAOT + displayName: 'Build NativeAOT artifacts' + type: boolean + default: false + + - name: RunNativeAOT + displayName: 'Run NativeAOT UI Tests' + type: boolean + default: false + + - name: androidPool + type: object + default: + name: MAUI + vmImage: MAUI + + - name: androidPoolLinux + type: object + default: + name: MAUI-DNCENG + demands: + - ImageOverride -equals 1ESPT-Ubuntu22.04 + + - name: iosPool + type: object + default: + name: MAUI + vmImage: MAUI + + - name: windowsBuildPool + type: object + default: + name: $(windowsVmPool) + vmImage: $(windowsVmImage) + + - name: windowsPool + type: object + default: + name: $(windowsTestsVmPool) + vmImage: $(windowsTestsVmImage) + + - name: macosPool + type: object + default: + name: Azure Pipelines + vmImage: macOS-14 + +stages: + + - template: common/ui-tests.yml + parameters: + androidPool: ${{ parameters.androidPool }} + androidLinuxPool: ${{ parameters.androidPoolLinux }} + iosPool: ${{ parameters.iosPool }} + windowsPool: ${{ parameters.windowsPool }} + windowsBuildPool: ${{ parameters.windowsBuildPool }} + macosPool: ${{ parameters.macosPool }} + # BuildNativeAOT is false by default, but true in devdiv environment + BuildNativeAOT: ${{ or(parameters.BuildNativeAOT, and(ne(variables['Build.Reason'], 'PullRequest'), eq(variables['System.TeamProject'], 'devdiv'))) }} + RunNativeAOT: ${{ parameters.RunNativeAOT }} + ${{ if or(parameters.BuildEverything, and(ne(variables['Build.Reason'], 'PullRequest'), eq(variables['System.TeamProject'], 'devdiv'))) }}: + androidApiLevels: [ 30 ] + iosVersions: [ '18.4' ] + ${{ else }}: + androidApiLevels: [ 30 ] + iosVersions: [ '18.4' ] + ${{ if or(parameters.UseProvisionator, eq(variables['internalProvisioning'],'true') ) }}: + skipProvisioning: false + ${{ else }}: + skipProvisioning: true + projects: + - name: controls + desc: Controls + androidApiLevelsExclude: [25] # Ignore for now API25 since the runs's are not stable + android: $(System.DefaultWorkingDirectory)/src/Controls/tests/TestCases.Android.Tests/Controls.TestCases.Android.Tests.csproj + app: $(Pipeline.Workspace)/Controls.TestCases.HostApp/ + iosVersionsExclude: [ '12.4'] # Ignore iOS 12.4 while we can't make it work on CI + ios: $(System.DefaultWorkingDirectory)/src/Controls/tests/TestCases.iOS.Tests/Controls.TestCases.iOS.Tests.csproj + winui: $(System.DefaultWorkingDirectory)/src/Controls/tests/TestCases.WinUI.Tests/Controls.TestCases.WinUI.Tests.csproj + mac: $(System.DefaultWorkingDirectory)/src/Controls/tests/TestCases.Mac.Tests/Controls.TestCases.Mac.Tests.csproj + + From c1a581922bacb94b96d5761f33b1571901b01e08 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 18:31:05 +0000 Subject: [PATCH 015/128] Add variable group MAUI --- eng/pipelines/common/variables.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index 9b134ba908e7..d9cda1d0ad56 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -56,9 +56,10 @@ variables: - name: nugetMultiFeedWarnLevel value: none +- group: MAUI # This is the main MAUI variable group that contains secret for the apple certificate + # Variable groups required for all builds - ${{ if and(ne(variables['Build.DefinitionName'], 'maui-pr'), ne(variables['Build.DefinitionName'], 'dotnet-maui'), ne(variables['Build.DefinitionName'], 'maui-pr-devicetests'), ne(variables['Build.DefinitionName'], 'maui-pr-uitests')) }}: - - group: MAUI # This is the main MAUI variable group that contains secret for the apple certificate - group: maui-provisionator # This is just needed for the provisionator From 3d24f084623f1f5cf93643ee399a13d4a9fdb9d0 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 22:37:37 +0000 Subject: [PATCH 016/128] [ci] Don t push the device tests --- eng/pipelines/arcade/stage-device-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/pipelines/arcade/stage-device-tests.yml b/eng/pipelines/arcade/stage-device-tests.yml index ff766e807697..e9bb3754af8a 100644 --- a/eng/pipelines/arcade/stage-device-tests.yml +++ b/eng/pipelines/arcade/stage-device-tests.yml @@ -48,7 +48,7 @@ parameters: default: $(System.DefaultWorkingDirectory) stages: -- stage: deviceTests_ios_android +- stage: devicetests_ios_catalyst_android displayName: ${{ parameters.TargetFrameworkVersion }} ios/catalyst/android Helix Tests dependsOn: [] jobs: @@ -115,7 +115,7 @@ stages: sourceIndexParams: ${{ parameters.sourceIndexParams }} publishAssetsImmediately: true enablePublishBuildArtifacts: true - enablePublishTestResults: true + enablePublishTestResults: false workspace: clean: all jobs: From 4fcc7b2c95d23cf914482078d1e30bdabfeace96 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 22:44:31 +0000 Subject: [PATCH 017/128] [ci] The default should be not using OfficialBuildId --- eng/pipelines/arcade/variables.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/arcade/variables.yml b/eng/pipelines/arcade/variables.yml index 2b9180f72a23..00f79298d2a8 100644 --- a/eng/pipelines/arcade/variables.yml +++ b/eng/pipelines/arcade/variables.yml @@ -25,7 +25,7 @@ variables: - name: TreatWarningsAsErrors value: false - name: _OfficialBuildIdArgs - value: /p:OfficialBuildId=$(_BuildOfficalId) /p:_SkipUpdateBuildNumber=true + value: '' - name: ApiScanAppId value: cbde2fca-1ca1-47f7-8212-fcdf1a556eb2 - name: ApiScanTenantId From c47423e7c9da0693efca423473b0159bc82b4488 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 23:28:09 +0000 Subject: [PATCH 018/128] [ci] Cleanup public build --- eng/pipelines/arcade/variables.yml | 2 +- eng/pipelines/ci-uitests.yml | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/eng/pipelines/arcade/variables.yml b/eng/pipelines/arcade/variables.yml index 00f79298d2a8..4053177ef6dd 100644 --- a/eng/pipelines/arcade/variables.yml +++ b/eng/pipelines/arcade/variables.yml @@ -33,7 +33,7 @@ variables: - name: ApiScanServiceConnectionId value: 334a6802-ebad-4fb1-bc3b-105bcc70bda2 # Produce test-signed build for PR and Public builds -- ${{ if or(eq(variables['_RunAsPublic'], 'true'), eq(variables['Build.Reason'], 'PullRequest')) }}: +- ${{ if or(eq(variables['_RunAsPublic'], 'true')) }}: # needed for darc (dependency flow) publishing - name: _PublishArgs value: '' diff --git a/eng/pipelines/ci-uitests.yml b/eng/pipelines/ci-uitests.yml index 08804d07dd6e..028ee6e0a7b6 100644 --- a/eng/pipelines/ci-uitests.yml +++ b/eng/pipelines/ci-uitests.yml @@ -46,10 +46,6 @@ variables: parameters: - - name: UseProvisionator - type: boolean - default: false - - name: BuildEverything type: boolean default: false @@ -120,10 +116,6 @@ stages: ${{ else }}: androidApiLevels: [ 30 ] iosVersions: [ '18.4' ] - ${{ if or(parameters.UseProvisionator, eq(variables['internalProvisioning'],'true') ) }}: - skipProvisioning: false - ${{ else }}: - skipProvisioning: true projects: - name: controls desc: Controls From ea1d91c74f6cc72fda178e56a59c1fd5f90c774c Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Thu, 13 Nov 2025 23:29:40 +0000 Subject: [PATCH 019/128] Fix yaml --- eng/pipelines/arcade/variables.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/arcade/variables.yml b/eng/pipelines/arcade/variables.yml index 4053177ef6dd..8ad8d411b151 100644 --- a/eng/pipelines/arcade/variables.yml +++ b/eng/pipelines/arcade/variables.yml @@ -33,7 +33,7 @@ variables: - name: ApiScanServiceConnectionId value: 334a6802-ebad-4fb1-bc3b-105bcc70bda2 # Produce test-signed build for PR and Public builds -- ${{ if or(eq(variables['_RunAsPublic'], 'true')) }}: +- ${{ if eq(variables['_RunAsPublic'], 'true') }}: # needed for darc (dependency flow) publishing - name: _PublishArgs value: '' From bd07a33f654a9e942952606bd9e20203790fe231 Mon Sep 17 00:00:00 2001 From: Shane Neuville Date: Thu, 13 Nov 2025 17:41:39 -0600 Subject: [PATCH 020/128] Bump MicrosoftMauiPreviousDotNetReleasedVersion to 9.0.120 --- eng/Versions.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/Versions.props b/eng/Versions.props index 06b44171565c..f971436da55d 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -28,7 +28,7 @@ - 9.0.111 + 9.0.120 10.0.100-rtm.25523.113 $(MicrosoftNETSdkPackageVersion) From 32711991979dc6ad2a57b321ffa44531dd42db53 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 10:32:24 +0000 Subject: [PATCH 021/128] Update eng/pipelines/common/variables.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- eng/pipelines/common/variables.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index d9cda1d0ad56..d9e9059817e4 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -56,7 +56,7 @@ variables: - name: nugetMultiFeedWarnLevel value: none -- group: MAUI # This is the main MAUI variable group that contains secret for the apple certificate +- group: MAUI # This is the main MAUI variable group that contains secrets for the apple certificate # Variable groups required for all builds - ${{ if and(ne(variables['Build.DefinitionName'], 'maui-pr'), ne(variables['Build.DefinitionName'], 'dotnet-maui'), ne(variables['Build.DefinitionName'], 'maui-pr-devicetests'), ne(variables['Build.DefinitionName'], 'maui-pr-uitests')) }}: From 02a8603d5ae783290b1be01ca0cc4f560c9e77a4 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 10:46:43 +0000 Subject: [PATCH 022/128] Bump xcode --- eng/pipelines/common/variables.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index 9b134ba908e7..87e3a9fbbcda 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -8,9 +8,9 @@ variables: - name: DOTNET_VERSION value: 10.0.100-preview.2.25164.34 - name: REQUIRED_XCODE - value: 26.0.0 + value: 26.0.1 - name: DEVICETESTS_REQUIRED_XCODE - value: 26.0.0 + value: 26.0.1 - name: XCODE value: 26.0.1 - name: POWERSHELL_VERSION From 54e484431b97e938d46700b50355354f2a973e6a Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 10:46:50 +0000 Subject: [PATCH 023/128] Bump .net --- eng/pipelines/common/variables.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index 87e3a9fbbcda..bf9fece83dcc 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -6,7 +6,7 @@ variables: - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE value: true - name: DOTNET_VERSION - value: 10.0.100-preview.2.25164.34 + value: 10.0.100 - name: REQUIRED_XCODE value: 26.0.1 - name: DEVICETESTS_REQUIRED_XCODE From 68f41a058ac0ab459942d6a22d50460b0fad10e0 Mon Sep 17 00:00:00 2001 From: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com> Date: Fri, 14 Nov 2025 15:09:12 +0100 Subject: [PATCH 024/128] Removed Value property coercion in RadioButton (#32489) Eliminated the coercion logic that set RadioButton.Value to the instance when null, allowing Value to be explicitly set to null. Updated related unit test to reflect the new behavior. --- src/Controls/src/Core/RadioButton/RadioButton.cs | 6 +----- src/Controls/tests/Core.UnitTests/RadioButtonTests.cs | 10 +++++++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Controls/src/Core/RadioButton/RadioButton.cs b/src/Controls/src/Core/RadioButton/RadioButton.cs index 6feaad9381e5..0aa3d0d87fab 100644 --- a/src/Controls/src/Core/RadioButton/RadioButton.cs +++ b/src/Controls/src/Core/RadioButton/RadioButton.cs @@ -56,8 +56,7 @@ public partial class RadioButton : TemplatedView, IElementConfigurationBindable property for . public static readonly BindableProperty ValueProperty = BindableProperty.Create(nameof(Value), typeof(object), typeof(RadioButton), null, - propertyChanged: (b, o, n) => ((RadioButton)b).OnValuePropertyChanged(), - coerceValue: (b, o) => o ?? b); + propertyChanged: (b, o, n) => ((RadioButton)b).OnValuePropertyChanged()); /// Bindable property for . public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create( @@ -210,9 +209,6 @@ public RadioButton() { _platformConfigurationRegistry = new Lazy>(() => new PlatformConfigurationRegistry(this)); - - //initialize Value to prevent null value - Value = this; } /// diff --git a/src/Controls/tests/Core.UnitTests/RadioButtonTests.cs b/src/Controls/tests/Core.UnitTests/RadioButtonTests.cs index 012499a3dcd4..cf2a18aed904 100644 --- a/src/Controls/tests/Core.UnitTests/RadioButtonTests.cs +++ b/src/Controls/tests/Core.UnitTests/RadioButtonTests.cs @@ -305,15 +305,19 @@ public void GroupNullSelectionClearsAnySelection() } [Fact] - public void ValuePropertyCoercedToItselfIfSetToNull() + public void ValuePropertyCanBeSetToNull() { var radioButton = new RadioButton(); - Assert.Equal(radioButton, radioButton.Value); + Assert.Null(radioButton.Value); + + radioButton.Value = 1; + + Assert.Equal(1, radioButton.Value); radioButton.Value = null; - Assert.Equal(radioButton, radioButton.Value); + Assert.Null(radioButton.Value); } } } From 3e0e46deb2d3fe59c988f3ab581be0376a0f40bd Mon Sep 17 00:00:00 2001 From: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com> Date: Fri, 14 Nov 2025 16:32:06 +0100 Subject: [PATCH 025/128] Refactor selection limit handling in MediaPicker (#32571) Replaces direct access to options.SelectionLimit with a local variable that defaults to 1 if options is null. Updates all relevant checks and method calls to use the new variable, improving null safety and code clarity. --- src/Essentials/src/MediaPicker/MediaPicker.android.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Essentials/src/MediaPicker/MediaPicker.android.cs b/src/Essentials/src/MediaPicker/MediaPicker.android.cs index 05308853f2bb..5632c51ad6f3 100644 --- a/src/Essentials/src/MediaPicker/MediaPicker.android.cs +++ b/src/Essentials/src/MediaPicker/MediaPicker.android.cs @@ -247,7 +247,8 @@ async Task> PickMultipleUsingPhotoPicker(MediaPickerOptions opt // Android has a limitation that you need to use a different request for single and multiple picks. // If the selection limit is 1, we can use the single pick method, // otherwise we need to use the multiple pick method. - if (options.SelectionLimit == 1) + int selectionLimit = options?.SelectionLimit ?? 1; + if (selectionLimit == 1) { var singleResult = await PickUsingPhotoPicker(options, photo); return singleResult is not null ? [singleResult] : []; @@ -258,9 +259,9 @@ async Task> PickMultipleUsingPhotoPicker(MediaPickerOptions opt // Only set the limit for 2 and up. For single selection (limit == 1) is handled above, // and limit == 0 should be treated as unlimited. - if (options.SelectionLimit >= 2) + if (selectionLimit >= 2) { - pickVisualMediaRequestBuilder.SetMaxItems(options.SelectionLimit); + pickVisualMediaRequestBuilder.SetMaxItems(selectionLimit); } var pickVisualMediaRequest = pickVisualMediaRequestBuilder.Build(); From 321c6f89328500419ad5091ed40af89f3239989b Mon Sep 17 00:00:00 2001 From: Matt Mitchell Date: Fri, 14 Nov 2025 07:38:29 -0800 Subject: [PATCH 026/128] Add .azuredevops/dependabot.yml --- .azuredevops/dependabot.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .azuredevops/dependabot.yml diff --git a/.azuredevops/dependabot.yml b/.azuredevops/dependabot.yml new file mode 100644 index 000000000000..f18e60565a42 --- /dev/null +++ b/.azuredevops/dependabot.yml @@ -0,0 +1,5 @@ +version: 2 + +# Disabling dependabot on Azure DevOps as this is a mirrored repo. Updates should go through github. +enable-campaigned-updates: false +enable-security-updates: false From 3d76b55ea6470a12cf1bef3713a46f68352ae195 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 17:00:33 +0000 Subject: [PATCH 027/128] Bump device --- eng/pipelines/common/maui-templates.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/pipelines/common/maui-templates.yml b/eng/pipelines/common/maui-templates.yml index 30849005ce91..dad96c0589e8 100644 --- a/eng/pipelines/common/maui-templates.yml +++ b/eng/pipelines/common/maui-templates.yml @@ -161,7 +161,7 @@ jobs: displayName: Reset iOS simulators # TODO: pass properly device type/version from top-level yml env: - IOS_TEST_DEVICE: ios-simulator-64_18.0 + IOS_TEST_DEVICE: ios-simulator-64_18.4 - pwsh: ./build.ps1 --target=dotnet-integration-test --filter="Category=${{ RunPlatform.testName }}" --resultsfilename="integration-run-${{ RunPlatform.testName }}" --verbosity=diagnostic displayName: Run ${{ RunPlatform.testName }} templates run tests @@ -169,7 +169,7 @@ jobs: # TODO: pass properly device type/version from top-level yml ${{ if eq(RunPlatform.testName, 'RunOniOS') }}: env: - IOS_TEST_DEVICE: ios-simulator-64_18.0 + IOS_TEST_DEVICE: ios-simulator-64_18.4 - ${{ if eq(RunPlatform.testName, 'RunOniOS') }}: - pwsh: ./build.ps1 --target=Cleanup -Script eng/devices/ios.cake ---results="$(TestResultsDirectory)" ${{ parameters.cakeArgs }} From cae2ccab568311348d23e64767fef57d2a3b923f Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 17:49:17 +0000 Subject: [PATCH 028/128] Try with other variables --- eng/pipelines/arcade/variables.yml | 2 +- eng/pipelines/common/variables.yml | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/eng/pipelines/arcade/variables.yml b/eng/pipelines/arcade/variables.yml index 8ad8d411b151..a7203cf84ec4 100644 --- a/eng/pipelines/arcade/variables.yml +++ b/eng/pipelines/arcade/variables.yml @@ -45,7 +45,7 @@ variables: - name: _SignArgs value: '/p:DotNetSignType=$(_SignType) /p:TeamName=$(TeamName)' # Set up non-PR build from internal project -- ${{ if and(ne(variables['_RunAsPublic'], 'true'), ne(variables['Build.Reason'], 'PullRequest')) }}: +- ${{ if or(eq(variables['Build.DefinitionName'], 'dotnet-maui'), eq(variables['Build.DefinitionName'], 'dotnet-maui-build')) }}: # needed for darc (dependency flow) publishing - name: _PublishArgs value: >- diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index d9e9059817e4..3673f9b20ded 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -49,8 +49,6 @@ variables: value: true - name: _RunAsInternal value: false -- name: _InternalBuildArgs - value: '' - name: cfsNugetWarnLevel value: warn - name: nugetMultiFeedWarnLevel @@ -78,9 +76,7 @@ variables: - group: DotNetBuilds storage account read tokens - group: AzureDevOps-Artifact-Feeds-Pats - - name: _InternalBuildArgs - value: /p:DotNetSignType=$(_SignType) /p:TeamName=$(_TeamName) /p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER) - + - ${{ if eq(variables['Build.DefinitionName'], 'dotnet-maui') }}: - ${{ if notin(variables['Build.Reason'], 'PullRequest') }}: # Publish-Build-Assets provides: MaestroAccessToken, BotAccount-dotnet-maestro-bot-PAT From 0c36b0807fe22be1b021ec413198b160415fd3e9 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 14 Nov 2025 11:58:46 -0600 Subject: [PATCH 029/128] Add Android emulator startup pattern to common testing patterns (#32615) * Initial plan * Add Android emulator startup pattern with error checking Co-authored-by: PureWeen <5375137+PureWeen@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: PureWeen <5375137+PureWeen@users.noreply.github.com> --- .../instructions/common-testing-patterns.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/.github/instructions/common-testing-patterns.md b/.github/instructions/common-testing-patterns.md index 8c7c7aa0c3ad..1aeb8f26a80e 100644 --- a/.github/instructions/common-testing-patterns.md +++ b/.github/instructions/common-testing-patterns.md @@ -106,6 +106,57 @@ echo "Simulator is booted and ready" --- +### Android Emulator Startup with Error Checking + +**Used in**: Investigation work + +**Pattern**: +```bash +# Clean up any existing emulator processes +pkill -9 qemu-system-x86_64 2>/dev/null || true +pkill -9 emulator 2>/dev/null || true +sleep 2 + +# Restart adb server +adb kill-server && sleep 1 && adb start-server && sleep 2 + +# Start emulator (must run from SDK emulator directory to find dependencies) +cd $ANDROID_HOME/emulator && ./emulator -avd Nexus_5X_API_30 -no-snapshot-load -no-audio -no-boot-anim & + +# Wait for device to appear +echo "Waiting for device to appear..." +adb wait-for-device + +# Wait for boot to complete +echo "Waiting for boot to complete..." +until [ "$(adb shell getprop sys.boot_completed 2>/dev/null)" = "1" ]; do + sleep 2 + echo -n "." +done +echo "" + +# Get device UDID +export DEVICE_UDID=$(adb devices | grep -v "List" | grep "device" | awk '{print $1}' | head -1) + +# Verify device is ready +if [ -z "$DEVICE_UDID" ]; then + echo "❌ ERROR: Emulator started but device not found" + exit 1 +fi + +# Check API level +API_LEVEL=$(adb shell getprop ro.build.version.sdk) +echo "✅ Emulator ready: $DEVICE_UDID (API $API_LEVEL)" +``` + +**When to use**: Starting Android emulator for testing + +**Critical detail**: The emulator command must be run from `$ANDROID_HOME/emulator` directory. Running from other directories causes "Qt library not found" and "qemu-system not found" errors. + +**Available emulators**: List with `emulator -list-avds` + +--- + ## 3. Build Patterns ### Sandbox App Build (iOS) From 8a897da47e3e32b2fc6d7820b185988f9c8d1ece Mon Sep 17 00:00:00 2001 From: Thimo Date: Fri, 14 Nov 2025 21:05:08 +0100 Subject: [PATCH 030/128] =?UTF-8?q?#32624=20Rename=20.NET=20Aspire=20to=20?= =?UTF-8?q?Aspire=20in=20Aspire=20ServiceDefaults=20templat=E2=80=A6=20(#3?= =?UTF-8?q?2626)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.template.config/template.json | 6 +++--- .../src/templates/maui-aspire-servicedefaults/Extensions.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Templates/src/templates/maui-aspire-servicedefaults/.template.config/template.json b/src/Templates/src/templates/maui-aspire-servicedefaults/.template.config/template.json index cc360b6496f9..bd1a0f5f8461 100644 --- a/src/Templates/src/templates/maui-aspire-servicedefaults/.template.config/template.json +++ b/src/Templates/src/templates/maui-aspire-servicedefaults/.template.config/template.json @@ -3,16 +3,16 @@ "author": "Microsoft", "classifications": [ "MAUI", - ".NET Aspire", + "Aspire", "Cloud", "Web", "Web API", "API", "Service" ], - "name": ".NET MAUI for .NET Aspire Service Defaults", + "name": ".NET MAUI for Aspire Service Defaults", "defaultName": "MauiAspire1.ServiceDefaults", - "description": "A project template for creating a .NET Aspire service defaults project for .NET MAUI.", + "description": "A project template for creating an Aspire service defaults project for .NET MAUI.", "shortName": "maui-aspire-servicedefaults", "sourceName": "MauiAspire.1.ServiceDefaults", "preferNameDirectory": true, diff --git a/src/Templates/src/templates/maui-aspire-servicedefaults/Extensions.cs b/src/Templates/src/templates/maui-aspire-servicedefaults/Extensions.cs index 2eacc50d6db1..39e549674a17 100644 --- a/src/Templates/src/templates/maui-aspire-servicedefaults/Extensions.cs +++ b/src/Templates/src/templates/maui-aspire-servicedefaults/Extensions.cs @@ -10,7 +10,7 @@ namespace Microsoft.Extensions.Hosting; -// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. +// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry. // This project should be referenced by each service project in your solution. // To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults public static class Extensions From 3d8ecfe01d437c42a2e78cbd2906a2e8e711ce05 Mon Sep 17 00:00:00 2001 From: Rui Marinho Date: Fri, 14 Nov 2025 20:07:01 +0000 Subject: [PATCH 031/128] [ci] Fix creator --- eng/helix.proj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/helix.proj b/eng/helix.proj index aa8eebf911fb..29ccb0cf6397 100644 --- a/eng/helix.proj +++ b/eng/helix.proj @@ -4,7 +4,7 @@ $(BUILD_BUILDNUMBER) default Windows.10.Amd64.Open;osx.15.arm64.maui.open - maui + maui true sdk true From 92d532f9ac87e601ed28547485d4fc68438def94 Mon Sep 17 00:00:00 2001 From: Stephane Delcroix Date: Sat, 15 Nov 2025 16:54:15 +0100 Subject: [PATCH 032/128] [XSG] add XmlLineInfoProvider (#32530) so the exception are correctly reported --- .../src/SourceGen/ServiceProviderExtensions.cs | 17 ++++++++++++----- .../HotReloadStaticResourceException.xaml.cs | 10 +++++++++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Controls/src/SourceGen/ServiceProviderExtensions.cs b/src/Controls/src/SourceGen/ServiceProviderExtensions.cs index 208d5dbb3616..4b1117840487 100644 --- a/src/Controls/src/SourceGen/ServiceProviderExtensions.cs +++ b/src/Controls/src/SourceGen/ServiceProviderExtensions.cs @@ -44,10 +44,10 @@ static void AddServices(this INode node, IndentedTextWriter writer, string servi var parentObjects = node.ParentObjects(context).Select(v => v.ValueAccessor).ToArray(); if (parentObjects.Length == 0) parentObjects = ["null"]; - if (createAllServices - || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IProvideParentValues")!, SymbolEqualityComparer.Default) - || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IProvideValueTarget")!, SymbolEqualityComparer.Default) - || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IReferenceProvider")!, SymbolEqualityComparer.Default)) + if ( createAllServices + || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IProvideParentValues")!, SymbolEqualityComparer.Default) + || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IProvideValueTarget")!, SymbolEqualityComparer.Default) + || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IReferenceProvider")!, SymbolEqualityComparer.Default)) { var simpleValueTargetProvider = NamingHelpers.CreateUniqueVariableName(context, context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IProvideValueTarget")!); writer.WriteLine($"var {simpleValueTargetProvider} = new global::Microsoft.Maui.Controls.Xaml.Internals.SimpleValueTargetProvider("); @@ -76,7 +76,7 @@ static void AddServices(this INode node, IndentedTextWriter writer, string servi writer.WriteLine($"{serviceProviderVariableName}.Add(typeof(global::Microsoft.Maui.Controls.Xaml.IProvideValueTarget), {simpleValueTargetProvider});"); } - if (createAllServices + if ( createAllServices || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IXamlTypeResolver")!, SymbolEqualityComparer.Default)) { var nsResolver = NamingHelpers.CreateUniqueVariableName(context, context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.Internals.XmlNamespaceResolver")!); @@ -87,6 +87,13 @@ static void AddServices(this INode node, IndentedTextWriter writer, string servi writer.WriteLine($"{serviceProviderVariableName}.Add(typeof(global::Microsoft.Maui.Controls.Xaml.IXamlTypeResolver), new global::Microsoft.Maui.Controls.Xaml.Internals.XamlTypeResolver({nsResolver}, typeof({context.RootType.ToFQDisplayString()}).Assembly));"); } + if ( node is IXmlLineInfo xmlLineInfo + && ( createAllServices + || requiredServices!.Value.Contains(context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.Xaml.IXmlLineInfoProvider")!, SymbolEqualityComparer.Default))) + { + writer.WriteLine($"{serviceProviderVariableName}.Add(typeof(global::Microsoft.Maui.Controls.Xaml.IXmlLineInfoProvider), new global::Microsoft.Maui.Controls.Xaml.Internals.XmlLineInfoProvider(new global::Microsoft.Maui.Controls.Xaml.XmlLineInfo({xmlLineInfo.LineNumber}, {xmlLineInfo.LinePosition})));"); + + } } static IEnumerable ParentObjects(this INode node, SourceGenContext context) diff --git a/src/Controls/tests/Xaml.UnitTests/HotReloadStaticResourceException.xaml.cs b/src/Controls/tests/Xaml.UnitTests/HotReloadStaticResourceException.xaml.cs index b13158968af5..665c17d46c2a 100644 --- a/src/Controls/tests/Xaml.UnitTests/HotReloadStaticResourceException.xaml.cs +++ b/src/Controls/tests/Xaml.UnitTests/HotReloadStaticResourceException.xaml.cs @@ -35,12 +35,20 @@ public void TearDown() [Test] public void MissingResourceExceptionAreHandled([Values(XamlInflator.Runtime, XamlInflator.SourceGen)] XamlInflator inflator) { + bool handled = false; Controls.Internals.ResourceLoader.ExceptionHandler2 = (ex) => { var (exception, filepath) = ex; - + Assert.AreEqual("HotReloadStaticResourceException.xaml", filepath); + if (exception is XamlParseException xpe && xpe.Message.Contains("StaticResource not found for key MissingResource", System.StringComparison.Ordinal)) + { + handled = true; + Assert.AreEqual(13, xpe.XmlInfo.LinePosition); + } + }; var page = new HotReloadStaticResourceException(inflator); + Assert.IsTrue(handled, "Exception was not handled"); } #endif } From 92392dc3db463a9ef40c8ca9df52092ab1c9dfb6 Mon Sep 17 00:00:00 2001 From: Stephane Delcroix Date: Sat, 15 Nov 2025 16:54:36 +0100 Subject: [PATCH 033/128] [XSG] Add clr-namespace fallback for x:Static with unresolved types (#32630) Implements fallback behavior for x:Static markup extension when types cannot be resolved during source generation but are defined in a clr-namespace declaration. This allows the C# compiler to handle type resolution at compile-time, enabling scenarios like Blazor templates where types are generated after XAML processing. Similar to the x:Type fallback implemented in PR #32384, when a type cannot be resolved but has a clr-namespace URI, the source generator now emits 'global::Namespace.TypeName.MemberName' and defers validation to the C# compiler. Changes: - Modified ProvideValueForStaticExtension in KnownMarkups.cs to use TryResolveTypeSymbol with null diagnostic reporting and fallback to clr-namespace-based string generation - Added comprehensive unit tests for x:Static with unresolved types - Updated XStaticException test expectations for SourceGen scenario to reflect intentional fallback behavior Fixes #32627 --- src/Controls/src/SourceGen/KnownMarkups.cs | 16 +- .../XStaticUnresolvedType.cs | 333 ++++++++++++++++++ .../XStaticException.rt.xaml.cs | 5 +- 3 files changed, 349 insertions(+), 5 deletions(-) create mode 100644 src/Controls/tests/SourceGen.UnitTests/InitializeComponent/XStaticUnresolvedType.cs diff --git a/src/Controls/src/SourceGen/KnownMarkups.cs b/src/Controls/src/SourceGen/KnownMarkups.cs index b13425c2c1bb..cdcfc616e649 100644 --- a/src/Controls/src/SourceGen/KnownMarkups.cs +++ b/src/Controls/src/SourceGen/KnownMarkups.cs @@ -34,16 +34,24 @@ public static bool ProvideValueForStaticExtension(ElementNode markupNode, Indent var typename = member.Substring(0, dotIdx); var membername = member.Substring(dotIdx + 1); - var typeSymbol = typename.GetTypeSymbol(context, markupNode); - if (typeSymbol == null) + XmlType xmlType = TypeArgumentsParser.ParseSingle(typename, markupNode.NamespaceResolver, markupNode as IXmlLineInfo); + if (!xmlType.TryResolveTypeSymbol(null, context.Compilation, context.XmlnsCache, context.TypeCache, out var typeSymbol)) { + //fallback to guessing, if it's a clr-namespace + if (xmlType.NamespaceUri.GetClrNamespace() is var ns && ns is not null) + { + value = $"global::{ns}.{xmlType.Name}.{membername}"; + return true; + } + //FIXME context.ReportDiagnostic(Diagnostic.Create(Descriptors.XamlParserError, null, $"Type not found {typename}")); value = string.Empty; return false; } - var field = typeSymbol.GetAllFields(membername, context).FirstOrDefault(f => f.IsStatic); - var property = typeSymbol.GetAllProperties(membername, context).FirstOrDefault(p => p.IsStatic); + + var field = typeSymbol!.GetAllFields(membername, context).FirstOrDefault(f => f.IsStatic); + var property = typeSymbol!.GetAllProperties(membername, context).FirstOrDefault(p => p.IsStatic); //TODO handle enums, or contstants if (field == null && property == null) diff --git a/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/XStaticUnresolvedType.cs b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/XStaticUnresolvedType.cs new file mode 100644 index 000000000000..15fe6775563e --- /dev/null +++ b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/XStaticUnresolvedType.cs @@ -0,0 +1,333 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace Microsoft.Maui.Controls.SourceGen.UnitTests; + +public class XStaticUnresolvedType : SourceGenXamlInitializeComponentTestBase +{ + [Fact] + public void XStaticWithClrNamespace() + { + var xaml = +""" + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = +$$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var staticExtension = global::MyApp.Routes.Route.Value; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 12); + var label = new global::Microsoft.Maui.Controls.Label(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(label!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 6); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + label.transientNamescope = iNameScope; +#endif +#line 6 "{{testXamlFilePath}}" + label.SetValue(global::Microsoft.Maui.Controls.Label.TextProperty, staticExtension); +#line default +#line 6 "{{testXamlFilePath}}" + __root.SetValue(global::Microsoft.Maui.Controls.ContentPage.ContentProperty, label); +#line default + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } + + [Fact] + public void XStaticWithClrNamespaceAndAssembly() + { + var xaml = +""" + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = +$$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var staticExtension = global::ExternalLib.Constants.AppConstants.AppName; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 12); + var label = new global::Microsoft.Maui.Controls.Label(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(label!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 6); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + label.transientNamescope = iNameScope; +#endif +#line 6 "{{testXamlFilePath}}" + label.SetValue(global::Microsoft.Maui.Controls.Label.TextProperty, staticExtension); +#line default +#line 6 "{{testXamlFilePath}}" + __root.SetValue(global::Microsoft.Maui.Controls.ContentPage.ContentProperty, label); +#line default + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } + + [Fact] + public void XStaticWithClrNamespaceFieldAccess() + { + var xaml = +""" + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = +$$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var staticExtension = global::MyApp.Config.Settings.DefaultFontSize; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 12); + var label = new global::Microsoft.Maui.Controls.Label(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(label!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 6); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + label.transientNamescope = iNameScope; +#endif +#line 6 "{{testXamlFilePath}}" + label.SetValue(global::Microsoft.Maui.Controls.Label.FontSizeProperty, staticExtension); +#line default +#line 6 "{{testXamlFilePath}}" + __root.SetValue(global::Microsoft.Maui.Controls.ContentPage.ContentProperty, label); +#line default + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } +} diff --git a/src/Controls/tests/Xaml.UnitTests/XStaticException.rt.xaml.cs b/src/Controls/tests/Xaml.UnitTests/XStaticException.rt.xaml.cs index 39bc3bda220b..f5f90710ef91 100644 --- a/src/Controls/tests/Xaml.UnitTests/XStaticException.rt.xaml.cs +++ b/src/Controls/tests/Xaml.UnitTests/XStaticException.rt.xaml.cs @@ -43,7 +43,10 @@ public partial class XStaticException : ContentPage } """) .RunMauiSourceGenerator(typeof(XStaticException)); - Assert.That(result.Diagnostics.Any()); + // When the type is not in the compilation (as is the case here), + // SourceGen falls back to letting the C# compiler handle the validation. + // This is intentional behavior for unresolved types in clr-namespaces. + Assert.That(!result.Diagnostics.Any()); } else Assert.Ignore("Unknown inflator"); From fa613f26cd72fdfd780d2966a76986dc969640bf Mon Sep 17 00:00:00 2001 From: Stephane Delcroix Date: Sat, 15 Nov 2025 16:55:36 +0100 Subject: [PATCH 034/128] [XSG] better AppThemeBinding (#32441) * better AppThemeBinding * fix test, remove unused helpers --- src/Controls/src/SourceGen/KnownMarkups.cs | 66 +++- .../src/SourceGen/NodeSGExtensions.cs | 7 +- .../Visitors/SetPropertiesVisitor.cs | 2 +- .../InitializeComponent/AppThemeBinding.cs | 327 ++++++++++++++++++ .../StaticResourceWithTypeConversion.cs | 130 +++++++ .../LineEndingNormalizedEqualityComparer.cs | 38 -- ...neEndingNormalizedEqualityComparerTests.cs | 36 -- 7 files changed, 512 insertions(+), 94 deletions(-) create mode 100644 src/Controls/tests/SourceGen.UnitTests/InitializeComponent/AppThemeBinding.cs create mode 100644 src/Controls/tests/SourceGen.UnitTests/InitializeComponent/StaticResourceWithTypeConversion.cs delete mode 100644 src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparer.cs delete mode 100644 src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparerTests.cs diff --git a/src/Controls/src/SourceGen/KnownMarkups.cs b/src/Controls/src/SourceGen/KnownMarkups.cs index cdcfc616e649..045c01e18b6a 100644 --- a/src/Controls/src/SourceGen/KnownMarkups.cs +++ b/src/Controls/src/SourceGen/KnownMarkups.cs @@ -568,10 +568,11 @@ internal static bool ProvideValueForAppThemeBindingExtension(ElementNode node, I // Get the target property type for type conversion ITypeSymbol? propertyType = null; + IFieldSymbol? bpFieldSymbol = null; if (node.TryGetPropertyName(node.Parent, out XmlName propertyName) && context.Variables.TryGetValue(node.Parent, out ILocalValue parentVar)) { var localName = propertyName.LocalName; - var bpFieldSymbol = parentVar.Type.GetBindableProperty(propertyName.NamespaceURI, ref localName, out bool attached, context, node as IXmlLineInfo); + bpFieldSymbol = parentVar.Type.GetBindableProperty(propertyName.NamespaceURI, ref localName, out bool attached, context, node as IXmlLineInfo); var propertySymbol = parentVar.Type.GetAllProperties(localName, context).FirstOrDefault(); var typeandconverter = bpFieldSymbol?.GetBPTypeAndConverter(context); propertyType = typeandconverter?.type ?? propertySymbol?.Type; @@ -581,6 +582,32 @@ internal static bool ProvideValueForAppThemeBindingExtension(ElementNode node, I if (propertyType is null) propertyType = context.Compilation.ObjectType; + // Helper to get value from node - handles both ValueNode (direct conversion) and ElementNode (via getNodeValue) + string? GetNodeValueString(INode? targetNode) + { + if (targetNode is null) + return null; + + if (targetNode is ValueNode vn) + { + // For ValueNode, convert directly using the property type + if (bpFieldSymbol is not null) + return vn.ConvertTo(bpFieldSymbol, writer, context, context.Variables.TryGetValue(node.Parent, out var pv) ? pv : null); + else if (propertyType is not null) + return vn.ConvertTo(propertyType, writer, context, context.Variables.TryGetValue(node.Parent, out var pv) ? pv : null); + else + return NodeSGExtensions.ValueForLanguagePrimitive(vn.Value as string ?? string.Empty, context.Compilation.ObjectType, context, vn); + } + else if (targetNode is ElementNode) + { + // For ElementNode, use getNodeValue to get the variable reference + var local = getNodeValue(targetNode, propertyType); + return local.ValueAccessor; + } + + return null; + } + // Extract Light, Dark, and Default values from the markup extension string? lightValue = null; string? darkValue = null; @@ -591,24 +618,21 @@ internal static bool ProvideValueForAppThemeBindingExtension(ElementNode node, I || node.Properties.TryGetValue(new XmlName(null, "Default"), out defaultNode) || (node.CollectionItems.Count == 1 && (defaultNode = node.CollectionItems[0]) != null)) { - var defaultLocal = getNodeValue(defaultNode, propertyType); - defaultValue = defaultLocal.ValueAccessor; + defaultValue = GetNodeValueString(defaultNode); } // Check for Light property if (node.Properties.TryGetValue(new XmlName("", "Light"), out INode? lightNode) || node.Properties.TryGetValue(new XmlName(null, "Light"), out lightNode)) { - var lightLocal = getNodeValue(lightNode, propertyType); - lightValue = lightLocal.ValueAccessor; + lightValue = GetNodeValueString(lightNode); } // Check for Dark property if (node.Properties.TryGetValue(new XmlName("", "Dark"), out INode? darkNode) || node.Properties.TryGetValue(new XmlName(null, "Dark"), out darkNode)) { - var darkLocal = getNodeValue(darkNode, propertyType); - darkValue = darkLocal.ValueAccessor; + darkValue = GetNodeValueString(darkNode); } // At least one value must be set @@ -657,14 +681,6 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In } var resource = GetResourceNode(eNode, context, (string)keyValueNode.Value); - if (resource != null && getNodeValue != null) - { - var lvalue = getNodeValue(resource, context.Compilation.ObjectType); - value = lvalue.ValueAccessor; - returnType = lvalue.Type; - return true; - } - if (resource is null || !context.Variables.TryGetValue(resource, out var variable)) { returnType = context.Compilation.ObjectType; @@ -672,7 +688,6 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In return false; } - //if the resource is a string, try to convert it if (resource.CollectionItems.Count == 1 && resource.CollectionItems[0] is ValueNode vn && vn.Value is string) { @@ -684,6 +699,14 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In var typeandconverter = bpFieldSymbol?.GetBPTypeAndConverter(context); var propertyType = typeandconverter?.type ?? propertySymbol?.Type; + var converter = typeandconverter?.converter; + + // If no converter from BP, check the property's TypeConverter attribute + if (converter == null && propertySymbol != null) + { + List attributes = [.. propertySymbol.GetAttributes(), .. propertyType!.GetAttributes()]; + converter = attributes.FirstOrDefault(ad => ad.AttributeClass?.ToString() == "System.ComponentModel.TypeConverterAttribute")?.ConstructorArguments[0].Value as ITypeSymbol; + } if (propertyType!.Equals(context.Compilation.GetSpecialType(SpecialType.System_String), SymbolEqualityComparer.Default)) { @@ -693,7 +716,7 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In } try { - value = vn.ConvertTo(propertyType!, typeandconverter?.converter, writer, context, parentVar); + value = vn.ConvertTo(propertyType!, converter, writer, context, parentVar); } catch (Exception) { @@ -706,6 +729,15 @@ internal static bool ProvideValueForStaticResourceExtension(ElementNode node, In return true; } } + + // If we get here and getNodeValue is provided, use it as fallback + if (getNodeValue != null) + { + var lvalue = getNodeValue(resource, context.Compilation.ObjectType); + value = lvalue.ValueAccessor; + returnType = lvalue.Type; + return true; + } //Fallback to runtime resolution of StaticResource returnType = context.Compilation.ObjectType; diff --git a/src/Controls/src/SourceGen/NodeSGExtensions.cs b/src/Controls/src/SourceGen/NodeSGExtensions.cs index 3621e973c188..303aa0506a3d 100644 --- a/src/Controls/src/SourceGen/NodeSGExtensions.cs +++ b/src/Controls/src/SourceGen/NodeSGExtensions.cs @@ -497,6 +497,9 @@ public static void ProvideValue(this ElementNode node, IndentedTextWriter writer } public static bool TryProvideValue(this ElementNode node, IndentedTextWriter writer, SourceGenContext context) + => TryProvideValue(node, writer, context, null); + + public static bool TryProvideValue(this ElementNode node, IndentedTextWriter writer, SourceGenContext context, GetNodeValueDelegate? getNodeValue) { if (!context.Variables.TryGetValue(node, out var variable)) return false; @@ -505,7 +508,7 @@ public static bool TryProvideValue(this ElementNode node, IndentedTextWriter wri return false; if (GetKnownLateMarkupExtensions(context).TryGetValue(variable.Type, out var provideValue) - && provideValue.Invoke(node, writer, context, null, out var returnType0, out var value)) + && provideValue.Invoke(node, writer, context, getNodeValue, out var returnType0, out var value)) { var variableName = NamingHelpers.CreateUniqueVariableName(context, returnType0 ?? context.Compilation.ObjectType); context.Writer.WriteLine($"var {variableName} = {value};"); @@ -516,7 +519,7 @@ public static bool TryProvideValue(this ElementNode node, IndentedTextWriter wri } if (GetKnownValueProviders(context).TryGetValue(variable.Type, out provideValue) - && provideValue.Invoke(node, writer, context, null, out returnType0, out value)) + && provideValue.Invoke(node, writer, context, getNodeValue, out returnType0, out value)) { var variableName = NamingHelpers.CreateUniqueVariableName(context, returnType0 ?? context.Compilation.ObjectType); context.Writer.WriteLine($"var {variableName} = {value};"); diff --git a/src/Controls/src/SourceGen/Visitors/SetPropertiesVisitor.cs b/src/Controls/src/SourceGen/Visitors/SetPropertiesVisitor.cs index 9d425cd4cc3e..a933c0cf13f7 100644 --- a/src/Controls/src/SourceGen/Visitors/SetPropertiesVisitor.cs +++ b/src/Controls/src/SourceGen/Visitors/SetPropertiesVisitor.cs @@ -120,7 +120,7 @@ public void Visit(ElementNode node, INode parentNode) } //IMarkupExtension or IValueProvider => ProvideValue() - node.TryProvideValue(Writer, context); + node.TryProvideValue(Writer, context, getNodeValue); if (propertyName != XmlName.Empty) { diff --git a/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/AppThemeBinding.cs b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/AppThemeBinding.cs new file mode 100644 index 000000000000..945a67e73d20 --- /dev/null +++ b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/AppThemeBinding.cs @@ -0,0 +1,327 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace Microsoft.Maui.Controls.SourceGen.UnitTests; + +public class AppThemeBinding : SourceGenXamlInitializeComponentTestBase +{ + [Fact] + public void AppThemeBindingWithLightAndDark() + { + var xaml = +""" + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = $$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var appThemeBindingExtension = new global::Microsoft.Maui.Controls.Xaml.AppThemeBindingExtension(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBindingExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Light = "White"; +#line default +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Dark = "Black"; +#line default + var appThemeBinding = new global::Microsoft.Maui.Controls.AppThemeBinding { Light = global::Microsoft.Maui.Graphics.Colors.White, Dark = global::Microsoft.Maui.Graphics.Colors.Black }; + if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(appThemeBinding!) == null) + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBinding!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + __root.SetBinding(global::Microsoft.Maui.Controls.VisualElement.BackgroundColorProperty, appThemeBinding); + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } + + [Fact] + public void AppThemeBindingWithDefault() + { + var xaml = +""" + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = $$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var appThemeBindingExtension = new global::Microsoft.Maui.Controls.Xaml.AppThemeBindingExtension(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBindingExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Default = "Gray"; +#line default +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Dark = "Black"; +#line default + var appThemeBinding = new global::Microsoft.Maui.Controls.AppThemeBinding { Dark = global::Microsoft.Maui.Graphics.Colors.Black, Default = global::Microsoft.Maui.Graphics.Colors.Gray }; + if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(appThemeBinding!) == null) + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBinding!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + __root.SetBinding(global::Microsoft.Maui.Controls.VisualElement.BackgroundColorProperty, appThemeBinding); + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } + + [Fact] + public void AppThemeBindingWithAllThree() + { + var xaml = +""" + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + var expected = $$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + var appThemeBindingExtension = new global::Microsoft.Maui.Controls.Xaml.AppThemeBindingExtension(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBindingExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Light = "White"; +#line default +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Dark = "Black"; +#line default +#line 6 "{{testXamlFilePath}}" + appThemeBindingExtension.Default = "Gray"; +#line default + var appThemeBinding = new global::Microsoft.Maui.Controls.AppThemeBinding { Light = global::Microsoft.Maui.Graphics.Colors.White, Dark = global::Microsoft.Maui.Graphics.Colors.Black, Default = global::Microsoft.Maui.Graphics.Colors.Gray }; + if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(appThemeBinding!) == null) + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(appThemeBinding!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 2); + __root.SetBinding(global::Microsoft.Maui.Controls.VisualElement.BackgroundColorProperty, appThemeBinding); + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + Assert.False(result.Diagnostics.Any()); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } +} diff --git a/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/StaticResourceWithTypeConversion.cs b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/StaticResourceWithTypeConversion.cs new file mode 100644 index 000000000000..695f93455222 --- /dev/null +++ b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/StaticResourceWithTypeConversion.cs @@ -0,0 +1,130 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace Microsoft.Maui.Controls.SourceGen.UnitTests; + +public class StaticResourceWithTypeConversion : SourceGenXamlInitializeComponentTestBase +{ + [Fact] + public void StaticResourceForGridRowAndColumnDefinitions() + { + var xaml = +""" + + + + 10, *, *, auto + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var testXamlFilePath = Path.Combine(Environment.CurrentDirectory, "Test.xaml"); + + var expected = +$$""" +//------------------------------------------------------------------------------ +// +// This code was generated by a .NET MAUI source generator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ +#nullable enable + +namespace Test; + +[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")] +public partial class TestPage +{ + private partial void InitializeComponent() + { + // Fallback to Runtime inflation if the page was updated by HotReload + static string? getPathForType(global::System.Type type) + { + var assembly = type.Assembly; + foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes(assembly)) + { + if (xria.Type == type) + return xria.Path; + } + return null; + } + + var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery + { + AssemblyName = typeof(global::Test.TestPage).Assembly.GetName(), + ResourcePath = getPathForType(typeof(global::Test.TestPage)), + Instance = this, + }); + + if (rlr?.ResourceContent != null) + { + this.InitializeComponentRuntime(); + return; + } + + string string0 = "10, *, *, auto"; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(string0!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 6, 10); + var staticResourceExtension = new global::Microsoft.Maui.Controls.Xaml.StaticResourceExtension(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticResourceExtension!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 8, 8); + var grid = new global::Microsoft.Maui.Controls.Grid(); + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(grid!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 8, 3); + var __root = this; + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 2, 2); +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope(); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope); +#endif +#if !_MAUIXAML_SG_NAMESCOPE_DISABLE + grid.transientNamescope = iNameScope; +#endif + __root.Resources["GridRowDef"] = string0; +#line 8 "{{testXamlFilePath}}" + staticResourceExtension.Key = "GridRowDef"; +#line default + var rowDefinitionCollection = new global::Microsoft.Maui.Controls.RowDefinitionCollection([new RowDefinition(new global::Microsoft.Maui.GridLength(10, global::Microsoft.Maui.GridUnitType.Absolute)), new RowDefinition(global::Microsoft.Maui.GridLength.Star), new RowDefinition(global::Microsoft.Maui.GridLength.Star), new RowDefinition(global::Microsoft.Maui.GridLength.Auto)]); + if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(rowDefinitionCollection!) == null) + global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(rowDefinitionCollection!, new global::System.Uri(@"Test.xaml;assembly=SourceGeneratorDriver.Generated", global::System.UriKind.Relative), 8, 8); +#line 8 "{{testXamlFilePath}}" + grid.SetValue(global::Microsoft.Maui.Controls.Grid.RowDefinitionsProperty, rowDefinitionCollection); +#line default +#line 8 "{{testXamlFilePath}}" + __root.SetValue(global::Microsoft.Maui.Controls.ContentPage.ContentProperty, grid); +#line default + } +} + +"""; + + var (result, generated) = RunGenerator(xaml, code); + + Assert.Empty(result.Diagnostics); + Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); + } +} diff --git a/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparer.cs b/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparer.cs deleted file mode 100644 index 016363a68545..000000000000 --- a/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparer.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace Microsoft.Maui.Controls.SourceGen.UnitTests; - -/// -/// EqualityComparer that normalizes line endings before comparing strings. -/// This ensures that tests pass regardless of the platform's line ending conventions. -/// -public class LineEndingNormalizedEqualityComparer : IEqualityComparer -{ - private static readonly Regex LineEndingRegex = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled); - - public static LineEndingNormalizedEqualityComparer Instance { get; } = new LineEndingNormalizedEqualityComparer(); - - public bool Equals(string? x, string? y) - { - if (ReferenceEquals(x, y)) return true; - if (x is null || y is null) return false; - - var normalizedX = NormalizeLineEndings(x); - var normalizedY = NormalizeLineEndings(y); - - return string.Equals(normalizedX, normalizedY, StringComparison.Ordinal); - } - - public int GetHashCode(string? obj) - { - if (obj is null) return 0; - return NormalizeLineEndings(obj).GetHashCode(StringComparison.Ordinal); - } - - private static string NormalizeLineEndings(string input) - { - return LineEndingRegex.Replace(input, "\n"); - } -} \ No newline at end of file diff --git a/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparerTests.cs b/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparerTests.cs deleted file mode 100644 index 175e09a516bd..000000000000 --- a/src/Controls/tests/SourceGen.UnitTests/LineEndingNormalizedEqualityComparerTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Xunit; - -namespace Microsoft.Maui.Controls.SourceGen.UnitTests; - -public class LineEndingNormalizedEqualityComparerTests -{ - [Fact] - public void Equals_SameStringsWithDifferentLineEndings_ReturnsTrue() - { - var comparer = LineEndingNormalizedEqualityComparer.Instance; - var text1 = "Hello\nWorld\nTest"; - var text2 = "Hello\r\nWorld\rTest"; - - Assert.True(comparer.Equals(text1, text2)); - } - - [Fact] - public void Equals_DifferentStrings_ReturnsFalse() - { - var comparer = LineEndingNormalizedEqualityComparer.Instance; - var text1 = "Hello\nWorld"; - var text2 = "Hello\nDifferent"; - - Assert.False(comparer.Equals(text1, text2)); - } - - [Fact] - public void GetHashCode_SameStringsWithDifferentLineEndings_ReturnsSameHashCode() - { - var comparer = LineEndingNormalizedEqualityComparer.Instance; - var text1 = "Hello\nWorld\nTest"; - var text2 = "Hello\r\nWorld\rTest"; - - Assert.Equal(comparer.GetHashCode(text1), comparer.GetHashCode(text2)); - } -} \ No newline at end of file From 9ec85f61bf52d563a837b39647c2fd68c61f2bc1 Mon Sep 17 00:00:00 2001 From: Stephane Delcroix Date: Sat, 15 Nov 2025 16:56:13 +0100 Subject: [PATCH 035/128] Enable OnPlatform element simplification for InitializeComponent code generation (#32534) * Enable OnPlatform element simplification for InitializeComponent code generation Fixes #32521 This PR enables compile-time simplification of XML elements in addition to the existing {OnPlatform} markup extension support. Changes: - Uncommented and fixed OnPlatform element simplification code in SimplifyOnPlatformVisitor - Fixed collection item handling to support content property scenarios - Improved null safety and fixed GetDefault() method reference - Added test for OnPlatform element simplification in InitializeComponentCodeWriter - Added test for OnPlatform element simplification in CodeBehindCodeWriter - Renamed existing markup extension test for clarity The SimplifyOnPlatformVisitor now correctly handles both: 1. {OnPlatform} markup extensions (e.g., Value="{OnPlatform Android=True, iOS=False}") 2. elements (e.g., ...) Both are simplified at compile time based on target framework, ensuring only platform-specific code for the target platform is generated in InitializeComponent() and code-behind fields. Test results: - All 55 SourceGen.UnitTests pass - All 94 OnPlatform-related Xaml.UnitTests pass - 1712/1738 total Xaml.UnitTests pass (1 pre-existing unrelated failure) * Enable OnPlatform simplification with x:TypeArguments (#32620) * Initial plan * Implement OnPlatform simplification with x:TypeArguments and add comprehensive unit tests Co-authored-by: StephaneDelcroix <313003+StephaneDelcroix@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: StephaneDelcroix <313003+StephaneDelcroix@users.noreply.github.com> --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: StephaneDelcroix <313003+StephaneDelcroix@users.noreply.github.com> --- .../src/Xaml/SimplifyOnPlatformVisitor.cs | 150 ++++++++----- .../InitializeComponent/SimplifyOnPlatform.cs | 211 +++++++++++++++++- .../SourceGenXamlCodeBehindTests.cs | 38 ++++ 3 files changed, 347 insertions(+), 52 deletions(-) diff --git a/src/Controls/src/Xaml/SimplifyOnPlatformVisitor.cs b/src/Controls/src/Xaml/SimplifyOnPlatformVisitor.cs index 471a7730a7c6..1f10ea7ef601 100644 --- a/src/Controls/src/Xaml/SimplifyOnPlatformVisitor.cs +++ b/src/Controls/src/Xaml/SimplifyOnPlatformVisitor.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; #nullable disable @@ -77,57 +78,104 @@ public void Visit(ElementNode node, INode parentNode) } //`` elements - //if (node.XmlType.Name == "OnPlatform" && node.XmlType.NamespaceUri == XamlParser.MauiUri) - //{ - // var onNode = GetOnNode(node, Target) ?? GetDefault(node); - - // //Property node - // if (node.TryGetPropertyName(parentNode, out XmlName name) - // && parentNode is IElementNode parentEnode) - // { - // if (onNode != null) - // parentEnode.Properties[name] = onNode; - // else - // parentEnode.Properties.Remove(name); - // return; - // } - - // //Collection item - // if (onNode != null && parentNode is IElementNode parentEnode2) - // parentEnode2.CollectionItems[parentEnode2.CollectionItems.IndexOf(node)] = onNode; - - //} - - //INode GetOnNode(ElementNode onPlatform, string target) - //{ - // foreach (var onNode in onPlatform.CollectionItems) - // { - // if ((onNode as ElementNode).Properties.TryGetValue(new XmlName("", "Platform"), out var platform)) - // { - // var splits = ((platform as ValueNode).Value as string).Split(','); - // foreach (var split in splits) - // { - // if (string.IsNullOrWhiteSpace(split)) - // continue; - // if (split.Trim() == target) - // { - // if ((onNode as ElementNode).Properties.TryGetValue(new XmlName("", "Value"), out var node)) - // return node; - - // return (onNode as ElementNode).CollectionItems.FirstOrDefault(); - // } - // } - // } - // } - // return null; - //} - - //INode GetDefault(ElementNode onPlatform) - //{ - // if (node.Properties.TryGetValue(new XmlName("", "Default"), out INode defaultNode)) - // return defaultNode; - // return null; - //} + if (node.XmlType.Name == "OnPlatform" && node.XmlType.NamespaceUri == XamlParser.MauiUri) + { + var onNode = GetOnNode(node, Target) ?? GetDefault(node); + + // Check if this OnPlatform has an x:Key (e.g., in ResourceDictionaries) + INode keyNode = null; + bool hasKey = node.Properties.TryGetValue(XmlName.xKey, out keyNode); + + // If OnPlatform has x:Key but the replacement node is a ValueNode, + // check if we have x:TypeArguments to create a proper ElementNode + if (hasKey && onNode is ValueNode valueNode) + { + // Check if OnPlatform has x:TypeArguments + if (node.XmlType.TypeArguments != null && node.XmlType.TypeArguments.Count > 0) + { + // Create a new ElementNode with the type from x:TypeArguments + var typeArg = node.XmlType.TypeArguments[0]; + var elementNode = new ElementNode(typeArg, typeArg.NamespaceUri, node.NamespaceResolver, node.LineNumber, node.LinePosition); + + // Set the value as the collection item (for types like Color, this is how they're represented) + elementNode.CollectionItems.Add(valueNode); + + // Replace the ValueNode with the new ElementNode + onNode = elementNode; + } + else + { + // No x:TypeArguments, so we cannot create a proper ElementNode + // Skip simplification + return; + } + } + + //Property node + if (node.TryGetPropertyName(parentNode, out XmlName name) + && parentNode is ElementNode parentEnode) + { + if (onNode != null) + { + // Transfer x:Key to the replacement node if it exists + if (hasKey && onNode is ElementNode onElementNode && !onElementNode.Properties.ContainsKey(XmlName.xKey)) + onElementNode.Properties[XmlName.xKey] = keyNode; + parentEnode.Properties[name] = onNode; + } + else + parentEnode.Properties.Remove(name); + return; + } + + //Collection item (e.g., when OnPlatform is the content property or in ResourceDictionary) + if (parentNode is ElementNode parentEnode2) + { + int index = parentEnode2.CollectionItems.IndexOf(node); + if (index >= 0) + { + if (onNode != null) + { + // Transfer x:Key to the replacement node if it exists + if (hasKey && onNode is ElementNode onElementNode && !onElementNode.Properties.ContainsKey(XmlName.xKey)) + onElementNode.Properties[XmlName.xKey] = keyNode; + parentEnode2.CollectionItems[index] = onNode; + } + else + parentEnode2.CollectionItems.RemoveAt(index); + } + } + } + + INode GetOnNode(ElementNode onPlatform, string target) + { + foreach (var onNode in onPlatform.CollectionItems) + { + if (onNode is ElementNode elementNode && elementNode.Properties.TryGetValue(new XmlName("", "Platform"), out var platform)) + { + var splits = ((platform as ValueNode).Value as string).Split(','); + foreach (var split in splits) + { + if (string.IsNullOrWhiteSpace(split)) + continue; + if (split.Trim() == target) + { + if (elementNode.Properties.TryGetValue(new XmlName("", "Value"), out var valueNode)) + return valueNode; + + return elementNode.CollectionItems.FirstOrDefault(); + } + } + } + } + return null; + } + + INode GetDefault(ElementNode onPlatform) + { + if (onPlatform.Properties.TryGetValue(new XmlName("", "Default"), out INode defaultNode)) + return defaultNode; + return null; + } } diff --git a/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SimplifyOnPlatform.cs b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SimplifyOnPlatform.cs index 6d8897faddc9..e40d82f6566e 100644 --- a/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SimplifyOnPlatform.cs +++ b/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SimplifyOnPlatform.cs @@ -8,7 +8,7 @@ namespace Microsoft.Maui.Controls.SourceGen.UnitTests; public class SimplifyOnPlatform : SourceGenXamlInitializeComponentTestBase { [Fact] - public void Test() + public void SimplifyOnPlatformMarkupExtension() { var xaml = """ @@ -143,4 +143,213 @@ private partial void InitializeComponent() Assert.Equal(expected, generated, ignoreLineEndingDifferences: true); } + + [Fact] + public void SimplifyOnPlatformElement() + { + // Issue #32521: OnPlatform elements should be simplified at compile time based on target framework + var xaml = +""" + + + + + + + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var (result, generated) = RunGenerator(xaml, code, targetFramework: "net10.0-android"); + Assert.False(result.Diagnostics.Any()); + + // Should contain only Android label, not iOS label + Assert.Contains("AndroidLabel", generated, StringComparison.Ordinal); + Assert.DoesNotContain("iOSLabel", generated, StringComparison.Ordinal); + Assert.Contains("Android Content", generated, StringComparison.Ordinal); + Assert.DoesNotContain("iOS Content", generated, StringComparison.Ordinal); + } + + [Fact] + public void SimplifyOnPlatformWithXKeyAndValueNodeWithoutTypeArguments() + { + // OnPlatform with x:Key but WITHOUT x:TypeArguments should NOT be simplified + // when the target value is a ValueNode, because we don't know how to create the typed element + var xaml = +""" + + + + + + + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var (result, generated) = RunGenerator(xaml, code, targetFramework: "net10.0-android"); + Assert.False(result.Diagnostics.Any()); + + // OnPlatform should NOT be simplified because there's no x:TypeArguments and the target is a ValueNode + Assert.Contains("OnPlatform", generated, StringComparison.Ordinal); + } + + [Fact] + public void SimplifyOnPlatformWithXKeyAndXTypeArguments() + { + // OnPlatform with x:Key and x:TypeArguments should be simplified by creating a typed element + // For example, OnPlatform with x:TypeArguments="Color" should become Red + var xaml = +""" + + + + + + + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var (result, generated) = RunGenerator(xaml, code, targetFramework: "net10.0-android"); + Assert.False(result.Diagnostics.Any()); + + // OnPlatform SHOULD be simplified because x:TypeArguments tells us how to create a proper typed element + Assert.DoesNotContain("OnPlatform", generated, StringComparison.Ordinal); + Assert.Contains("TestColor", generated, StringComparison.Ordinal); + // Should contain Red (Android), not Blue (iOS) + Assert.Contains("Red", generated, StringComparison.Ordinal); + Assert.DoesNotContain("Blue", generated, StringComparison.Ordinal); + + // Verify the generated code creates a Color object directly + Assert.Contains("Colors.Red", generated, StringComparison.Ordinal); + } + + [Fact] + public void SimplifyOnPlatformWithXKeyAndElementNode() + { + // OnPlatform with x:Key should be simplified if the target value is an ElementNode + // and the x:Key should be transferred to the replacement element + var xaml = +""" + + + + + + + + + + + + + +"""; + + var code = +""" +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Xaml; + +namespace Test; + +[XamlProcessing(XamlInflator.SourceGen)] +public partial class TestPage : ContentPage +{ + public TestPage() + { + InitializeComponent(); + } +} +"""; + + var (result, generated) = RunGenerator(xaml, code, targetFramework: "net10.0-android"); + Assert.False(result.Diagnostics.Any()); + + // OnPlatform should be simplified and the x:Key transferred to the Style element + Assert.DoesNotContain("OnPlatform", generated, StringComparison.Ordinal); + Assert.Contains("TestStyle", generated, StringComparison.Ordinal); + // Should contain Android style (Red), not iOS style (Blue) + Assert.Contains("Red", generated, StringComparison.Ordinal); + Assert.DoesNotContain("Blue", generated, StringComparison.Ordinal); + } } \ No newline at end of file diff --git a/src/Controls/tests/SourceGen.UnitTests/SourceGenXamlCodeBehindTests.cs b/src/Controls/tests/SourceGen.UnitTests/SourceGenXamlCodeBehindTests.cs index 5aba96f45078..e2e2b0b1ebc8 100644 --- a/src/Controls/tests/SourceGen.UnitTests/SourceGenXamlCodeBehindTests.cs +++ b/src/Controls/tests/SourceGen.UnitTests/SourceGenXamlCodeBehindTests.cs @@ -547,4 +547,42 @@ internal class InternalButVisible : Label { } Assert.True(generated.Contains("External.InternalButVisible internalButVisible", StringComparison.Ordinal)); } + + [Fact] + public void TestCodeBehindGenerator_OnPlatform_Android() + { + // Issue #32521: Named controls under OnPlatform should only generate fields for the target platform + var xaml = +""" + + + + + +