From 8e2adfae6854eda1b8fafc96b68f6b4c8f6e7dc3 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:01:10 +0300 Subject: [PATCH 1/8] Remove calls to `GetTypeInfo()`. --- .../Definition/ProjectCollection_Tests.cs | 2 +- .../BackEnd/AssemblyTaskFactory_Tests.cs | 4 ++-- .../BackEnd/LoggingService_Tests.cs | 24 +++++++++---------- .../BackEnd/SdkResolverLoader_Tests.cs | 4 ++-- .../BackEnd/TaskExecutionHost_Tests.cs | 6 ++--- .../BackEnd/TaskRegistry_Tests.cs | 24 ++----------------- .../BackEnd/BuildManager/BuildManager.cs | 7 +++--- .../Components/Logging/LoggingService.cs | 2 +- .../ProjectCache/ProjectCacheService.cs | 8 +------ .../RequestBuilder/IntrinsicTask.cs | 3 +-- .../Components/RequestBuilder/TaskBuilder.cs | 2 +- .../Components/RequestBuilder/TaskHost.cs | 3 +-- .../SdkResolution/SdkResolverLoader.cs | 4 +--- .../SdkResolution/SdkResolverService.cs | 3 +-- .../TaskExecutionHost/TaskExecutionHost.cs | 4 ++-- src/Build/Definition/ProjectCollection.cs | 2 +- src/Build/Evaluation/Expander.cs | 2 +- .../Instance/TaskFactories/TaskHostTask.cs | 4 ++-- src/Build/Instance/TaskFactoryLoggingHost.cs | 3 +-- src/Build/Instance/TaskRegistry.cs | 10 ++++---- src/Build/Logging/LoggerDescription.cs | 12 +++++----- src/Build/Resources/AssemblyResources.cs | 5 ++-- .../Resources/MSBuildAssemblyFileVersion.cs | 2 +- .../EditorConfig_Tests.cs | 4 ++-- src/Framework.UnitTests/Attribute_Tests.cs | 2 +- src/Framework/AssemblyUtilities.cs | 10 -------- src/Framework/NativeMethods.cs | 4 ++-- src/Framework/TaskPropertyInfo.cs | 2 +- src/MSBuild/AssemblyResources.cs | 4 ++-- src/MSBuild/OutOfProcTaskHostNode.cs | 2 +- src/MSBuild/XMake.cs | 4 ++-- src/Samples/PortableTask/ShowItems.cs | 2 +- src/Shared/CommunicationsUtilities.cs | 2 +- src/Shared/FileUtilities.cs | 5 ++-- src/Shared/LoadedType.cs | 6 ++--- src/Shared/TaskLoader.cs | 9 ++++--- src/Shared/TaskParameter.cs | 10 ++++---- src/Shared/TaskParameterTypeVerifier.cs | 17 +++++++------ src/Shared/Tracing.cs | 3 +-- src/Tasks/AssemblyResources.cs | 4 ++-- .../RoslynCodeTaskFactory.cs | 2 +- src/UnitTests.Shared/MockLogger.cs | 2 +- src/Utilities.UnitTests/MockTask.cs | 2 +- .../ToolLocationHelper_Tests.cs | 4 ++-- src/Utilities/AssemblyResources.cs | 4 ++-- 45 files changed, 99 insertions(+), 145 deletions(-) diff --git a/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs index 168cb67c58e..d1cf4739f6e 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs @@ -1448,7 +1448,7 @@ public void ProjectChangedEvent() [Fact] public void ProjectCollectionVersionIsCorrect() { - Version expectedVersion = new Version(this.GetType().GetTypeInfo().Assembly.GetCustomAttribute().Version); + Version expectedVersion = new Version(this.GetType().Assembly.GetCustomAttribute().Version); ProjectCollection.Version.Major.ShouldBe(expectedVersion.Major); ProjectCollection.Version.Minor.ShouldBe(expectedVersion.Minor); diff --git a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs index a2d52c2df63..cb836c84f2e 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs @@ -212,7 +212,7 @@ public void CreatableByTaskFactoryMismatchedIdentity() public void VerifyGetTaskParameters() { TaskPropertyInfo[] propertyInfos = _taskFactory.GetTaskParameters(); - LoadedType comparisonType = new LoadedType(typeof(TaskToTestFactories), _loadInfo, typeof(TaskToTestFactories).GetTypeInfo().Assembly, typeof(ITaskItem)); + LoadedType comparisonType = new LoadedType(typeof(TaskToTestFactories), _loadInfo, typeof(TaskToTestFactories).Assembly, typeof(ITaskItem)); PropertyInfo[] comparisonInfo = comparisonType.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public); Assert.Equal(comparisonInfo.Length, propertyInfos.Length); @@ -686,7 +686,7 @@ private void SetupTaskFactory(IDictionary factoryParameters, boo #if FEATURE_ASSEMBLY_LOCATION _loadInfo = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location); #else - _loadInfo = AssemblyLoadInfo.Create(typeof(TaskToTestFactories).GetTypeInfo().Assembly.FullName, null); + _loadInfo = AssemblyLoadInfo.Create(typeof(TaskToTestFactories).Assembly.FullName, null); #endif _loadedType = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty); Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal" diff --git a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs index 4d42f596bcb..7125997276a 100644 --- a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs @@ -334,7 +334,7 @@ public void RegisterDistributedLoggerServiceShutdown() #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); #endif _initializedService.RegisterDistributedLogger(null, description); }); @@ -351,8 +351,8 @@ public void RegisterGoodDistributedAndCentralLogger() LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); - LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).Assembly.FullName, true); + LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).Assembly.FullName, true); #endif DistributedFileLogger fileLogger = new DistributedFileLogger(); @@ -388,8 +388,8 @@ public void RegisterGoodDistributedAndCentralLoggerTestBuildStartedFinished() LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); - LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, typeof(ProjectCollection).Assembly.FullName, true); + LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, typeof(ProjectCollection).Assembly.FullName, true); #endif RegularILogger regularILoggerA = new RegularILogger(); @@ -433,7 +433,7 @@ public void RegisterDuplicateCentralLogger() #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); @@ -461,7 +461,7 @@ public void RegisterDuplicateForwardingLoggerLogger() #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); @@ -526,7 +526,7 @@ public void NullForwardingLoggerSink() #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); #endif _initializedService.ShutdownComponent(); List tempList = new List(); @@ -549,8 +549,8 @@ public void RegisterGoodDiscriptions() loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); #else - loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true)); - loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true)); + loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).Assembly.FullName, true)); + loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).Assembly.FullName, true)); #endif // Register some descriptions with a sink @@ -611,7 +611,7 @@ public void RegisterDuplicateDistributedCentralLogger() #if FEATURE_ASSEMBLY_LOCATION LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); #else - LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); + LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); #endif RegularILogger regularILogger = new RegularILogger(); @@ -1108,7 +1108,7 @@ private void VerifyShutdownExceptions(ILogger logger, string className, Type exp #if FEATURE_ASSEMBLY_LOCATION Assembly thisAssembly = Assembly.GetAssembly(typeof(LoggingService_Tests)); #else - Assembly thisAssembly = typeof(LoggingService_Tests).GetTypeInfo().Assembly; + Assembly thisAssembly = typeof(LoggingService_Tests).Assembly; #endif string loggerAssemblyName = thisAssembly.FullName; LoggerDescription centralLoggerDescrption = CreateLoggerDescription(className, loggerAssemblyName, true); diff --git a/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs b/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs index 298987ef008..373a37a93ad 100644 --- a/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs +++ b/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs @@ -126,7 +126,7 @@ public void VerifyThrowsWhenResolverFailsToLoad() { SdkResolverLoader sdkResolverLoader = new MockSdkResolverLoader { - LoadResolverAssemblyFunc = (resolverPath) => typeof(SdkResolverLoader_Tests).GetTypeInfo().Assembly, + LoadResolverAssemblyFunc = (resolverPath) => typeof(SdkResolverLoader_Tests).Assembly, FindPotentialSdkResolversFunc = (rootFolder, loc) => new List { "myresolver.dll" @@ -158,7 +158,7 @@ public void VerifyThrowsWhenResolverHasNoPublicConstructor() { SdkResolverLoader sdkResolverLoader = new MockSdkResolverLoader { - LoadResolverAssemblyFunc = (resolverPath) => typeof(SdkResolverLoader_Tests).GetTypeInfo().Assembly, + LoadResolverAssemblyFunc = (resolverPath) => typeof(SdkResolverLoader_Tests).Assembly, FindPotentialSdkResolversFunc = (rootFolder, loc) => new List { "myresolver.dll" diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index ce24deabc92..cc0eabb41da 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -1218,8 +1218,8 @@ public bool BuildProjectFile(string projectFileName, string[] targetNames, IDict /// private static bool IsTaskFactoryClass(Type type, object unused) { - return type.GetTypeInfo().IsClass && - !type.GetTypeInfo().IsAbstract && + return type.IsClass && + !type.IsAbstract && (type.GetInterface("Microsoft.Build.Framework.ITaskFactory") != null); } @@ -1242,7 +1242,7 @@ private void InitializeHost(bool throwOnExecute) #if !FEATURE_ASSEMBLYLOADCONTEXT AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(Assembly.GetAssembly(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory)).FullName, null); #else - AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory).GetTypeInfo().FullName, null); + AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory).FullName, null); #endif LoadedType loadedType = new LoadedType(typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory), loadInfo, typeof(TaskBuilderTestTask.TaskBuilderTestTaskFactory).Assembly, typeof(ITaskItem)); diff --git a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs index 6a652802962..ca008ba2a9b 100644 --- a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs @@ -83,7 +83,7 @@ public class TaskRegistry_Tests /// public TaskRegistry_Tests(ITestOutputHelper output) { - _testTaskLocation = typeof(TaskRegistry_Tests).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName; + _testTaskLocation = typeof(TaskRegistry_Tests).Assembly.ManifestModule.FullyQualifiedName; _loggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); _targetLoggingContext = new TargetLoggingContext(_loggingService, _loggerContext); @@ -1237,7 +1237,7 @@ public void TaskFactoryWithNullTaskTypeLogsError() List elementList = new List(); ProjectRootElement project = ProjectRootElement.Create(); - ProjectUsingTaskElement element = project.AddUsingTask("Task1", AssemblyUtilities.GetAssemblyLocation(typeof(TaskRegistry_Tests.NullTaskTypeTaskFactory).GetTypeInfo().Assembly), null); + ProjectUsingTaskElement element = project.AddUsingTask("Task1", AssemblyUtilities.GetAssemblyLocation(typeof(TaskRegistry_Tests.NullTaskTypeTaskFactory).Assembly), null); element.TaskFactory = typeof(NullTaskTypeTaskFactory).FullName; elementList.Add(element); @@ -1461,11 +1461,7 @@ public void BadScalarInputOnInputParameterDerivedFromITask() // Note output is false so these are only input parameters string output = bool.FalseString; string required = bool.TrueString; -#if FEATURE_ASSEMBLY_LOCATION string type = type = typeof(DerivedFromITaskItem).FullName + "," + typeof(DerivedFromITaskItem).Assembly.FullName; -#else - string type = type = typeof(DerivedFromITaskItem).FullName + "," + typeof(DerivedFromITaskItem).GetTypeInfo().Assembly.FullName; -#endif List elementList = CreateParameterElementWithAttributes(output, required, type); TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); @@ -1516,11 +1512,7 @@ public void GoodOutPutParameters() type = typeof(ITaskItem).FullName; VerifyTypeParameter(output, required, type); -#if FEATURE_ASSEMBLY_LOCATION type = typeof(DerivedFromITaskItem).FullName + "," + typeof(DerivedFromITaskItem).Assembly.FullName; -#else - type = typeof(DerivedFromITaskItem).FullName + "," + typeof(DerivedFromITaskItem).GetTypeInfo().Assembly.FullName; -#endif VerifyTypeParameter(output, required, type); type = typeof(ITaskItem[]).FullName; @@ -1535,11 +1527,7 @@ public void GoodOutPutParameters() type = typeof(DateTime[]).FullName; VerifyTypeParameter(output, required, type); -#if FEATURE_ASSEMBLY_LOCATION type = typeof(DerivedFromITaskItem[]).FullName + "," + typeof(DerivedFromITaskItem).Assembly.FullName; -#else - type = typeof(DerivedFromITaskItem[]).FullName + "," + typeof(DerivedFromITaskItem).GetTypeInfo().Assembly.FullName; -#endif VerifyTypeParameter(output, required, type); } @@ -1706,11 +1694,7 @@ public void ExpandedGoodParameters() Assert.Equal( parameterInfo.PropertyType, Type.GetType( -#if FEATURE_ASSEMBLY_LOCATION expandedType + "," + typeof(ITaskItem).Assembly.FullName, -#else - expandedType + "," + typeof(ITaskItem).GetTypeInfo().Assembly.FullName, -#endif false /* don't throw on error */, true /* case-insensitive */)); } @@ -2116,11 +2100,7 @@ private void VerifyTypeParameter(string output, string required, string type) if (paramType == null) { paramType = Type.GetType( -#if FEATURE_ASSEMBLY_LOCATION type + "," + typeof(ITaskItem).Assembly.FullName, -#else - type + "," + typeof(ITaskItem).GetTypeInfo().Assembly.FullName, -#endif false /* don't throw on error */, true /* case-insensitive */); } diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index 2451efbc7cd..6c1d136bb7d 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -12,7 +12,6 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Threading; @@ -3010,7 +3009,7 @@ private ILoggingService CreateLoggingService( // In the future we might optimize for single, in-node build scenario - where forwarding logger is not needed (but it's just quick pass-through) LoggerDescription forwardingLoggerDescription = new LoggerDescription( loggerClassName: typeof(BuildCheckForwardingLogger).FullName, - loggerAssemblyName: typeof(BuildCheckForwardingLogger).GetTypeInfo().Assembly.GetName().FullName, + loggerAssemblyName: typeof(BuildCheckForwardingLogger).Assembly.GetName().FullName, loggerAssemblyFile: null, loggerSwitchParameters: null, verbosity: LoggerVerbosity.Quiet); @@ -3030,7 +3029,7 @@ private ILoggingService CreateLoggingService( // In the future we might optimize for single, in-node build scenario - where forwarding logger is not needed (but it's just quick pass-through) LoggerDescription forwardingLoggerDescription = new LoggerDescription( loggerClassName: typeof(InternalTelemetryForwardingLogger).FullName, - loggerAssemblyName: typeof(InternalTelemetryForwardingLogger).GetTypeInfo().Assembly.GetName().FullName, + loggerAssemblyName: typeof(InternalTelemetryForwardingLogger).Assembly.GetName().FullName, loggerAssemblyFile: null, loggerSwitchParameters: null, verbosity: LoggerVerbosity.Quiet); @@ -3081,7 +3080,7 @@ private ILoggingService CreateLoggingService( static List ProcessForwardingLoggers(IEnumerable? forwarders) { Type configurableLoggerType = typeof(ConfigurableForwardingLogger); - string engineAssemblyName = configurableLoggerType.GetTypeInfo().Assembly.GetName().FullName; + string engineAssemblyName = configurableLoggerType.Assembly.GetName().FullName; string configurableLoggerName = configurableLoggerType.FullName!; if (forwarders == null) diff --git a/src/Build/BackEnd/Components/Logging/LoggingService.cs b/src/Build/BackEnd/Components/Logging/LoggingService.cs index 1e4121594e2..ab2066be9ec 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingService.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingService.cs @@ -1012,7 +1012,7 @@ public bool RegisterLogger(ILogger logger) if (_centralForwardingLoggerSinkId == -1) { // Create a forwarding logger which forwards all events to an eventSourceSink - Assembly engineAssembly = typeof(LoggingService).GetTypeInfo().Assembly; + Assembly engineAssembly = typeof(LoggingService).Assembly; string loggerClassName = "Microsoft.Build.BackEnd.Logging.CentralForwardingLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription centralForwardingLoggerDescription = new LoggerDescription( diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs index 97f373790bd..016035fe759 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs @@ -451,13 +451,7 @@ Assembly LoadAssembly(string resolverPath) IEnumerable GetTypes(Assembly assembly) { return assembly.ExportedTypes - .Select(type => new { type, info = type.GetTypeInfo() }) - .Where( - t => t.info.IsClass && - t.info.IsPublic && - !t.info.IsAbstract && - typeof(T).IsAssignableFrom(t.type)) - .Select(t => t.type); + .Where(t => t.IsClass && t.IsPublic && !t.IsAbstract && typeof(T).IsAssignableFrom(t)); } } diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs index 94c1ee183ac..9476b8105bf 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Reflection; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Execution; using Microsoft.Build.Shared; @@ -77,7 +76,7 @@ internal static IntrinsicTask InstantiateTask(ProjectTargetInstanceChild taskIns } else { - ErrorUtilities.ThrowInternalError("Unhandled intrinsic task type {0}", taskInstance.GetType().GetTypeInfo().BaseType); + ErrorUtilities.ThrowInternalError("Unhandled intrinsic task type {0}", taskInstance.GetType().BaseType); return null; } } diff --git a/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs index 0bba1d2b4e6..96a02ed1e1f 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs @@ -904,7 +904,7 @@ private async ValueTask ExecuteInstantiatedTask(TaskExecutionHos throw new InvalidProjectFileException(ipex.Message, ipex); } } - else if (type == typeof(Exception) || type.GetTypeInfo().IsSubclassOf(typeof(Exception))) + else if (type == typeof(Exception) || type.IsSubclassOf(typeof(Exception))) { // Occasionally, when debugging a very uncommon task exception, it is useful to loop the build with // a debugger attached to break on 2nd chance exceptions. diff --git a/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs b/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs index 034569b6236..799fff06987 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs @@ -10,7 +10,6 @@ using System.Runtime.Remoting.Lifetime; #endif using System.Diagnostics; -using System.Reflection; using System.Threading.Tasks; using Microsoft.Build.BackEnd.Components.Caching; using Microsoft.Build.Collections; @@ -1119,7 +1118,7 @@ internal bool IsEventSerializable(BuildEventArgs e) #pragma warning disable SYSLIB0050 // Types which are not serializable and are not IExtendedBuildEventArgs as // those always implement custom serialization by WriteToStream and CreateFromStream. - if (!e.GetType().GetTypeInfo().IsSerializable && e is not IExtendedBuildEventArgs) + if (!e.GetType().IsSerializable && e is not IExtendedBuildEventArgs) #pragma warning restore SYSLIB0050 { _taskLoggingContext.LogWarning(null, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs index c9876d8a9bc..c9f82f2770f 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs @@ -223,9 +223,7 @@ private bool TryAddAssemblyManifestFromDll(string assemblyPath, List GetResolverTypes(Assembly assembly) { return assembly.ExportedTypes - .Select(type => new { type, info = type.GetTypeInfo() }) - .Where(t => t.info.IsClass && t.info.IsPublic && !t.info.IsAbstract && typeof(SdkResolver).IsAssignableFrom(t.type)) - .Select(t => t.type); + .Where(t => t.IsClass && t.IsPublic && !t.IsAbstract && typeof(SdkResolver).IsAssignableFrom(t)); } protected virtual Assembly LoadResolverAssembly(string resolverPath) diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs index 9c0efaef777..b44d46e84f8 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; using System.Text.RegularExpressions; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; @@ -339,7 +338,7 @@ private bool TryResolveSdkUsingSpecifiedResolvers( loggingContext.LogComment(MessageImportance.Low, "SDKResolverNullMessage", sdkResolver.Name, sdk.ToString()); } } - catch (Exception e) when ((e is FileNotFoundException || e is FileLoadException) && sdkResolver.GetType().GetTypeInfo().Name.Equals("NuGetSdkResolver", StringComparison.Ordinal)) + catch (Exception e) when ((e is FileNotFoundException || e is FileLoadException) && sdkResolver.GetType().Name.Equals("NuGetSdkResolver", StringComparison.Ordinal)) { // Since we explicitly add the NuGetSdkResolver, we special case this. The NuGetSdkResolver has special logic // to load NuGet assemblies at runtime which could fail if the user is not running installed MSBuild. Rather diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index bdf355ead93..058c2843c04 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -918,13 +918,13 @@ private TaskFactoryWrapper FindTaskInRegistry(IDictionary taskId // Map to an intrinsic task, if necessary. if (String.Equals(returnClass.TaskFactory.TaskType.FullName, "Microsoft.Build.Tasks.MSBuild", StringComparison.OrdinalIgnoreCase)) { - Assembly taskExecutionHostAssembly = typeof(TaskExecutionHost).GetTypeInfo().Assembly; + Assembly taskExecutionHostAssembly = typeof(TaskExecutionHost).Assembly; returnClass = new TaskFactoryWrapper(new IntrinsicTaskFactory(typeof(MSBuild)), new LoadedType(typeof(MSBuild), AssemblyLoadInfo.Create(taskExecutionHostAssembly.FullName, null), taskExecutionHostAssembly, typeof(ITaskItem)), _taskName, null); _intrinsicTasks[_taskName] = returnClass; } else if (String.Equals(returnClass.TaskFactory.TaskType.FullName, "Microsoft.Build.Tasks.CallTarget", StringComparison.OrdinalIgnoreCase)) { - Assembly taskExecutionHostAssembly = typeof(TaskExecutionHost).GetTypeInfo().Assembly; + Assembly taskExecutionHostAssembly = typeof(TaskExecutionHost).Assembly; returnClass = new TaskFactoryWrapper(new IntrinsicTaskFactory(typeof(CallTarget)), new LoadedType(typeof(CallTarget), AssemblyLoadInfo.Create(taskExecutionHostAssembly.FullName, null), taskExecutionHostAssembly, typeof(ITaskItem)), _taskName, null); _intrinsicTasks[_taskName] = returnClass; } diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 9973e5d3d80..5041ef60fd3 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -484,7 +484,7 @@ public static string DisplayVersion { if (s_assemblyDisplayVersion == null) { - var fullInformationalVersion = typeof(Constants).GetTypeInfo().Assembly.GetCustomAttribute().InformationalVersion; + var fullInformationalVersion = typeof(Constants).Assembly.GetCustomAttribute().InformationalVersion; // use a truncated version with only 9 digits of SHA var plusIndex = fullInformationalVersion.IndexOf('+'); diff --git a/src/Build/Evaluation/Expander.cs b/src/Build/Evaluation/Expander.cs index 47ebdcfd234..113bdeea780 100644 --- a/src/Build/Evaluation/Expander.cs +++ b/src/Build/Evaluation/Expander.cs @@ -4520,7 +4520,7 @@ private static object[] CoerceArguments(object[] args, ParameterInfo[] parameter { coercedArguments[n] = args[n].ToString().ToCharArray(); } - else if (parameters[n].ParameterType.GetTypeInfo().IsEnum && args[n] is string v && v.Contains('.')) + else if (parameters[n].ParameterType.IsEnum && args[n] is string v && v.Contains('.')) { Type enumType = parameters[n].ParameterType; string typeLeafName = $"{enumType.Name}."; diff --git a/src/Build/Instance/TaskFactories/TaskHostTask.cs b/src/Build/Instance/TaskFactories/TaskHostTask.cs index f374c203a7b..3aeee326c08 100644 --- a/src/Build/Instance/TaskFactories/TaskHostTask.cs +++ b/src/Build/Instance/TaskFactories/TaskHostTask.cs @@ -280,7 +280,7 @@ public bool Execute() BuildEngine.ProjectFileOfTaskNode, BuildEngine.ContinueOnError, _taskType.Type.FullName, - AssemblyUtilities.GetAssemblyLocation(_taskType.Type.GetTypeInfo().Assembly), + AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly), _buildComponentHost.BuildParameters.LogTaskInputs, _setParameters, new Dictionary(_buildComponentHost.BuildParameters.GlobalProperties), @@ -497,7 +497,7 @@ private void HandleTaskHostTaskComplete(TaskHostTaskComplete taskHostTaskComplet else { exceptionMessageArgs = [_taskType.Type.Name, - AssemblyUtilities.GetAssemblyLocation(_taskType.Type.GetTypeInfo().Assembly), + AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly), string.Empty]; } diff --git a/src/Build/Instance/TaskFactoryLoggingHost.cs b/src/Build/Instance/TaskFactoryLoggingHost.cs index 7b6ef85cb76..30cf2f5bec2 100644 --- a/src/Build/Instance/TaskFactoryLoggingHost.cs +++ b/src/Build/Instance/TaskFactoryLoggingHost.cs @@ -10,7 +10,6 @@ using System.Runtime.Remoting.Lifetime; using System.Runtime.Remoting; #endif -using System.Reflection; using Microsoft.Build.BackEnd.Logging; #nullable disable @@ -340,7 +339,7 @@ internal bool IsEventSerializable(BuildEventArgs e) #pragma warning disable SYSLIB0050 // Types which are not serializable and are not IExtendedBuildEventArgs as // those always implement custom serialization by WriteToStream and CreateFromStream. - if (!e.GetType().GetTypeInfo().IsSerializable && + if (!e.GetType().IsSerializable && e is not IExtendedBuildEventArgs && e is not GeneratedFileUsedEventArgs) #pragma warning restore SYSLIB0050 diff --git a/src/Build/Instance/TaskRegistry.cs b/src/Build/Instance/TaskRegistry.cs index b5e8a6c8bce..4e1e059835e 100644 --- a/src/Build/Instance/TaskRegistry.cs +++ b/src/Build/Instance/TaskRegistry.cs @@ -651,8 +651,8 @@ ConcurrentDictionary taskRecords /// private static bool IsTaskFactoryClass(Type type, object unused) { - return type.GetTypeInfo().IsClass && - !type.GetTypeInfo().IsAbstract && + return type.IsClass && + !type.IsAbstract && typeof(Microsoft.Build.Framework.ITaskFactory).IsAssignableFrom(type); } @@ -1544,7 +1544,7 @@ private bool GetTaskFactory(TargetLoggingContext targetLoggingContext, ElementLo // We have loaded the type, lets now try and construct it // Any exceptions from the constructor of the task factory will be caught lower down and turned into an InvalidProjectFileExceptions #if FEATURE_APPDOMAIN - factory = (ITaskFactory)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(loadedType.Type.GetTypeInfo().Assembly.FullName, loadedType.Type.FullName); + factory = (ITaskFactory)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(loadedType.Type.Assembly.FullName, loadedType.Type.FullName); #else factory = (ITaskFactory)Activator.CreateInstance(loadedType.Type); #endif @@ -1788,13 +1788,13 @@ private void ParseUsingTaskParameterGroupElement(UsingTaskParameterGroupEl // Visual Studio can load different version of Microsoft.Build.Framework.dll and non fully classified type could be resolved from it // which cause InvalidProjectFileException with "UnsupportedTaskParameterTypeError" message. // Another way to address this is to load types from compiled assembly - that would be more robust solution but also much more complex and risky code changes. - paramType = Type.GetType(expandedType + "," + typeof(ITaskItem).GetTypeInfo().Assembly.FullName, false /* don't throw on error */, true /* case-insensitive */) ?? + paramType = Type.GetType(expandedType + "," + typeof(ITaskItem).Assembly.FullName, false /* don't throw on error */, true /* case-insensitive */) ?? Type.GetType(expandedType); } else { paramType = Type.GetType(expandedType) ?? - Type.GetType(expandedType + "," + typeof(ITaskItem).GetTypeInfo().Assembly.FullName, false /* don't throw on error */, true /* case-insensitive */); + Type.GetType(expandedType + "," + typeof(ITaskItem).Assembly.FullName, false /* don't throw on error */, true /* case-insensitive */); } ProjectErrorUtilities.VerifyThrowInvalidProject( diff --git a/src/Build/Logging/LoggerDescription.cs b/src/Build/Logging/LoggerDescription.cs index 9b4e34e5c34..3db42f12351 100644 --- a/src/Build/Logging/LoggerDescription.cs +++ b/src/Build/Logging/LoggerDescription.cs @@ -256,9 +256,9 @@ private ILogger CreateLogger(bool forwardingLogger) /// true, if specified type is a logger private static bool IsForwardingLoggerClass(Type type, object unused) { - return type.GetTypeInfo().IsClass && - !type.GetTypeInfo().IsAbstract && - (type.GetTypeInfo().GetInterface("IForwardingLogger") != null); + return type.IsClass && + !type.IsAbstract && + (type.GetInterface("IForwardingLogger") != null); } /// @@ -268,9 +268,9 @@ private static bool IsForwardingLoggerClass(Type type, object unused) /// true, if specified type is a logger private static bool IsLoggerClass(Type type, object unused) { - return type.GetTypeInfo().IsClass && - !type.GetTypeInfo().IsAbstract && - (type.GetTypeInfo().GetInterface("ILogger") != null); + return type.IsClass && + !type.IsAbstract && + (type.GetInterface("ILogger") != null); } /// diff --git a/src/Build/Resources/AssemblyResources.cs b/src/Build/Resources/AssemblyResources.cs index 0eca428e261..3494531ee84 100644 --- a/src/Build/Resources/AssemblyResources.cs +++ b/src/Build/Resources/AssemblyResources.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; -using System.Reflection; using System.Resources; #nullable disable @@ -115,8 +114,8 @@ internal static ResourceManager SharedResources } // assembly resources - private static readonly ResourceManager s_resources = new ResourceManager("Microsoft.Build.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly); + private static readonly ResourceManager s_resources = new ResourceManager("Microsoft.Build.Strings", typeof(AssemblyResources).Assembly); // shared resources - private static readonly ResourceManager s_sharedResources = new ResourceManager("Microsoft.Build.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly); + private static readonly ResourceManager s_sharedResources = new ResourceManager("Microsoft.Build.Strings.shared", typeof(AssemblyResources).Assembly); } } diff --git a/src/Build/Resources/MSBuildAssemblyFileVersion.cs b/src/Build/Resources/MSBuildAssemblyFileVersion.cs index 14b044481eb..25078092d58 100644 --- a/src/Build/Resources/MSBuildAssemblyFileVersion.cs +++ b/src/Build/Resources/MSBuildAssemblyFileVersion.cs @@ -36,7 +36,7 @@ public static MSBuildAssemblyFileVersion Instance private static MSBuildAssemblyFileVersion GetMSBuildAssemblyFileVersion() { string versionString = typeof(MSBuildAssemblyFileVersion) - .GetTypeInfo() + ?.Assembly .GetCustomAttribute() ?.Version; diff --git a/src/BuildCheck.UnitTests/EditorConfig_Tests.cs b/src/BuildCheck.UnitTests/EditorConfig_Tests.cs index 58ff3c04668..1f440c6d234 100644 --- a/src/BuildCheck.UnitTests/EditorConfig_Tests.cs +++ b/src/BuildCheck.UnitTests/EditorConfig_Tests.cs @@ -25,8 +25,8 @@ private sealed class AssertEqualityComparer : IEqualityComparer private static bool CanBeNull() { var type = typeof(T); - return !type.GetTypeInfo().IsValueType || - (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); + return !type.IsValueType || + (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static bool IsNull(T @object) diff --git a/src/Framework.UnitTests/Attribute_Tests.cs b/src/Framework.UnitTests/Attribute_Tests.cs index 981047ff9a3..ee4699bd33f 100644 --- a/src/Framework.UnitTests/Attribute_Tests.cs +++ b/src/Framework.UnitTests/Attribute_Tests.cs @@ -20,7 +20,7 @@ public class AttributeTests public void RequiredRuntimeAttribute() { RequiredRuntimeAttribute attribute = - typeof(X).GetTypeInfo().GetCustomAttribute(); + typeof(X).GetCustomAttribute(); attribute.RuntimeVersion.ShouldBe("v5"); } diff --git a/src/Framework/AssemblyUtilities.cs b/src/Framework/AssemblyUtilities.cs index 6b21b7d22eb..819552cea79 100644 --- a/src/Framework/AssemblyUtilities.cs +++ b/src/Framework/AssemblyUtilities.cs @@ -55,16 +55,6 @@ public static string GetAssemblyLocation(Assembly assembly) #endif } -#if CLR2COMPATIBILITY - /// - /// Shim for the lack of in .NET 3.5. - /// - public static Type GetTypeInfo(this Type t) - { - return t; - } -#endif - public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone) { #if CLR2COMPATIBILITY diff --git a/src/Framework/NativeMethods.cs b/src/Framework/NativeMethods.cs index 23d09a573fd..d7b776262dd 100644 --- a/src/Framework/NativeMethods.cs +++ b/src/Framework/NativeMethods.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -884,7 +884,7 @@ internal static string FrameworkCurrentPath { if (s_frameworkCurrentPath == null) { - var baseTypeLocation = AssemblyUtilities.GetAssemblyLocation(typeof(string).GetTypeInfo().Assembly); + var baseTypeLocation = AssemblyUtilities.GetAssemblyLocation(typeof(string).Assembly); s_frameworkCurrentPath = Path.GetDirectoryName(baseTypeLocation) diff --git a/src/Framework/TaskPropertyInfo.cs b/src/Framework/TaskPropertyInfo.cs index 73e1f817e22..d36b5089bf0 100644 --- a/src/Framework/TaskPropertyInfo.cs +++ b/src/Framework/TaskPropertyInfo.cs @@ -28,7 +28,7 @@ public TaskPropertyInfo(string name, Type typeOfParameter, bool output, bool req Output = output; Required = required; Type elementType = typeOfParameter.IsArray ? typeOfParameter.GetElementType() : typeOfParameter; - IsValueTypeOutputParameter = elementType.GetTypeInfo().IsValueType || elementType.FullName.Equals("System.String"); + IsValueTypeOutputParameter = elementType.IsValueType || elementType.FullName.Equals("System.String"); IsAssignableToITask = typeof(ITaskItem).IsAssignableFrom(elementType); } diff --git a/src/MSBuild/AssemblyResources.cs b/src/MSBuild/AssemblyResources.cs index 041c55cc2b2..2436ca910f0 100644 --- a/src/MSBuild/AssemblyResources.cs +++ b/src/MSBuild/AssemblyResources.cs @@ -36,8 +36,8 @@ internal static string GetString(string name) } // assembly resources - private static readonly ResourceManager s_resources = new ResourceManager("MSBuild.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly); + private static readonly ResourceManager s_resources = new ResourceManager("MSBuild.Strings", typeof(AssemblyResources).Assembly); // shared resources - private static readonly ResourceManager s_sharedResources = new ResourceManager("MSBuild.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly); + private static readonly ResourceManager s_sharedResources = new ResourceManager("MSBuild.Strings.shared", typeof(AssemblyResources).Assembly); } } diff --git a/src/MSBuild/OutOfProcTaskHostNode.cs b/src/MSBuild/OutOfProcTaskHostNode.cs index 9b670a086d4..a5391eeddcc 100644 --- a/src/MSBuild/OutOfProcTaskHostNode.cs +++ b/src/MSBuild/OutOfProcTaskHostNode.cs @@ -1195,7 +1195,7 @@ private void SendBuildEvent(BuildEventArgs e) #pragma warning disable SYSLIB0050 // Types which are not serializable and are not IExtendedBuildEventArgs as // those always implement custom serialization by WriteToStream and CreateFromStream. - if (!e.GetType().GetTypeInfo().IsSerializable && e is not IExtendedBuildEventArgs) + if (!e.GetType().IsSerializable && e is not IExtendedBuildEventArgs) #pragma warning disable SYSLIB0050 { // log a warning and bail. This will end up re-calling SendBuildEvent, but we know for a fact diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 40f50fbeb26..0b60eba99c2 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -4178,7 +4178,7 @@ private static DistributedLoggerRecord CreateForwardingLoggerRecord(ILogger logg loggerParameters += ";FORWARDPROJECTCONTEXTEVENTS"; // Gets the currently loaded assembly in which the specified class is defined - Assembly engineAssembly = typeof(ProjectCollection).GetTypeInfo().Assembly; + Assembly engineAssembly = typeof(ProjectCollection).Assembly; string loggerClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription forwardingLoggerDescription = new LoggerDescription(loggerClassName, loggerAssemblyName, null, loggerParameters, effectiveVerbosity); @@ -4237,7 +4237,7 @@ internal static void ProcessDistributedFileLogger( } // Gets the currently loaded assembly in which the specified class is defined - Assembly engineAssembly = typeof(ProjectCollection).GetTypeInfo().Assembly; + Assembly engineAssembly = typeof(ProjectCollection).Assembly; string loggerClassName = "Microsoft.Build.Logging.DistributedFileLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; // Node the verbosity parameter is not used by the Distributed file logger so changing it here has no effect. It must be changed in the distributed file logger diff --git a/src/Samples/PortableTask/ShowItems.cs b/src/Samples/PortableTask/ShowItems.cs index 061f38bdb7d..ec4b5ef31e9 100644 --- a/src/Samples/PortableTask/ShowItems.cs +++ b/src/Samples/PortableTask/ShowItems.cs @@ -15,7 +15,7 @@ public class ShowItems : Microsoft.Build.Utilities.Task public override bool Execute() { - Assembly coreAssembly = typeof(object).GetTypeInfo().Assembly; + Assembly coreAssembly = typeof(object).Assembly; var coreAssemblyFileVersion = coreAssembly.GetCustomAttribute(); if (coreAssemblyFileVersion == null) diff --git a/src/Shared/CommunicationsUtilities.cs b/src/Shared/CommunicationsUtilities.cs index 87f748e9d6e..2cd50b8ca87 100644 --- a/src/Shared/CommunicationsUtilities.cs +++ b/src/Shared/CommunicationsUtilities.cs @@ -754,7 +754,7 @@ internal static HandshakeOptions GetHandshakeOptions( // No parameters given, default to current if (taskHostParameters == null) { - clrVersion = typeof(bool).GetTypeInfo().Assembly.GetName().Version.Major; + clrVersion = typeof(bool).Assembly.GetName().Version.Major; architectureFlagToSet = XMakeAttributes.GetCurrentMSBuildArchitecture(); } else // Figure out flags based on parameters given diff --git a/src/Shared/FileUtilities.cs b/src/Shared/FileUtilities.cs index 71259e9d412..6199161844d 100644 --- a/src/Shared/FileUtilities.cs +++ b/src/Shared/FileUtilities.cs @@ -16,7 +16,6 @@ using System.IO; using System.Globalization; using System.Linq; -using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; @@ -765,7 +764,7 @@ internal static bool HasExtension(string fileName, string[] allowedExtensions) /// /// Get the currently executing assembly path /// - internal static string ExecutingAssemblyPath => Path.GetFullPath(AssemblyUtilities.GetAssemblyLocation(typeof(FileUtilities).GetTypeInfo().Assembly)); + internal static string ExecutingAssemblyPath => Path.GetFullPath(AssemblyUtilities.GetAssemblyLocation(typeof(FileUtilities).Assembly)); /// /// Determines the full path for the given file-spec. @@ -1603,4 +1602,4 @@ internal static void ReadExactly(this Stream stream, byte[] buffer, int offset, } } } -#endif \ No newline at end of file +#endif diff --git a/src/Shared/LoadedType.cs b/src/Shared/LoadedType.cs index 6be0b228a75..6d68d3d47a1 100644 --- a/src/Shared/LoadedType.cs +++ b/src/Shared/LoadedType.cs @@ -107,8 +107,8 @@ internal LoadedType(Type type, AssemblyLoadInfo assemblyLoadInfo, Assembly loade } #else // For v3.5 fallback to old full type approach, as oppose to reflection only - HasLoadInSeparateAppDomainAttribute = this.Type.GetTypeInfo().IsDefined(typeof(LoadInSeparateAppDomainAttribute), true /* inherited */); - HasSTAThreadAttribute = this.Type.GetTypeInfo().IsDefined(typeof(RunInSTAAttribute), true /* inherited */); + HasLoadInSeparateAppDomainAttribute = this.Type.IsDefined(typeof(LoadInSeparateAppDomainAttribute), true /* inherited */); + HasSTAThreadAttribute = this.Type.IsDefined(typeof(RunInSTAAttribute), true /* inherited */); IsMarshalByRef = this.Type.IsMarshalByRef; #endif } @@ -140,7 +140,7 @@ private bool CheckForHardcodedSTARequirement() // we changed to running all tasks in MTA. if (String.Equals("Microsoft.Build.Tasks.Xaml.PartialClassGenerationTask", Type.FullName, StringComparison.OrdinalIgnoreCase)) { - AssemblyName assemblyName = Type.GetTypeInfo().Assembly.GetName(); + AssemblyName assemblyName = Type.Assembly.GetName(); Version lastVersionToForce = new Version(3, 5); if (assemblyName.Version?.CompareTo(lastVersionToForce) > 0) { diff --git a/src/Shared/TaskLoader.cs b/src/Shared/TaskLoader.cs index 602a36871ed..88e588e28a1 100644 --- a/src/Shared/TaskLoader.cs +++ b/src/Shared/TaskLoader.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Reflection; using Microsoft.Build.Framework; namespace Microsoft.Build.Shared @@ -32,8 +31,8 @@ internal static class TaskLoader /// true, if specified type is a task internal static bool IsTaskClass(Type type, object unused) { - return type.GetTypeInfo().IsClass && !type.GetTypeInfo().IsAbstract && ( - type.GetTypeInfo().GetInterface("Microsoft.Build.Framework.ITask") != null); + return type.IsClass && !type.IsAbstract && + type.GetInterface("Microsoft.Build.Framework.ITask") != null; } /// @@ -146,14 +145,14 @@ bool isOutOfProc taskColumn, "ConflictingTaskAssembly", loadedType.Assembly.AssemblyFile, - loadedType.Type.GetTypeInfo().Assembly.Location); + loadedType.Type.Assembly.Location); taskInstanceInOtherAppDomain = null; } } else { - taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.GetTypeInfo().Assembly.FullName, loadedType.Type.FullName); + taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.Assembly.FullName, loadedType.Type.FullName); } return taskInstanceInOtherAppDomain; diff --git a/src/Shared/TaskParameter.cs b/src/Shared/TaskParameter.cs index f7a53882283..527f3d302ab 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -5,7 +5,9 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Reflection; +using System.Linq; +using Microsoft.Build.Collections; + #if FEATURE_APPDOMAIN using System.Security; #endif @@ -124,7 +126,7 @@ public TaskParameter(object wrappedParameter) _parameterTypeCode = typeCode; _wrappedParameter = wrappedParameter; } - else if (typeof(ITaskItem[]).GetTypeInfo().IsAssignableFrom(wrappedParameterType.GetTypeInfo())) + else if (typeof(ITaskItem[]).IsAssignableFrom(wrappedParameterType)) { _parameterType = TaskParameterType.ITaskItemArray; ITaskItem[] inputAsITaskItemArray = (ITaskItem[])wrappedParameter; @@ -140,7 +142,7 @@ public TaskParameter(object wrappedParameter) _wrappedParameter = taskItemArrayParameter; } - else if (wrappedParameterType.GetElementType().GetTypeInfo().IsValueType) + else if (wrappedParameterType.GetElementType().IsValueType) { _parameterType = TaskParameterType.ValueTypeArray; _wrappedParameter = wrappedParameter; @@ -175,7 +177,7 @@ public TaskParameter(object wrappedParameter) _parameterType = TaskParameterType.ITaskItem; _wrappedParameter = CreateNewTaskItemFrom((ITaskItem)wrappedParameter); } - else if (wrappedParameterType.GetTypeInfo().IsValueType) + else if (wrappedParameterType.IsValueType) { _parameterType = TaskParameterType.ValueType; _wrappedParameter = wrappedParameter; diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 2b7d6160d84..533ff19c251 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Reflection; using Microsoft.Build.Framework; #if NET35 using Microsoft.Build.Shared; @@ -21,14 +20,14 @@ internal static class TaskParameterTypeVerifier /// Is the parameter type a valid scalar input value /// internal static bool IsValidScalarInputParameter(Type parameterType) => - parameterType.GetTypeInfo().IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem); + parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem); /// /// Is the passed in parameterType a valid vector input parameter /// internal static bool IsValidVectorInputParameter(Type parameterType) { - bool result = (parameterType.IsArray && parameterType.GetElementType().GetTypeInfo().IsValueType) || + bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || parameterType == typeof(string[]) || parameterType == typeof(ITaskItem[]); return result; @@ -39,8 +38,8 @@ internal static bool IsValidVectorInputParameter(Type parameterType) /// internal static bool IsAssignableToITask(Type parameterType) { - bool result = typeof(ITaskItem[]).GetTypeInfo().IsAssignableFrom(parameterType.GetTypeInfo()) || /* ITaskItem array or derived type, or */ - typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ + bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || /* ITaskItem array or derived type, or */ + typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ return result; } @@ -49,10 +48,10 @@ internal static bool IsAssignableToITask(Type parameterType) /// internal static bool IsValueTypeOutputParameter(Type parameterType) { - bool result = (parameterType.IsArray && parameterType.GetElementType().GetTypeInfo().IsValueType) || /* array of value types, or */ - parameterType == typeof(string[]) || /* string array, or */ - parameterType.GetTypeInfo().IsValueType || /* value type, or */ - parameterType == typeof(string); /* string */ + bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || /* array of value types, or */ + parameterType == typeof(string[]) || /* string array, or */ + parameterType.IsValueType || /* value type, or */ + parameterType == typeof(string); /* string */ return result; } diff --git a/src/Shared/Tracing.cs b/src/Shared/Tracing.cs index 70b8d4e0792..9189c001109 100644 --- a/src/Shared/Tracing.cs +++ b/src/Shared/Tracing.cs @@ -7,7 +7,6 @@ #if DEBUG using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Reflection; #endif #nullable disable @@ -68,7 +67,7 @@ static Tracing() s_interval = TimeSpan.FromSeconds(1); } - s_currentAssemblyName = typeof(Tracing).GetTypeInfo().Assembly.GetName().Name; + s_currentAssemblyName = typeof(Tracing).Assembly.GetName().Name; // Trace.WriteLine(new string('/', 100)); // Trace.WriteLine("interval: " + interval.Seconds); diff --git a/src/Tasks/AssemblyResources.cs b/src/Tasks/AssemblyResources.cs index 51a9b19d201..9bf6db29c8c 100644 --- a/src/Tasks/AssemblyResources.cs +++ b/src/Tasks/AssemblyResources.cs @@ -34,14 +34,14 @@ internal static string GetString(string name) /// /// This property is thread-safe. /// ResourceManager for primary resources. - internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly); + internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings", typeof(AssemblyResources).Assembly); /// /// Gets the assembly's shared resources i.e. the resources this assembly shares with other assemblies. /// /// This property is thread-safe. /// ResourceManager for shared resources. - internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly); + internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings.shared", typeof(AssemblyResources).Assembly); // assembly resources // shared resources diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs index d5d9ebda785..3229c9976e1 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs @@ -89,7 +89,7 @@ public sealed class RoslynCodeTaskFactory : ITaskFactory /// /// Stores the path to the directory that this assembly is located in. /// - private static readonly Lazy ThisAssemblyDirectoryLazy = new Lazy(() => Path.GetDirectoryName(typeof(RoslynCodeTaskFactory).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName)); + private static readonly Lazy ThisAssemblyDirectoryLazy = new Lazy(() => Path.GetDirectoryName(typeof(RoslynCodeTaskFactory).Assembly.ManifestModule.FullyQualifiedName)); /// /// Stores an instance of a for logging messages. diff --git a/src/UnitTests.Shared/MockLogger.cs b/src/UnitTests.Shared/MockLogger.cs index ba8c937e598..eac19aa3dad 100644 --- a/src/UnitTests.Shared/MockLogger.cs +++ b/src/UnitTests.Shared/MockLogger.cs @@ -445,7 +445,7 @@ private void PrintFullLog() // Lazy-init property returning the MSBuild engine resource manager private static ResourceManager EngineResourceManager => s_engineResourceManager ?? (s_engineResourceManager = new ResourceManager( "Microsoft.Build.Strings", - typeof(ProjectCollection).GetTypeInfo().Assembly)); + typeof(ProjectCollection).Assembly)); private static ResourceManager s_engineResourceManager; private bool _reportTelemetry; diff --git a/src/Utilities.UnitTests/MockTask.cs b/src/Utilities.UnitTests/MockTask.cs index e72febfb0e6..d032f90b33a 100644 --- a/src/Utilities.UnitTests/MockTask.cs +++ b/src/Utilities.UnitTests/MockTask.cs @@ -24,7 +24,7 @@ internal MockTask(bool registerResources) } } - private void RegisterResources() => Log.TaskResources = new ResourceManager("Microsoft.Build.Utilities.UnitTests.strings", typeof(MockTask).GetTypeInfo().Assembly); + private void RegisterResources() => Log.TaskResources = new ResourceManager("Microsoft.Build.Utilities.UnitTests.strings", typeof(MockTask).Assembly); public override bool Execute() => true; } diff --git a/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs b/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs index a14605728ea..532d4873a48 100644 --- a/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs +++ b/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs @@ -512,14 +512,14 @@ public void VerifyinternalGetPathToDotNetFrameworkSdkFileNullPassedIn() public void FindFrameworksPathRunningThisTest() { string path = FrameworkLocationHelper.FindDotNetFrameworkPath( - Path.GetDirectoryName(typeof(object).GetTypeInfo().Module.FullyQualifiedName), + Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName), ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.Version40), DirectoryExists, GetDirectories, SharedDotNetFrameworkArchitecture.Current); #if FEATURE_INSTALLED_MSBUILD - path.ShouldBe(Path.GetDirectoryName(typeof(object).GetTypeInfo().Module.FullyQualifiedName)); + path.ShouldBe(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)); #else path.ShouldBeNull(); #endif diff --git a/src/Utilities/AssemblyResources.cs b/src/Utilities/AssemblyResources.cs index 3258aecf36d..b8c81daa33b 100644 --- a/src/Utilities/AssemblyResources.cs +++ b/src/Utilities/AssemblyResources.cs @@ -35,14 +35,14 @@ internal static string GetString(string name) /// /// This property is thread-safe. /// ResourceManager for primary resources. - internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly); + internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings", typeof(AssemblyResources).Assembly); /// /// Gets the assembly's shared resources i.e. the resources this assembly shares with other assemblies. /// /// This property is thread-safe. /// ResourceManager for shared resources. - internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly); + internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings.shared", typeof(AssemblyResources).Assembly); /// /// Formats the given string using the variable arguments passed in. The current thread's culture is used for formatting. From de14c36e150a25b36b8755fe6aefbd2c98016f91 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:32:43 +0300 Subject: [PATCH 2/8] Remove `Assembly` polyfills and the `FEATURE_ASSEMBLY_LOCATION` directive. --- .../BackEnd/AssemblyTaskFactory_Tests.cs | 6 +-- .../BackEnd/LoggingService_Tests.cs | 39 ------------------- .../BackEnd/TaskRegistry_Tests.cs | 2 +- .../Definition/ItemDefinitionGroup_Tests.cs | 4 +- .../EscapingInProjects_Tests.cs | 7 ++-- .../Instance/TaskFactories/TaskHostTask.cs | 4 +- src/Directory.BeforeCommon.targets | 3 +- src/Framework/AssemblyUtilities.cs | 33 +--------------- src/Framework/NativeMethods.cs | 2 +- src/MSBuild/XMake.cs | 4 -- src/Shared/BuildEnvironmentHelper.cs | 7 ++-- src/Shared/FileUtilities.cs | 2 +- src/Shared/UnitTests/TypeLoader_Tests.cs | 6 +-- 13 files changed, 18 insertions(+), 101 deletions(-) diff --git a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs index cb836c84f2e..d89ffb71824 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs @@ -683,11 +683,7 @@ public void VerifySameFactoryCanGenerateDifferentTaskInstances() private void SetupTaskFactory(IDictionary factoryParameters, bool explicitlyLaunchTaskHost) { _taskFactory = new AssemblyTaskFactory(); -#if FEATURE_ASSEMBLY_LOCATION - _loadInfo = AssemblyLoadInfo.Create(null, Assembly.GetAssembly(typeof(TaskToTestFactories)).Location); -#else - _loadInfo = AssemblyLoadInfo.Create(typeof(TaskToTestFactories).Assembly.FullName, null); -#endif + _loadInfo = AssemblyLoadInfo.Create(null, typeof(TaskToTestFactories).Assembly.Location); _loadedType = _taskFactory.InitializeFactory(_loadInfo, "TaskToTestFactories", new Dictionary(), string.Empty, factoryParameters, explicitlyLaunchTaskHost, null, ElementLocation.Create("NONE"), String.Empty); Assert.True(_loadedType.Assembly.Equals(_loadInfo)); // "Expected the AssemblyLoadInfo to be equal" } diff --git a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs index 7125997276a..ef99f2e38fe 100644 --- a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs @@ -331,11 +331,7 @@ public void RegisterDistributedLoggerServiceShutdown() { _initializedService.ShutdownComponent(); string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); -#endif _initializedService.RegisterDistributedLogger(null, description); }); } @@ -347,13 +343,8 @@ public void RegisterGoodDistributedAndCentralLogger() { string configurableClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string distributedClassName = "Microsoft.Build.Logging.DistributedFileLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); - LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).Assembly.FullName, true); LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).Assembly.FullName, true); -#endif DistributedFileLogger fileLogger = new DistributedFileLogger(); RegularILogger regularILogger = new RegularILogger(); @@ -384,13 +375,8 @@ public void RegisterGoodDistributedAndCentralLoggerTestBuildStartedFinished() string configurableClassNameA = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string configurableClassNameB = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); - LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, typeof(ProjectCollection).Assembly.FullName, true); LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, typeof(ProjectCollection).Assembly.FullName, true); -#endif RegularILogger regularILoggerA = new RegularILogger(); RegularILogger regularILoggerB = new RegularILogger(); @@ -430,11 +416,7 @@ public void RegisterGoodDistributedAndCentralLoggerTestBuildStartedFinished() public void RegisterDuplicateCentralLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); -#endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); @@ -458,11 +440,7 @@ public void RegisterDuplicateCentralLogger() public void RegisterDuplicateForwardingLoggerLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); -#endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); @@ -523,11 +501,7 @@ public void NullForwardingLoggerSink() Assert.Throws(() => { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); -#endif _initializedService.ShutdownComponent(); List tempList = new List(); tempList.Add(description); @@ -545,13 +519,8 @@ public void RegisterGoodDiscriptions() EventSourceSink sink = new EventSourceSink(); EventSourceSink sink2 = new EventSourceSink(); List loggerDescriptions = new List(); -#if FEATURE_ASSEMBLY_LOCATION - loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); - loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true)); -#else loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).Assembly.FullName, true)); loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).Assembly.FullName, true)); -#endif // Register some descriptions with a sink _initializedService.InitializeNodeLoggers(loggerDescriptions, sink, 1); @@ -608,11 +577,7 @@ public void RegisterGoodDiscriptions() public void RegisterDuplicateDistributedCentralLogger() { string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; -#if FEATURE_ASSEMBLY_LOCATION - LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true); -#else LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).Assembly.FullName, true); -#endif RegularILogger regularILogger = new RegularILogger(); Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description)); @@ -1105,11 +1070,7 @@ private void VerifyShutdownExceptions(ILogger logger, string className, Type exp InitializeLoggingService(); if (className != null) { -#if FEATURE_ASSEMBLY_LOCATION - Assembly thisAssembly = Assembly.GetAssembly(typeof(LoggingService_Tests)); -#else Assembly thisAssembly = typeof(LoggingService_Tests).Assembly; -#endif string loggerAssemblyName = thisAssembly.FullName; LoggerDescription centralLoggerDescrption = CreateLoggerDescription(className, loggerAssemblyName, true); _initializedService.RegisterDistributedLogger(null, centralLoggerDescrption); diff --git a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs index ca008ba2a9b..7eb2b9f63e1 100644 --- a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs @@ -1237,7 +1237,7 @@ public void TaskFactoryWithNullTaskTypeLogsError() List elementList = new List(); ProjectRootElement project = ProjectRootElement.Create(); - ProjectUsingTaskElement element = project.AddUsingTask("Task1", AssemblyUtilities.GetAssemblyLocation(typeof(TaskRegistry_Tests.NullTaskTypeTaskFactory).Assembly), null); + ProjectUsingTaskElement element = project.AddUsingTask("Task1", typeof(TaskRegistry_Tests.NullTaskTypeTaskFactory).Assembly.Location, null); element.TaskFactory = typeof(NullTaskTypeTaskFactory).FullName; elementList.Add(element); diff --git a/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs b/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs index f7cb141db85..23a3f652dab 100644 --- a/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs +++ b/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs @@ -1070,7 +1070,6 @@ public void ItemDefinitionInTargetErrors() }); } -#if FEATURE_ASSEMBLY_LOCATION // Verify that anyone with a task named "ItemDefinitionGroup" can still // use it by fully qualifying the name. [Fact] @@ -1083,11 +1082,10 @@ public void ItemDefinitionGroupTask() - ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath)); + ", Assembly.GetExecutingAssembly().Location)); Assert.Contains("In ItemDefinitionGroup task.", ml.FullLog); } -#endif [Fact] public void MetadataOnItemWins() diff --git a/src/Build.UnitTests/EscapingInProjects_Tests.cs b/src/Build.UnitTests/EscapingInProjects_Tests.cs index 2f2931fc8e3..40e1075fdf9 100644 --- a/src/Build.UnitTests/EscapingInProjects_Tests.cs +++ b/src/Build.UnitTests/EscapingInProjects_Tests.cs @@ -24,6 +24,7 @@ using Shouldly; using Xunit; using Xunit.Abstractions; +using System.Reflection; #if FEATURE_COMPILE_IN_TESTS using Microsoft.Build.Shared; #endif @@ -124,7 +125,6 @@ public void SemicolonInPropertyPassedIntoStringParam_UsingTaskHost() logger.AssertLogContains("Property value is 'abc ; def ; ghi'"); } -#if FEATURE_ASSEMBLY_LOCATION /// /// Make sure I can define a property with escaped characters and pass it into /// an ITaskItem[] task parameter. @@ -136,7 +136,7 @@ public void SemicolonInPropertyPassedIntoITaskItemParam() - + abc %3b def %3b ghi @@ -177,12 +177,11 @@ public void SemicolonInPropertyPassedIntoITaskItemParam_UsingTaskHost() - ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath), + ", Assembly.GetExecutingAssembly().Location), logger: new MockLogger(_output)); logger.AssertLogContains("Received TaskItemParam: 123 abc ; def ; ghi 789"); } -#endif /// /// If I try to add a new item to a project, and my new item's Include has an unescaped semicolon diff --git a/src/Build/Instance/TaskFactories/TaskHostTask.cs b/src/Build/Instance/TaskFactories/TaskHostTask.cs index 3aeee326c08..c3090561640 100644 --- a/src/Build/Instance/TaskFactories/TaskHostTask.cs +++ b/src/Build/Instance/TaskFactories/TaskHostTask.cs @@ -280,7 +280,7 @@ public bool Execute() BuildEngine.ProjectFileOfTaskNode, BuildEngine.ContinueOnError, _taskType.Type.FullName, - AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly), + _taskType.Type.Assembly.Location, _buildComponentHost.BuildParameters.LogTaskInputs, _setParameters, new Dictionary(_buildComponentHost.BuildParameters.GlobalProperties), @@ -497,7 +497,7 @@ private void HandleTaskHostTaskComplete(TaskHostTaskComplete taskHostTaskComplet else { exceptionMessageArgs = [_taskType.Type.Name, - AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly), + _taskType.Type.Assembly.Location, string.Empty]; } diff --git a/src/Directory.BeforeCommon.targets b/src/Directory.BeforeCommon.targets index 73b91fe6c96..e774f391e30 100644 --- a/src/Directory.BeforeCommon.targets +++ b/src/Directory.BeforeCommon.targets @@ -1,4 +1,4 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) @@ -20,7 +20,6 @@ $(DefineConstants);FEATURE_APPDOMAIN true $(DefineConstants);FEATURE_ASPNET_COMPILER - $(DefineConstants);FEATURE_ASSEMBLY_LOCATION $(DefineConstants);FEATURE_COMPILED_XSL $(DefineConstants);FEATURE_COMPILE_IN_TESTS $(DefineConstants);FEATURE_CONSTRAINED_EXECUTION diff --git a/src/Framework/AssemblyUtilities.cs b/src/Framework/AssemblyUtilities.cs index 819552cea79..9181eb9f893 100644 --- a/src/Framework/AssemblyUtilities.cs +++ b/src/Framework/AssemblyUtilities.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -24,37 +24,11 @@ internal static class AssemblyUtilities private static bool s_initialized; // Cached method info - private static PropertyInfo s_assemblylocationProperty; private static MethodInfo s_cultureInfoGetCultureMethod; private static Lazy s_validCultures = new Lazy(() => GetValidCultures(), true); #endif -#if !CLR2COMPATIBILITY - private static Lazy s_entryAssembly = new Lazy(() => GetEntryAssembly()); - public static Assembly EntryAssembly => s_entryAssembly.Value; -#else - public static Assembly EntryAssembly = GetEntryAssembly(); -#endif - - public static string GetAssemblyLocation(Assembly assembly) - { -#if FEATURE_ASSEMBLY_LOCATION - return assembly.Location; -#else - // Assembly.Location is only available in .netstandard1.5, but MSBuild needs to target 1.3. - // use reflection to access the property - Initialize(); - - if (s_assemblylocationProperty == null) - { - throw new NotSupportedException("Type Assembly does not have the Location property"); - } - - return (string)s_assemblylocationProperty.GetValue(assembly); -#endif - } - public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone) { #if CLR2COMPATIBILITY @@ -133,11 +107,6 @@ private static void Initialize() } #endif // !FEATURE_CULTUREINFO_GETCULTURES - private static Assembly GetEntryAssembly() - { - return System.Reflection.Assembly.GetEntryAssembly(); - } - #if !FEATURE_CULTUREINFO_GETCULTURES private static CultureInfo[] GetValidCultures() { diff --git a/src/Framework/NativeMethods.cs b/src/Framework/NativeMethods.cs index d7b776262dd..c776259cc97 100644 --- a/src/Framework/NativeMethods.cs +++ b/src/Framework/NativeMethods.cs @@ -884,7 +884,7 @@ internal static string FrameworkCurrentPath { if (s_frameworkCurrentPath == null) { - var baseTypeLocation = AssemblyUtilities.GetAssemblyLocation(typeof(string).Assembly); + var baseTypeLocation = typeof(string).Assembly.Location; s_frameworkCurrentPath = Path.GetDirectoryName(baseTypeLocation) diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 0b60eba99c2..b4a2a906fe2 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1500,11 +1500,7 @@ internal static bool BuildProject( parameters.EnableNodeReuse = enableNodeReuse; parameters.LowPriority = lowPriority; -#if FEATURE_ASSEMBLY_LOCATION parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location; -#else - parameters.NodeExeLocation = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath; -#endif parameters.MaxNodeCount = cpuCount; parameters.MultiThreaded = multiThreaded; parameters.Loggers = projectCollection.Loggers; diff --git a/src/Shared/BuildEnvironmentHelper.cs b/src/Shared/BuildEnvironmentHelper.cs index a81e5a9041a..82f05b5eaed 100644 --- a/src/Shared/BuildEnvironmentHelper.cs +++ b/src/Shared/BuildEnvironmentHelper.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.Shared.FileSystem; @@ -426,14 +427,14 @@ private static bool IsProcessInList(string processName, string[] processList) private static string GetProcessFromRunningProcess() { #if RUNTIME_TYPE_NETCORE - // The EntryAssembly property can return null when a managed assembly has been loaded from + // Assembly.GetEntryAssembly() can return null when a managed assembly has been loaded from // an unmanaged application (for example, using custom CLR hosting). - if (AssemblyUtilities.EntryAssembly == null) + if (Assembly.GetEntryAssembly() is not { } entryAsm) { return EnvironmentUtilities.ProcessPath; } - return AssemblyUtilities.GetAssemblyLocation(AssemblyUtilities.EntryAssembly); + return entryAsm.Location; #else return EnvironmentUtilities.ProcessPath; diff --git a/src/Shared/FileUtilities.cs b/src/Shared/FileUtilities.cs index 6199161844d..c55cb6e37c4 100644 --- a/src/Shared/FileUtilities.cs +++ b/src/Shared/FileUtilities.cs @@ -764,7 +764,7 @@ internal static bool HasExtension(string fileName, string[] allowedExtensions) /// /// Get the currently executing assembly path /// - internal static string ExecutingAssemblyPath => Path.GetFullPath(AssemblyUtilities.GetAssemblyLocation(typeof(FileUtilities).Assembly)); + internal static string ExecutingAssemblyPath => Path.GetFullPath(typeof(FileUtilities).Assembly.Location); /// /// Determines the full path for the given file-spec. diff --git a/src/Shared/UnitTests/TypeLoader_Tests.cs b/src/Shared/UnitTests/TypeLoader_Tests.cs index a63894695da..94e80006318 100644 --- a/src/Shared/UnitTests/TypeLoader_Tests.cs +++ b/src/Shared/UnitTests/TypeLoader_Tests.cs @@ -223,7 +223,6 @@ private void CheckIfCorrectAssemblyLoaded(string scriptOutput, string expectedAs } } -#if FEATURE_ASSEMBLY_LOCATION /// /// Make sure that when we load multiple types out of the same assembly with different type filters that both the fullyqualified name matching and the /// partial name matching still work. @@ -322,15 +321,14 @@ private static bool IsLoggerClass(Type type, object unused) { return type.IsClass && !type.IsAbstract && - (type.GetInterface("ILogger") != null); + type.GetInterface("ILogger") != null; } private static bool IsForwardingLoggerClass(Type type, object unused) { return type.IsClass && !type.IsAbstract && - (type.GetInterface("IForwardingLogger") != null); + type.GetInterface("IForwardingLogger") != null; } -#endif } } From 5cf43dea4a4eec5bb7fe9303ab4ee39598b489aa Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:33:48 +0300 Subject: [PATCH 3/8] Remove `FEATURE_CULTUREINFO_GETCULTURES` as always available. --- .../Evaluation/Expander_Tests.cs | 4 - src/Directory.BeforeCommon.targets | 3 +- src/Framework/AssemblyUtilities.cs | 78 -- src/Tasks/CultureInfoCache.cs | 870 +----------------- 4 files changed, 2 insertions(+), 953 deletions(-) diff --git a/src/Build.UnitTests/Evaluation/Expander_Tests.cs b/src/Build.UnitTests/Evaluation/Expander_Tests.cs index c39c1c358aa..d2a446e8de0 100644 --- a/src/Build.UnitTests/Evaluation/Expander_Tests.cs +++ b/src/Build.UnitTests/Evaluation/Expander_Tests.cs @@ -3487,11 +3487,7 @@ public void PropertyFunctionStaticMethodGetCultureInfo() Expander expander = new Expander(pg, FileSystems.Default); -#if FEATURE_CULTUREINFO_GETCULTURES string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Globalization.CultureInfo]::GetCultureInfo(`en-US`).ToString())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); -#else - string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.Globalization.CultureInfo]::new(`en-US`).ToString())", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); -#endif Assert.Equal(new CultureInfo("en-US").ToString(), result); } diff --git a/src/Directory.BeforeCommon.targets b/src/Directory.BeforeCommon.targets index e774f391e30..ea19e0466d2 100644 --- a/src/Directory.BeforeCommon.targets +++ b/src/Directory.BeforeCommon.targets @@ -1,4 +1,4 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) @@ -25,7 +25,6 @@ $(DefineConstants);FEATURE_CONSTRAINED_EXECUTION $(DefineConstants);FEATURE_CODETASKFACTORY $(DefineConstants);FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES - $(DefineConstants);FEATURE_CULTUREINFO_GETCULTURES $(DefineConstants);FEATURE_ENCODING_DEFAULT $(DefineConstants);FEATURE_ENVIRONMENT_SYSTEMDIRECTORY $(DefineConstants);FEATURE_FILE_TRACKER diff --git a/src/Framework/AssemblyUtilities.cs b/src/Framework/AssemblyUtilities.cs index 9181eb9f893..b6eba1828a5 100644 --- a/src/Framework/AssemblyUtilities.cs +++ b/src/Framework/AssemblyUtilities.cs @@ -1,15 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Globalization; using System.Reflection; -#if !FEATURE_CULTUREINFO_GETCULTURES -using System.Linq; -using Microsoft.Build.Framework; -#endif - #nullable disable namespace Microsoft.Build.Shared @@ -19,16 +12,6 @@ namespace Microsoft.Build.Shared /// internal static class AssemblyUtilities { -#if !FEATURE_CULTUREINFO_GETCULTURES - // True when the cached method info objects have been set. - private static bool s_initialized; - - // Cached method info - private static MethodInfo s_cultureInfoGetCultureMethod; - - private static Lazy s_validCultures = new Lazy(() => GetValidCultures(), true); -#endif - public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone) { #if CLR2COMPATIBILITY @@ -65,66 +48,5 @@ public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone #endif } - -#if !FEATURE_CULTUREINFO_GETCULTURES - public static bool CultureInfoHasGetCultures() - { - return s_cultureInfoGetCultureMethod != null; - } -#endif // !FEATURE_CULTUREINFO_GETCULTURES - - public static CultureInfo[] GetAllCultures() - { -#if FEATURE_CULTUREINFO_GETCULTURES - return CultureInfo.GetCultures(CultureTypes.AllCultures); -#else - Initialize(); - - if (!CultureInfoHasGetCultures()) - { - throw new NotSupportedException("CultureInfo does not have the method GetCultures"); - } - - return s_validCultures.Value; -#endif - } - -#if !FEATURE_CULTUREINFO_GETCULTURES - /// - /// Initialize static fields. Doesn't need to be thread safe. - /// - private static void Initialize() - { - if (s_initialized) - { - return; - } - - s_assemblylocationProperty = typeof(Assembly).GetProperty("Location", typeof(string)); - s_cultureInfoGetCultureMethod = typeof(CultureInfo).GetMethod("GetCultures"); - - s_initialized = true; - } -#endif // !FEATURE_CULTUREINFO_GETCULTURES - -#if !FEATURE_CULTUREINFO_GETCULTURES - private static CultureInfo[] GetValidCultures() - { - var cultureTypesType = s_cultureInfoGetCultureMethod?.GetParameters().FirstOrDefault()?.ParameterType; - - FrameworkErrorUtilities.VerifyThrow(cultureTypesType?.Name == "CultureTypes" && - Enum.IsDefined(cultureTypesType, "AllCultures"), - "GetCulture is expected to accept CultureTypes.AllCultures"); - - var allCulturesEnumValue = Enum.Parse(cultureTypesType, "AllCultures", true); - - var cultures = s_cultureInfoGetCultureMethod.Invoke(null, [allCulturesEnumValue]) as CultureInfo[]; - - // CultureInfo.GetCultures should work if all reflection checks pass - FrameworkErrorUtilities.VerifyThrowInternalNull(cultures); - - return cultures; - } -#endif } } diff --git a/src/Tasks/CultureInfoCache.cs b/src/Tasks/CultureInfoCache.cs index 66baa32d31f..183cafb2fb2 100644 --- a/src/Tasks/CultureInfoCache.cs +++ b/src/Tasks/CultureInfoCache.cs @@ -7,7 +7,6 @@ using System.Linq; #else using System.Collections.Generic; -using Microsoft.Build.Shared; #endif #nullable disable @@ -36,14 +35,8 @@ internal static class CultureInfoCache #if !NET private static HashSet InitializeValidCultureNames() { -#if !FEATURE_CULTUREINFO_GETCULTURES - if (!AssemblyUtilities.CultureInfoHasGetCultures()) - { - return HardcodedCultureNames; - } -#endif HashSet validCultureNames = new(StringComparer.OrdinalIgnoreCase); - foreach (CultureInfo cultureName in AssemblyUtilities.GetAllCultures()) + foreach (CultureInfo cultureName in CultureInfo.GetCultures(CultureTypes.AllCultures)) { validCultureNames.Add(cultureName.Name); } @@ -81,866 +74,5 @@ internal static bool IsValidCultureString(string name) return ValidCultureNames.Value.Contains(name); #endif } - -#if !NET && !FEATURE_CULTUREINFO_GETCULTURES - // Copied from https://github.com/aspnet/Localization/blob/5e1fb16071affd15f15b9c732833f3ae2ac46e10/src/Microsoft.Framework.Globalization.CultureInfoCache/CultureInfoList.cs - // Regenerated using the tool (removed by https://github.com/aspnet/Localization/pull/130) - // * Removed the empty string from the list - // * Any cultures not present when regenerated were retained - // * Added the Windows pseudo-locales - private static readonly HashSet HardcodedCultureNames = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "aa", - "aa-DJ", - "aa-ER", - "aa-ET", - "af", - "af-NA", - "af-ZA", - "agq", - "agq-CM", - "ak", - "ak-GH", - "am", - "am-ET", - "ar", - "ar-001", - "ar-AE", - "ar-BH", - "ar-DJ", - "ar-DZ", - "ar-EG", - "ar-ER", - "ar-IL", - "ar-IQ", - "ar-JO", - "ar-KM", - "ar-KW", - "ar-LB", - "ar-LY", - "ar-MA", - "ar-MR", - "ar-OM", - "ar-PS", - "ar-QA", - "ar-SA", - "ar-SD", - "ar-SO", - "ar-SS", - "ar-SY", - "ar-TD", - "ar-TN", - "ar-YE", - "arn", - "arn-CL", - "as", - "as-IN", - "asa", - "asa-TZ", - "ast", - "ast-ES", - "az", - "az-Cyrl", - "az-Cyrl-AZ", - "az-Latn", - "az-Latn-AZ", - "ba", - "ba-RU", - "bas", - "bas-CM", - "be", - "be-BY", - "bem", - "bem-ZM", - "bez", - "bez-TZ", - "bg", - "bg-BG", - "bin", - "bin-NG", - "bm", - "bm-Latn", - "bm-Latn-ML", - "bn", - "bn-BD", - "bn-IN", - "bo", - "bo-CN", - "bo-IN", - "br", - "br-FR", - "brx", - "brx-IN", - "bs", - "bs-Cyrl", - "bs-Cyrl-BA", - "bs-Latn", - "bs-Latn-BA", - "byn", - "byn-ER", - "ca", - "ca-AD", - "ca-ES", - "ca-ES-valencia", - "ca-FR", - "ca-IT", - "ce", - "ce-RU", - "cgg", - "cgg-UG", - "chr", - "chr-Cher", - "chr-Cher-US", - "co", - "co-FR", - "cs", - "cs-CZ", - "cu", - "cu-RU", - "cy", - "cy-GB", - "da", - "da-DK", - "da-GL", - "dav", - "dav-KE", - "de", - "de-AT", - "de-BE", - "de-CH", - "de-DE", - "de-IT", - "de-LI", - "de-LU", - "dje", - "dje-NE", - "dsb", - "dsb-DE", - "dua", - "dua-CM", - "dv", - "dv-MV", - "dyo", - "dyo-SN", - "dz", - "dz-BT", - "ebu", - "ebu-KE", - "ee", - "ee-GH", - "ee-TG", - "el", - "el-CY", - "el-GR", - "en", - "en-001", - "en-029", - "en-150", - "en-AG", - "en-AI", - "en-AS", - "en-AT", - "en-AU", - "en-BB", - "en-BE", - "en-BI", - "en-BM", - "en-BS", - "en-BW", - "en-BZ", - "en-CA", - "en-CC", - "en-CH", - "en-CK", - "en-CM", - "en-CX", - "en-CY", - "en-DE", - "en-DK", - "en-DM", - "en-ER", - "en-FI", - "en-FJ", - "en-FK", - "en-FM", - "en-GB", - "en-GD", - "en-GG", - "en-GH", - "en-GI", - "en-GM", - "en-GU", - "en-GY", - "en-HK", - "en-ID", - "en-IE", - "en-IL", - "en-IM", - "en-IN", - "en-IO", - "en-JE", - "en-JM", - "en-KE", - "en-KI", - "en-KN", - "en-KY", - "en-LC", - "en-LR", - "en-LS", - "en-MG", - "en-MH", - "en-MO", - "en-MP", - "en-MS", - "en-MT", - "en-MU", - "en-MW", - "en-MY", - "en-NA", - "en-NF", - "en-NG", - "en-NL", - "en-NR", - "en-NU", - "en-NZ", - "en-PG", - "en-PH", - "en-PK", - "en-PN", - "en-PR", - "en-PW", - "en-RW", - "en-SB", - "en-SC", - "en-SD", - "en-SE", - "en-SG", - "en-SH", - "en-SI", - "en-SL", - "en-SS", - "en-SX", - "en-SZ", - "en-TC", - "en-TK", - "en-TO", - "en-TT", - "en-TV", - "en-TZ", - "en-UG", - "en-UM", - "en-US", - "en-VC", - "en-VG", - "en-VI", - "en-VU", - "en-WS", - "en-ZA", - "en-ZM", - "en-ZW", - "eo", - "eo-001", - "es", - "es-419", - "es-AR", - "es-BO", - "es-BR", - "es-BZ", - "es-CL", - "es-CO", - "es-CR", - "es-CU", - "es-DO", - "es-EC", - "es-ES", - "es-GQ", - "es-GT", - "es-HN", - "es-MX", - "es-NI", - "es-PA", - "es-PE", - "es-PH", - "es-PR", - "es-PY", - "es-SV", - "es-US", - "es-UY", - "es-VE", - "et", - "et-EE", - "eu", - "eu-ES", - "ewo", - "ewo-CM", - "fa", - "fa-IR", - "ff", - "ff-CM", - "ff-GN", - "ff-Latn", - "ff-Latn-SN", - "ff-MR", - "ff-NG", - "fi", - "fi-FI", - "fil", - "fil-PH", - "fo", - "fo-DK", - "fo-FO", - "fr", - "fr-029", - "fr-BE", - "fr-BF", - "fr-BI", - "fr-BJ", - "fr-BL", - "fr-CA", - "fr-CD", - "fr-CF", - "fr-CG", - "fr-CH", - "fr-CI", - "fr-CM", - "fr-DJ", - "fr-DZ", - "fr-FR", - "fr-GA", - "fr-GF", - "fr-GN", - "fr-GP", - "fr-GQ", - "fr-HT", - "fr-KM", - "fr-LU", - "fr-MA", - "fr-MC", - "fr-MF", - "fr-MG", - "fr-ML", - "fr-MQ", - "fr-MR", - "fr-MU", - "fr-NC", - "fr-NE", - "fr-PF", - "fr-PM", - "fr-RE", - "fr-RW", - "fr-SC", - "fr-SN", - "fr-SY", - "fr-TD", - "fr-TG", - "fr-TN", - "fr-VU", - "fr-WF", - "fr-YT", - "fur", - "fur-IT", - "fy", - "fy-NL", - "ga", - "ga-IE", - "gd", - "gd-GB", - "gl", - "gl-ES", - "gn", - "gn-PY", - "gsw", - "gsw-CH", - "gsw-FR", - "gsw-LI", - "gu", - "gu-IN", - "guz", - "guz-KE", - "gv", - "gv-IM", - "ha", - "ha-Latn", - "ha-Latn-GH", - "ha-Latn-NE", - "ha-Latn-NG", - "haw", - "haw-US", - "he", - "he-IL", - "hi", - "hi-IN", - "hr", - "hr-BA", - "hr-HR", - "hsb", - "hsb-DE", - "hu", - "hu-HU", - "hy", - "hy-AM", - "ia", - "ia-001", - "ia-FR", - "ibb", - "ibb-NG", - "id", - "id-ID", - "ig", - "ig-NG", - "ii", - "ii-CN", - "is", - "is-IS", - "it", - "it-CH", - "it-IT", - "it-SM", - "it-VA", - "iu", - "iu-Cans", - "iu-Cans-CA", - "iu-Latn", - "iu-Latn-CA", - "ja", - "ja-JP", - "jgo", - "jgo-CM", - "jmc", - "jmc-TZ", - "jv", - "jv-Java", - "jv-Java-ID", - "jv-Latn", - "jv-Latn-ID", - "ka", - "ka-GE", - "kab", - "kab-DZ", - "kam", - "kam-KE", - "kde", - "kde-TZ", - "kea", - "kea-CV", - "khq", - "khq-ML", - "ki", - "ki-KE", - "kk", - "kk-KZ", - "kkj", - "kkj-CM", - "kl", - "kl-GL", - "kln", - "kln-KE", - "km", - "km-KH", - "kn", - "kn-IN", - "ko", - "ko-KP", - "ko-KR", - "kok", - "kok-IN", - "kr", - "kr-NG", - "ks", - "ks-Arab", - "ks-Arab-IN", - "ks-Deva", - "ks-Deva-IN", - "ksb", - "ksb-TZ", - "ksf", - "ksf-CM", - "ksh", - "ksh-DE", - "ku", - "ku-Arab", - "ku-Arab-IQ", - "ku-Arab-IR", - "kw", - "kw-GB", - "ky", - "ky-KG", - "la", - "la-001", - "lag", - "lag-TZ", - "lb", - "lb-LU", - "lg", - "lg-UG", - "lkt", - "lkt-US", - "ln", - "ln-AO", - "ln-CD", - "ln-CF", - "ln-CG", - "lo", - "lo-LA", - "lrc", - "lrc-IQ", - "lrc-IR", - "lt", - "lt-LT", - "lu", - "lu-CD", - "luo", - "luo-KE", - "luy", - "luy-KE", - "lv", - "lv-LV", - "mas", - "mas-KE", - "mas-TZ", - "mer", - "mer-KE", - "mfe", - "mfe-MU", - "mg", - "mg-MG", - "mgh", - "mgh-MZ", - "mgo", - "mgo-CM", - "mi", - "mi-NZ", - "mk", - "mk-MK", - "ml", - "ml-IN", - "mn", - "mn-Cyrl", - "mn-MN", - "mn-Mong", - "mn-Mong-CN", - "mn-Mong-MN", - "mni", - "mni-IN", - "moh", - "moh-CA", - "mr", - "mr-IN", - "ms", - "ms-BN", - "ms-MY", - "ms-SG", - "mt", - "mt-MT", - "mua", - "mua-CM", - "my", - "my-MM", - "mzn", - "mzn-IR", - "naq", - "naq-NA", - "nb", - "nb-NO", - "nb-SJ", - "nd", - "nd-ZW", - "nds", - "nds-DE", - "nds-NL", - "ne", - "ne-IN", - "ne-NP", - "nl", - "nl-AW", - "nl-BE", - "nl-BQ", - "nl-CW", - "nl-NL", - "nl-SR", - "nl-SX", - "nmg", - "nmg-CM", - "nn", - "nn-NO", - "nnh", - "nnh-CM", - "no", - "nqo", - "nqo-GN", - "nr", - "nr-ZA", - "nso", - "nso-ZA", - "nus", - "nus-SS", - "nyn", - "nyn-UG", - "oc", - "oc-FR", - "om", - "om-ET", - "om-KE", - "or", - "or-IN", - "os", - "os-GE", - "os-RU", - "pa", - "pa-Arab", - "pa-Arab-PK", - "pa-Guru", - "pa-IN", - "pap", - "pap-029", - "pl", - "pl-PL", - "prg", - "prg-001", - "prs", - "prs-AF", - "ps", - "ps-AF", - "pt", - "pt-AO", - "pt-BR", - "pt-CH", - "pt-CV", - "pt-GQ", - "pt-GW", - "pt-LU", - "pt-MO", - "pt-MZ", - "pt-PT", - "pt-ST", - "pt-TL", - "qps-ploc", - "qps-ploca", - "qps-plocm", - "qps-Latn-x-sh", - "quc", - "quc-Latn", - "quc-Latn-GT", - "qut", - "qut-GT", - "quz", - "quz-BO", - "quz-EC", - "quz-PE", - "rm", - "rm-CH", - "rn", - "rn-BI", - "ro", - "ro-MD", - "ro-RO", - "rof", - "rof-TZ", - "ru", - "ru-BY", - "ru-KG", - "ru-KZ", - "ru-MD", - "ru-RU", - "ru-UA", - "rw", - "rw-RW", - "rwk", - "rwk-TZ", - "sa", - "sa-IN", - "sah", - "sah-RU", - "saq", - "saq-KE", - "sbp", - "sbp-TZ", - "sd", - "sd-Arab", - "sd-Arab-PK", - "sd-Deva", - "sd-Deva-IN", - "se", - "se-FI", - "se-NO", - "se-SE", - "seh", - "seh-MZ", - "ses", - "ses-ML", - "sg", - "sg-CF", - "shi", - "shi-Latn", - "shi-Latn-MA", - "shi-Tfng", - "shi-Tfng-MA", - "si", - "si-LK", - "sk", - "sk-SK", - "sl", - "sl-SI", - "sma", - "sma-NO", - "sma-SE", - "smj", - "smj-NO", - "smj-SE", - "smn", - "smn-FI", - "sms", - "sms-FI", - "sn", - "sn-Latn", - "sn-Latn-ZW", - "so", - "so-DJ", - "so-ET", - "so-KE", - "so-SO", - "sq", - "sq-AL", - "sq-MK", - "sq-XK", - "sr", - "sr-Cyrl", - "sr-Cyrl-BA", - "sr-Cyrl-CS", - "sr-Cyrl-ME", - "sr-Cyrl-RS", - "sr-Cyrl-XK", - "sr-Latn", - "sr-Latn-BA", - "sr-Latn-CS", - "sr-Latn-ME", - "sr-Latn-RS", - "sr-Latn-XK", - "ss", - "ss-SZ", - "ss-ZA", - "ssy", - "ssy-ER", - "st", - "st-LS", - "st-ZA", - "sv", - "sv-AX", - "sv-FI", - "sv-SE", - "sw", - "sw-CD", - "sw-KE", - "sw-TZ", - "sw-UG", - "syr", - "syr-SY", - "ta", - "ta-IN", - "ta-LK", - "ta-MY", - "ta-SG", - "te", - "te-IN", - "teo", - "teo-KE", - "teo-UG", - "tg", - "tg-Cyrl", - "tg-Cyrl-TJ", - "th", - "th-TH", - "ti", - "ti-ER", - "ti-ET", - "tig", - "tig-ER", - "tk", - "tk-TM", - "tn", - "tn-BW", - "tn-ZA", - "to", - "to-TO", - "tr", - "tr-CY", - "tr-TR", - "ts", - "ts-ZA", - "tt", - "tt-RU", - "twq", - "twq-NE", - "tzm", - "tzm-Arab", - "tzm-Arab-MA", - "tzm-Latn", - "tzm-Latn-DZ", - "tzm-Latn-MA", - "tzm-Tfng", - "tzm-Tfng-MA", - "ug", - "ug-CN", - "uk", - "uk-UA", - "ur", - "ur-IN", - "ur-PK", - "uz", - "uz-Arab", - "uz-Arab-AF", - "uz-Cyrl", - "uz-Cyrl-UZ", - "uz-Latn", - "uz-Latn-UZ", - "vai", - "vai-Latn", - "vai-Latn-LR", - "vai-Vaii", - "vai-Vaii-LR", - "ve", - "ve-ZA", - "vi", - "vi-VN", - "vo", - "vo-001", - "vun", - "vun-TZ", - "wae", - "wae-CH", - "wal", - "wal-ET", - "wo", - "wo-SN", - "xh", - "xh-ZA", - "xog", - "xog-UG", - "yav", - "yav-CM", - "yi", - "yi-001", - "yo", - "yo-BJ", - "yo-NG", - "zgh", - "zgh-Tfng", - "zgh-Tfng-MA", - "zh", - "zh-CN", - "zh-Hans", - "zh-Hans-HK", - "zh-Hans-MO", - "zh-Hant", - "zh-HK", - "zh-MO", - "zh-SG", - "zh-TW", - "zu", - "zu-ZA", - "zh-CHS", - "zh-CHT" - }; -#endif } } From 75dbb2d468abc79053e67864b1296c23c7f3011f Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 23:09:15 +0300 Subject: [PATCH 4/8] Remove `FEATURE_GET_COMMANDLINE` as always available. --- src/Build.UnitTests/Utilities_Tests.cs | 8 -- src/Build/BackEnd/Client/MSBuildClient.cs | 26 +--- src/Build/BackEnd/Node/OutOfProcServerNode.cs | 7 +- .../BackEnd/Node/ServerNodeBuildCommand.cs | 12 -- src/Directory.BeforeCommon.targets | 1 - .../CommandLineSwitches_Tests.cs | 4 - src/MSBuild.UnitTests/XMake_Tests.cs | 39 +----- src/MSBuild/MSBuildClientApp.cs | 22 +--- src/MSBuild/XMake.cs | 112 ++---------------- 9 files changed, 21 insertions(+), 210 deletions(-) diff --git a/src/Build.UnitTests/Utilities_Tests.cs b/src/Build.UnitTests/Utilities_Tests.cs index a29466e852c..9218a7dd7ba 100644 --- a/src/Build.UnitTests/Utilities_Tests.cs +++ b/src/Build.UnitTests/Utilities_Tests.cs @@ -80,17 +80,9 @@ public void CommentsInPreprocessing() env.SetEnvironmentVariable("MSBUILDLOADALLFILESASWRITEABLE", "1"); -#if FEATURE_GET_COMMANDLINE MSBuildApp.Execute(@"c:\bin\msbuild.exe """ + inputFile.Path + (NativeMethodsShared.IsUnixLike ? @""" -pp:""" : @""" /pp:""") + outputFile.Path + @"""") .ShouldBe(MSBuildApp.ExitType.Success); -#else - Assert.Equal( - MSBuildApp.ExitType.Success, - MSBuildApp.Execute( - new[] { @"c:\bin\msbuild.exe", '"' + inputFile.Path + '"', - '"' + (NativeMethodsShared.IsUnixLike ? "-pp:" : "/pp:") + outputFile.Path + '"'})); -#endif bool foundDoNotModify = false; foreach (string line in File.ReadLines(outputFile.Path)) diff --git a/src/Build/BackEnd/Client/MSBuildClient.cs b/src/Build/BackEnd/Client/MSBuildClient.cs index 0abf86a2aa2..bf12248a1f3 100644 --- a/src/Build/BackEnd/Client/MSBuildClient.cs +++ b/src/Build/BackEnd/Client/MSBuildClient.cs @@ -48,11 +48,7 @@ public sealed class MSBuildClient /// The command line to process. /// The first argument on the command line is assumed to be the name/path of the executable, and is ignored. /// -#if FEATURE_GET_COMMANDLINE private readonly string _commandLine; -#else - private readonly string[] _commandLine; -#endif /// /// The MSBuild client execution result. @@ -112,13 +108,7 @@ public sealed class MSBuildClient /// on the command line is assumed to be the name/path of the executable, and is ignored /// Full path to current MSBuild.exe if executable is MSBuild.exe, /// or to version of MSBuild.dll found to be associated with the current process. - public MSBuildClient( -#if FEATURE_GET_COMMANDLINE - string commandLine, -#else - string[] commandLine, -#endif - string msbuildLocation) + public MSBuildClient(string commandLine, string msbuildLocation) { _serverEnvironmentVariables = new(); _exitResult = new(); @@ -161,15 +151,7 @@ private void CreateNodePipeStream() /// or the manner in which it failed. public MSBuildClientExitResult Execute(CancellationToken cancellationToken) { - // Command line in one string used only in human readable content. - string descriptiveCommandLine = -#if FEATURE_GET_COMMANDLINE - _commandLine; -#else - string.Join(" ", _commandLine); -#endif - - CommunicationsUtilities.Trace("Executing build with command line '{0}'", descriptiveCommandLine); + CommunicationsUtilities.Trace("Executing build with command line '{0}'", _commandLine); try { @@ -217,7 +199,7 @@ public MSBuildClientExitResult Execute(CancellationToken cancellationToken) // Send build command. // Let's send it outside the packet pump so that we easier and quicker deal with possible issues with connection to server. - MSBuildEventSource.Log.MSBuildServerBuildStart(descriptiveCommandLine); + MSBuildEventSource.Log.MSBuildServerBuildStart(_commandLine); if (TrySendBuildCommand()) { _numConsoleWritePackets = 0; @@ -225,7 +207,7 @@ public MSBuildClientExitResult Execute(CancellationToken cancellationToken) ReadPacketsLoop(cancellationToken); - MSBuildEventSource.Log.MSBuildServerBuildStop(descriptiveCommandLine, _numConsoleWritePackets, _sizeOfConsoleWritePackets, _exitResult.MSBuildClientExitType.ToString(), _exitResult.MSBuildAppExitTypeString ?? string.Empty); + MSBuildEventSource.Log.MSBuildServerBuildStop(_commandLine, _numConsoleWritePackets, _sizeOfConsoleWritePackets, _exitResult.MSBuildClientExitType.ToString(), _exitResult.MSBuildAppExitTypeString ?? string.Empty); CommunicationsUtilities.Trace("Build finished."); } diff --git a/src/Build/BackEnd/Node/OutOfProcServerNode.cs b/src/Build/BackEnd/Node/OutOfProcServerNode.cs index fa0252b41f4..d3a1a57d9a2 100644 --- a/src/Build/BackEnd/Node/OutOfProcServerNode.cs +++ b/src/Build/BackEnd/Node/OutOfProcServerNode.cs @@ -25,12 +25,7 @@ public sealed class OutOfProcServerNode : INode, INodePacketFactory, INodePacket /// /// A callback used to execute command line build. /// - public delegate (int exitCode, string exitType) BuildCallback( -#if FEATURE_GET_COMMANDLINE - string commandLine); -#else - string[] commandLine); -#endif + public delegate (int exitCode, string exitType) BuildCallback(string commandLine); private readonly BuildCallback _buildFunction; diff --git a/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs b/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs index fc5bca7e920..0cb76428a2b 100644 --- a/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs +++ b/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs @@ -14,11 +14,7 @@ namespace Microsoft.Build.BackEnd /// internal sealed class ServerNodeBuildCommand : INodePacket { -#if FEATURE_GET_COMMANDLINE private string _commandLine = default!; -#else - private string[] _commandLine = default!; -#endif private string _startupDirectory = default!; private Dictionary _buildProcessEnvironment = default!; private CultureInfo _culture = default!; @@ -34,11 +30,7 @@ internal sealed class ServerNodeBuildCommand : INodePacket /// /// Command line including arguments /// -#if FEATURE_GET_COMMANDLINE public string CommandLine => _commandLine; -#else - public string[] CommandLine => _commandLine; -#endif /// /// The startup directory @@ -79,11 +71,7 @@ private ServerNodeBuildCommand() } public ServerNodeBuildCommand( -#if FEATURE_GET_COMMANDLINE string commandLine, -#else - string[] commandLine, -#endif string startupDirectory, Dictionary buildProcessEnvironment, CultureInfo culture, CultureInfo uiCulture, diff --git a/src/Directory.BeforeCommon.targets b/src/Directory.BeforeCommon.targets index ea19e0466d2..796e212c30c 100644 --- a/src/Directory.BeforeCommon.targets +++ b/src/Directory.BeforeCommon.targets @@ -29,7 +29,6 @@ $(DefineConstants);FEATURE_ENVIRONMENT_SYSTEMDIRECTORY $(DefineConstants);FEATURE_FILE_TRACKER $(DefineConstants);FEATURE_GAC - $(DefineConstants);FEATURE_GET_COMMANDLINE $(DefineConstants);FEATURE_HANDLEPROCESSCORRUPTEDSTATEEXCEPTIONS $(DefineConstants);FEATURE_HTTP_LISTENER $(DefineConstants);FEATURE_INSTALLED_MSBUILD diff --git a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs index c7ee888a52a..a3bfe9835ea 100644 --- a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs +++ b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs @@ -1545,11 +1545,7 @@ public void ProcessInvalidTargetSwitch() using TestEnvironment testEnvironment = TestEnvironment.Create(); string project = testEnvironment.CreateTestProjectWithFiles("project.proj", projectContent).ProjectFile; -#if FEATURE_GET_COMMANDLINE MSBuildApp.Execute(@"msbuild.exe " + project + " /t:foo.bar").ShouldBe(MSBuildApp.ExitType.SwitchError); -#else - MSBuildApp.Execute(new[] { @"msbuild.exe", project, "/t:foo.bar" }).ShouldBe(MSBuildApp.ExitType.SwitchError); -#endif } /// diff --git a/src/MSBuild.UnitTests/XMake_Tests.cs b/src/MSBuild.UnitTests/XMake_Tests.cs index 836c3dab0ab..b77cd64127c 100644 --- a/src/MSBuild.UnitTests/XMake_Tests.cs +++ b/src/MSBuild.UnitTests/XMake_Tests.cs @@ -520,13 +520,7 @@ public void GetLengthOfSwitchIndicatorTest() [InlineData(@"/h")] public void Help(string indicator) { - MSBuildApp.Execute( -#if FEATURE_GET_COMMANDLINE - @$"c:\bin\msbuild.exe {indicator} ") -#else - new[] { @"c:\bin\msbuild.exe", indicator }) -#endif - .ShouldBe(MSBuildApp.ExitType.Success); + MSBuildApp.Execute(@$"c:\bin\msbuild.exe {indicator} ").ShouldBe(MSBuildApp.ExitType.Success); } [Fact] @@ -618,19 +612,11 @@ public void VersionSwitchDisableChangeWave() public void ErrorCommandLine() { string oldValueForMSBuildLoadMicrosoftTargetsReadOnly = Environment.GetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly"); -#if FEATURE_GET_COMMANDLINE MSBuildApp.Execute(@"c:\bin\msbuild.exe -junk").ShouldBe(MSBuildApp.ExitType.SwitchError); MSBuildApp.Execute(@"msbuild.exe -t").ShouldBe(MSBuildApp.ExitType.SwitchError); MSBuildApp.Execute(@"msbuild.exe @bogus.rsp").ShouldBe(MSBuildApp.ExitType.InitializationError); -#else - MSBuildApp.Execute(new[] { @"c:\bin\msbuild.exe", "-junk" }).ShouldBe(MSBuildApp.ExitType.SwitchError); - - MSBuildApp.Execute(new[] { @"msbuild.exe", "-t" }).ShouldBe(MSBuildApp.ExitType.SwitchError); - - MSBuildApp.Execute(new[] { @"msbuild.exe", "@bogus.rsp" }).ShouldBe(MSBuildApp.ExitType.InitializationError); -#endif Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", oldValueForMSBuildLoadMicrosoftTargetsReadOnly); } @@ -1111,11 +1097,7 @@ public void TestEnvironmentTest() sw.WriteLine(projectString); } // Should pass -#if FEATURE_GET_COMMANDLINE MSBuildApp.Execute(@"c:\bin\msbuild.exe " + quotedProjectFileName).ShouldBe(MSBuildApp.ExitType.Success); -#else - MSBuildApp.Execute(new[] { @"c:\bin\msbuild.exe", quotedProjectFileName }).ShouldBe(MSBuildApp.ExitType.Success); -#endif } finally { @@ -1148,21 +1130,10 @@ public void MSBuildEngineLogger() { sw.WriteLine(projectString); } -#if FEATURE_GET_COMMANDLINE - // Should pass - MSBuildApp.Execute(@$"c:\bin\msbuild.exe /logger:FileLogger,""Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"";""LogFile={logFile}"" /verbosity:detailed " + quotedProjectFileName).ShouldBe(MSBuildApp.ExitType.Success); -#else // Should pass - MSBuildApp.Execute( - new[] - { - NativeMethodsShared.IsWindows ? @"c:\bin\msbuild.exe" : "/msbuild.exe", - @$"/logger:FileLogger,""Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"";""LogFile={logFile}""", - "/verbosity:detailed", - quotedProjectFileName - }).ShouldBe(MSBuildApp.ExitType.Success); -#endif + string exeName = NativeMethodsShared.IsWindows ? @"c:\bin\msbuild.exe" : "/msbuild.exe"; + MSBuildApp.Execute(@$"{exeName} /logger:FileLogger,""Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"";""LogFile={logFile}"" /verbosity:detailed " + quotedProjectFileName).ShouldBe(MSBuildApp.ExitType.Success); File.Exists(logFile).ShouldBeTrue(); var logFileContents = File.ReadAllText(logFile); @@ -2498,7 +2469,7 @@ public void MissingOptionalLoggersAreIgnored(string logger, string expectedLogge [InlineData("-logger:,Logger.dll", "Logger.dll")] public void LoggerThrowsIOExceptionWhenDllNotFound(string logger, string expectedLoggerName) { - string projectString =""; + string projectString = ""; var tempDir = _env.CreateFolder(); var projectFile = tempDir.CreateFile("iologgertest.proj", projectString); @@ -2515,7 +2486,7 @@ public void LoggerThrowsIOExceptionWhenDllNotFound(string logger, string expecte [InlineData("-distributedlogger:,BadFile.dll", "BadFile.dll")] public void LoggerThrowsBadImageFormatExceptionWhenFileIsInvalid(string logger, string expectedLoggerName) { - string projectString =""; + string projectString = ""; var tempDir = _env.CreateFolder(); var projectFile = tempDir.CreateFile("badimagetest.proj", projectString); diff --git a/src/MSBuild/MSBuildClientApp.cs b/src/MSBuild/MSBuildClientApp.cs index 3eeb975bc40..c5bfb0c3a07 100644 --- a/src/MSBuild/MSBuildClientApp.cs +++ b/src/MSBuild/MSBuildClientApp.cs @@ -34,20 +34,11 @@ internal static class MSBuildClientApp /// /// The locations of msbuild exe/dll and dotnet.exe would be automatically detected if called from dotnet or msbuild cli. Calling this function from other executables might not work. /// - public static MSBuildApp.ExitType Execute( -#if FEATURE_GET_COMMANDLINE - string commandLine, -#else - string[] commandLine, -#endif - CancellationToken cancellationToken) + public static MSBuildApp.ExitType Execute(string commandLine, CancellationToken cancellationToken) { string msbuildLocation = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath; - return Execute( - commandLine, - msbuildLocation, - cancellationToken); + return Execute(commandLine, msbuildLocation, cancellationToken); } /// @@ -61,14 +52,7 @@ public static MSBuildApp.ExitType Execute( /// Cancellation token. /// A value of type that indicates whether the build succeeded, /// or the manner in which it failed. - public static MSBuildApp.ExitType Execute( -#if FEATURE_GET_COMMANDLINE - string commandLine, -#else - string[] commandLine, -#endif - string msbuildLocation, - CancellationToken cancellationToken) + public static MSBuildApp.ExitType Execute(string commandLine, string msbuildLocation, CancellationToken cancellationToken) { MSBuildClient msbuildClient = new MSBuildClient(commandLine, msbuildLocation); MSBuildClientExitResult exitResult = msbuildClient.Execute(cancellationToken); diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index b4a2a906fe2..2ec5e4183e5 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -233,13 +233,7 @@ private static void HandleConfigurationException(Exception ex) #if FEATURE_APPDOMAIN [LoaderOptimization(LoaderOptimization.MultiDomain)] #endif -#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter - public static int Main( -#if !FEATURE_GET_COMMANDLINE - string[] args -#endif - ) -#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter + public static int Main() { // Setup the console UI. using AutomaticEncodingRestorer _ = new(); @@ -263,35 +257,18 @@ string[] args if ( Environment.GetEnvironmentVariable(Traits.UseMSBuildServerEnvVarName) == "1" && !Traits.Instance.EscapeHatches.EnsureStdOutForChildNodesIsPrimaryStdout && - CanRunServerBasedOnCommandLineSwitches( -#if FEATURE_GET_COMMANDLINE - Environment.CommandLine)) -#else - ConstructArrayArg(args))) -#endif + CanRunServerBasedOnCommandLineSwitches(Environment.CommandLine)) { Console.CancelKeyPress += Console_CancelKeyPress; // Use the client app to execute build in msbuild server. Opt-in feature. - exitCode = ((s_initialized && MSBuildClientApp.Execute( -#if FEATURE_GET_COMMANDLINE - Environment.CommandLine, -#else - ConstructArrayArg(args), -#endif - s_buildCancellationSource.Token) == ExitType.Success) ? 0 : 1); + exitCode = (s_initialized && MSBuildClientApp.Execute(Environment.CommandLine, s_buildCancellationSource.Token) == ExitType.Success) ? 0 : 1; } else { // return 0 on success, non-zero on failure - exitCode = ((s_initialized && Execute( -#if FEATURE_GET_COMMANDLINE - Environment.CommandLine) -#else - ConstructArrayArg(args)) -#endif - == ExitType.Success) ? 0 : 1); + exitCode = (s_initialized && Execute(Environment.CommandLine) == ExitType.Success) ? 0 : 1; } if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1") @@ -310,12 +287,7 @@ string[] args /// /// Will not throw. If arguments processing fails, we will not run it on server - no reason as it will not run any build anyway. /// - private static bool CanRunServerBasedOnCommandLineSwitches( -#if FEATURE_GET_COMMANDLINE - string commandLine) -#else - string[] commandLine) -#endif + private static bool CanRunServerBasedOnCommandLineSwitches(string commandLine) { bool canRunServer = true; try @@ -384,23 +356,6 @@ private static bool IsInteractiveBuild(CommandLineSwitches commandLineSwitches) return false; } -#if !FEATURE_GET_COMMANDLINE - /// - /// Insert the command executable path as the first element of the args array. - /// - /// - /// - private static string[] ConstructArrayArg(string[] args) - { - string[] newArgArray = new string[args.Length + 1]; - - newArgArray[0] = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath; - Array.Copy(args, 0, newArgArray, 1, args.Length); - - return newArgArray; - } -#endif // !FEATURE_GET_COMMANDLINE - /// /// Append output file with elapsedTime /// @@ -647,12 +602,7 @@ private static void DebuggerLaunchCheck() /// is ignored. /// A value of type ExitType that indicates whether the build succeeded, /// or the manner in which it failed. - public static ExitType Execute( -#if FEATURE_GET_COMMANDLINE - string commandLine) -#else - string[] commandLine) -#endif + public static ExitType Execute(string commandLine) { DebuggerLaunchCheck(); @@ -669,9 +619,7 @@ public static ExitType Execute( // and those form the great majority of our unnecessary memory use. Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", "true"); -#if FEATURE_GET_COMMANDLINE ErrorUtilities.VerifyThrowArgumentLength(commandLine); -#endif AppDomain.CurrentDomain.UnhandledException += ExceptionHandling.UnhandledExceptionHandler; @@ -683,14 +631,7 @@ public static ExitType Execute( TextWriter targetsWriter = null; try { -#if FEATURE_GET_COMMANDLINE MSBuildEventSource.Log.MSBuildExeStart(commandLine); -#else - if (MSBuildEventSource.Log.IsEnabled()) - { - MSBuildEventSource.Log.MSBuildExeStart(string.Join(" ", commandLine)); - } -#endif Console.CancelKeyPress += cancelHandler; // check the operating system the code is running on @@ -790,11 +731,7 @@ public static ExitType Execute( ref getTargetResult, ref getResultOutputFile, recursing: false, -#if FEATURE_GET_COMMANDLINE commandLine); -#else - string.Join(' ', commandLine)); -#endif CommandLineSwitches.SwitchesFromResponseFiles = null; @@ -1093,14 +1030,7 @@ public static ExitType Execute( preprocessWriter?.Dispose(); targetsWriter?.Dispose(); -#if FEATURE_GET_COMMANDLINE MSBuildEventSource.Log.MSBuildExeStop(commandLine); -#else - if (MSBuildEventSource.Log.IsEnabled()) - { - MSBuildEventSource.Log.MSBuildExeStop(string.Join(" ", commandLine)); - } -#endif } /********************************************************************************************************************** * WARNING: Do NOT add any more catch blocks above! @@ -1322,11 +1252,7 @@ internal static bool BuildProject( #if FEATURE_REPORTFILEACCESSES bool reportFileAccesses, #endif -#if FEATURE_GET_COMMANDLINE string commandLine) -#else - string[] commandLine) -#endif { if (FileUtilities.IsVCProjFilename(projectFile) || FileUtilities.IsDspFilename(projectFile)) { @@ -1561,13 +1487,7 @@ internal static bool BuildProject( if (!Traits.Instance.EscapeHatches.DoNotSendDeferredMessagesToBuildManager) { - var commandLineString = -#if FEATURE_GET_COMMANDLINE - commandLine; -#else - string.Join(" ", commandLine); -#endif - messagesToLogInBuildLoggers.AddRange(GetMessagesToLogInBuildLoggers(commandLineString)); + messagesToLogInBuildLoggers.AddRange(GetMessagesToLogInBuildLoggers(commandLine)); // Log a message for every response file and include it in log foreach (var responseFilePath in s_includedResponseFiles) @@ -1999,26 +1919,14 @@ internal static void SetConsoleUI() /// /// /// Combined bag of switches. - private static void GatherAllSwitches( -#if FEATURE_GET_COMMANDLINE - string commandLine, -#else - string[] commandLine, -#endif - out CommandLineSwitches switchesFromAutoResponseFile, out CommandLineSwitches switchesNotFromAutoResponseFile, out string fullCommandLine) + private static void GatherAllSwitches(string commandLine, out CommandLineSwitches switchesFromAutoResponseFile, out CommandLineSwitches switchesNotFromAutoResponseFile, out string fullCommandLine) { ResetGatheringSwitchesState(); -#if FEATURE_GET_COMMANDLINE // split the command line on (unquoted) whitespace var commandLineArgs = QuotingUtilities.SplitUnquoted(commandLine); s_exeName = FileUtilities.FixFilePath(QuotingUtilities.Unquote(commandLineArgs[0])); -#else - var commandLineArgs = new List(commandLine); - - s_exeName = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath; -#endif #if USE_MSBUILD_DLL_EXTN var msbuildExtn = ".dll"; @@ -2033,11 +1941,7 @@ private static void GatherAllSwitches( // discard the first piece, because that's the path to the executable -- the rest are args commandLineArgs.RemoveAt(0); -#if FEATURE_GET_COMMANDLINE fullCommandLine = $"'{commandLine}'"; -#else - fullCommandLine = $"'{string.Join(' ', commandLine)}'"; -#endif // parse the command line, and flag syntax errors and obvious switch errors switchesNotFromAutoResponseFile = new CommandLineSwitches(); From 840eb5f8cf2dacf8c31317208e25aa3c6ed0eaf7 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 26 Jul 2025 23:59:32 +0300 Subject: [PATCH 5/8] Fix compile errors. --- src/Build.UnitTests/EscapingInProjects_Tests.cs | 3 --- src/Framework/NativeMethods.cs | 1 - src/Framework/TaskPropertyInfo.cs | 1 - src/Shared/BuildEnvironmentHelper.cs | 3 +-- src/Shared/TaskLoader.cs | 4 ++++ src/Shared/TaskParameter.cs | 2 -- src/Tasks/AssemblyResources.cs | 1 - src/Utilities/AssemblyResources.cs | 1 - 8 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Build.UnitTests/EscapingInProjects_Tests.cs b/src/Build.UnitTests/EscapingInProjects_Tests.cs index 40e1075fdf9..00d72edde4e 100644 --- a/src/Build.UnitTests/EscapingInProjects_Tests.cs +++ b/src/Build.UnitTests/EscapingInProjects_Tests.cs @@ -5,9 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -#if FEATURE_COMPILE_IN_TESTS using System.Reflection; -#endif using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; @@ -24,7 +22,6 @@ using Shouldly; using Xunit; using Xunit.Abstractions; -using System.Reflection; #if FEATURE_COMPILE_IN_TESTS using Microsoft.Build.Shared; #endif diff --git a/src/Framework/NativeMethods.cs b/src/Framework/NativeMethods.cs index c776259cc97..affe0358930 100644 --- a/src/Framework/NativeMethods.cs +++ b/src/Framework/NativeMethods.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Build.Shared; diff --git a/src/Framework/TaskPropertyInfo.cs b/src/Framework/TaskPropertyInfo.cs index d36b5089bf0..6d0fe72c7de 100644 --- a/src/Framework/TaskPropertyInfo.cs +++ b/src/Framework/TaskPropertyInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Reflection; #nullable disable diff --git a/src/Shared/BuildEnvironmentHelper.cs b/src/Shared/BuildEnvironmentHelper.cs index 82f05b5eaed..92f1151a69c 100644 --- a/src/Shared/BuildEnvironmentHelper.cs +++ b/src/Shared/BuildEnvironmentHelper.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.Shared.FileSystem; @@ -429,7 +428,7 @@ private static string GetProcessFromRunningProcess() #if RUNTIME_TYPE_NETCORE // Assembly.GetEntryAssembly() can return null when a managed assembly has been loaded from // an unmanaged application (for example, using custom CLR hosting). - if (Assembly.GetEntryAssembly() is not { } entryAsm) + if (System.Reflection.Assembly.GetEntryAssembly() is not { } entryAsm) { return EnvironmentUtilities.ProcessPath; } diff --git a/src/Shared/TaskLoader.cs b/src/Shared/TaskLoader.cs index 88e588e28a1..44ffa7b454b 100644 --- a/src/Shared/TaskLoader.cs +++ b/src/Shared/TaskLoader.cs @@ -4,6 +4,10 @@ using System; using Microsoft.Build.Framework; +#if FEATURE_APPDOMAIN +using System.Reflection; +#endif + namespace Microsoft.Build.Shared { /// diff --git a/src/Shared/TaskParameter.cs b/src/Shared/TaskParameter.cs index 527f3d302ab..85c139a7ca3 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -5,8 +5,6 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Linq; -using Microsoft.Build.Collections; #if FEATURE_APPDOMAIN using System.Security; diff --git a/src/Tasks/AssemblyResources.cs b/src/Tasks/AssemblyResources.cs index 9bf6db29c8c..856e4e61d4c 100644 --- a/src/Tasks/AssemblyResources.cs +++ b/src/Tasks/AssemblyResources.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; -using System.Reflection; using System.Resources; #nullable disable diff --git a/src/Utilities/AssemblyResources.cs b/src/Utilities/AssemblyResources.cs index b8c81daa33b..0f179580348 100644 --- a/src/Utilities/AssemblyResources.cs +++ b/src/Utilities/AssemblyResources.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; -using System.Reflection; using System.Resources; #nullable disable From 119759eda6690b457be64fc273c74ac65dfd1be5 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sun, 27 Jul 2025 20:59:08 +0300 Subject: [PATCH 6/8] Do not create additional ALC to load a well-known assembly. Fixes at least one failing test. Type checking in tests was also enhanced to better catch these kinds of errors. --- .../BackEnd/TranslationHelpers.cs | 29 +++++++++++++++---- src/Shared/CoreCLRAssemblyLoader.cs | 9 ++++++ src/Shared/UnitTests/TypeLoader_Tests.cs | 6 ++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/Build.UnitTests/BackEnd/TranslationHelpers.cs b/src/Build.UnitTests/BackEnd/TranslationHelpers.cs index 9d80a38e901..49449cea379 100644 --- a/src/Build.UnitTests/BackEnd/TranslationHelpers.cs +++ b/src/Build.UnitTests/BackEnd/TranslationHelpers.cs @@ -6,6 +6,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +#if FEATURE_ASSEMBLYLOADCONTEXT +using System.Runtime.Loader; +#endif using System.Text; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; @@ -146,17 +149,31 @@ internal static bool CompareExceptions(Exception left, Exception right, out stri if (left.GetType() != right.GetType()) { // Handle known type conversions during serialization - if (!IsKnownMovedType(left, right)) - { - diffReason = $"Exception types are different ({left.GetType().FullName} vs {right.GetType().FullName})."; - return false; - } - else + if (IsKnownMovedType(left, right)) { // For known moved types, skip detailed property comparison since types are different // but this is expected behavior - just return true since basic checks passed return true; } + else + { + string leftName = left.GetType().FullName; + string rightName = right.GetType().FullName; +#if FEATURE_ASSEMBLYLOADCONTEXT + AssemblyLoadContext leftContext = AssemblyLoadContext.GetLoadContext(left.GetType().Assembly); + AssemblyLoadContext rightContext = AssemblyLoadContext.GetLoadContext(right.GetType().Assembly); + if (leftName == rightName && leftContext != rightContext) + { + diffReason = $"Exception types are the same ({leftName}) but loaded from different assembly load contexts ({leftContext} vs {rightContext})."; + } + else +#endif + { + diffReason = $"Exception types are different ({leftName} vs {rightName})."; + } + + return false; + } } foreach (var prop in left.GetType().GetProperties()) diff --git a/src/Shared/CoreCLRAssemblyLoader.cs b/src/Shared/CoreCLRAssemblyLoader.cs index 69269b204a9..5556eba8eb3 100644 --- a/src/Shared/CoreCLRAssemblyLoader.cs +++ b/src/Shared/CoreCLRAssemblyLoader.cs @@ -55,6 +55,15 @@ public Assembly LoadFromPath(string fullPath) // folders in a NuGet package). fullPath = FileUtilities.NormalizePath(fullPath); + AssemblyName assemblyName = AssemblyLoadContext.GetAssemblyName(fullPath); + if (MSBuildLoadContext.WellKnownAssemblyNames.Contains(assemblyName.Name)) + { + // If this is a well-known assembly, load it directly, ensuring that + // it is loaded only once. Some tests might pass a well-known assembly + // to this method. + return Assembly.Load(assemblyName); + } + if (Traits.Instance.EscapeHatches.UseSingleLoadContext) { return LoadUsingLegacyDefaultContext(fullPath); diff --git a/src/Shared/UnitTests/TypeLoader_Tests.cs b/src/Shared/UnitTests/TypeLoader_Tests.cs index 94e80006318..a9921de2712 100644 --- a/src/Shared/UnitTests/TypeLoader_Tests.cs +++ b/src/Shared/UnitTests/TypeLoader_Tests.cs @@ -6,6 +6,9 @@ using System.IO; using System.Linq; using System.Reflection; +#if NET +using System.Runtime.Loader; +#endif using Microsoft.Build.Shared; using Microsoft.Build.UnitTests.Shared; using Shouldly; @@ -283,6 +286,9 @@ public void NoTypeNamePicksFirstType() LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation)); Assert.NotNull(loadedType); Assert.Equal(forwardingLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation); +#if NET + Assert.Equal(AssemblyLoadContext.GetLoadContext(firstPublicType.Assembly), AssemblyLoadContext.GetLoadContext(loadedType.Type.Assembly)); +#endif Assert.Equal(firstPublicType, loadedType.Type); From ec46ffee0e562d748c90f929b2a60e6eddf4a459 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sun, 13 Jul 2025 00:07:14 +0300 Subject: [PATCH 7/8] Remove `FEATURE_XML_SCHEMA_VALIDATION` as always available. --- src/Directory.BeforeCommon.targets | 1 - .../CommandLineSwitches_Tests.cs | 4 -- .../ProjectSchemaValidationHandler_Tests.cs | 2 - src/MSBuild/CommandLineSwitches.cs | 4 -- src/MSBuild/ProjectSchemaValidationHandler.cs | 2 - src/MSBuild/XMake.cs | 71 +++++++------------ 6 files changed, 27 insertions(+), 57 deletions(-) diff --git a/src/Directory.BeforeCommon.targets b/src/Directory.BeforeCommon.targets index 796e212c30c..2c2c0d492c9 100644 --- a/src/Directory.BeforeCommon.targets +++ b/src/Directory.BeforeCommon.targets @@ -63,7 +63,6 @@ $(DefineConstants);FEATURE_XAML_TYPES $(DefineConstants);FEATURE_XAMLTASKFACTORY true - $(DefineConstants);FEATURE_XML_SCHEMA_VALIDATION $(DefineConstants);FEATURE_WIN32_REGISTRY $(DefineConstants);FEATURE_VISUALSTUDIOSETUP $(DefineConstants);FEATURE_MSCOREE diff --git a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs index a3bfe9835ea..3cf11a73f63 100644 --- a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs +++ b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs @@ -474,7 +474,6 @@ public void MultiThreadedeParametersIdentificationTests(string multithreaded) unquoteParameters.ShouldBeTrue(); } -#if FEATURE_XML_SCHEMA_VALIDATION [Theory] [InlineData("validate")] [InlineData("VALIDATE")] @@ -498,7 +497,6 @@ public void ValidateSwitchIdentificationTests(string validate) missingParametersErrorMessage.ShouldBeNull(); unquoteParameters.ShouldBeTrue(); } -#endif [Theory] [InlineData("preprocess")] @@ -1185,10 +1183,8 @@ public void InvalidToolsVersionErrors() Array.Empty(), LoggerVerbosity.Normal, Array.Empty(), -#if FEATURE_XML_SCHEMA_VALIDATION false, null, -#endif 1, false, true, diff --git a/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs b/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs index 7a224860a2f..2bc33da9585 100644 --- a/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs +++ b/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if FEATURE_XML_SCHEMA_VALIDATION using System; using System.IO; using System.Reflection; @@ -397,4 +396,3 @@ private static string CleanupFileContents(string projectFileContents) #pragma warning restore format } } -#endif diff --git a/src/MSBuild/CommandLineSwitches.cs b/src/MSBuild/CommandLineSwitches.cs index 66b529eb62f..8d3e4d064c7 100644 --- a/src/MSBuild/CommandLineSwitches.cs +++ b/src/MSBuild/CommandLineSwitches.cs @@ -72,9 +72,7 @@ internal enum ParameterizedSwitch Logger, DistributedLogger, Verbosity, -#if FEATURE_XML_SCHEMA_VALIDATION Validate, -#endif ConsoleLoggerParameters, NodeMode, MaxCPUCount, @@ -247,9 +245,7 @@ internal ParameterizedSwitchInfo( new ParameterizedSwitchInfo( ["logger", "l"], ParameterizedSwitch.Logger, null, false, "MissingLoggerError", false, false, "HelpMessage_11_LoggerSwitch"), new ParameterizedSwitchInfo( ["distributedlogger", "dl"], ParameterizedSwitch.DistributedLogger, null, false, "MissingLoggerError", false, false, "HelpMessage_18_DistributedLoggerSwitch"), new ParameterizedSwitchInfo( ["verbosity", "v"], ParameterizedSwitch.Verbosity, null, false, "MissingVerbosityError", true, false, "HelpMessage_12_VerbositySwitch"), -#if FEATURE_XML_SCHEMA_VALIDATION new ParameterizedSwitchInfo( ["validate", "val"], ParameterizedSwitch.Validate, null, false, null, true, false, "HelpMessage_15_ValidateSwitch"), -#endif new ParameterizedSwitchInfo( ["consoleloggerparameters", "clp"], ParameterizedSwitch.ConsoleLoggerParameters, null, false, "MissingConsoleLoggerParameterError", true, false, "HelpMessage_13_ConsoleLoggerParametersSwitch"), new ParameterizedSwitchInfo( ["nodemode", "nmode"], ParameterizedSwitch.NodeMode, null, false, null, false, false, null), new ParameterizedSwitchInfo( ["maxcpucount", "m"], ParameterizedSwitch.MaxCPUCount, null, false, "MissingMaxCPUCountError", true, false, "HelpMessage_17_MaximumCPUSwitch"), diff --git a/src/MSBuild/ProjectSchemaValidationHandler.cs b/src/MSBuild/ProjectSchemaValidationHandler.cs index 474a0c0984d..a1035d673e9 100644 --- a/src/MSBuild/ProjectSchemaValidationHandler.cs +++ b/src/MSBuild/ProjectSchemaValidationHandler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if FEATURE_XML_SCHEMA_VALIDATION using System; using System.IO; using System.Xml; @@ -276,4 +275,3 @@ private void OnSchemaValidationError(object sender, ValidationEventArgs args) #pragma warning restore format } } -#endif diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 2ec5e4183e5..2d5ea230ea2 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -651,10 +651,8 @@ public static ExitType Execute(string commandLine) LoggerVerbosity verbosity = LoggerVerbosity.Normal; LoggerVerbosity originalVerbosity = LoggerVerbosity.Normal; List distributedLoggerRecords = null; -#if FEATURE_XML_SCHEMA_VALIDATION bool needToValidateProject = false; string schemaFile = null; -#endif int cpuCount = 1; bool multiThreaded = false; #if FEATURE_NODE_REUSE @@ -698,10 +696,8 @@ public static ExitType Execute(string commandLine) ref verbosity, ref originalVerbosity, ref distributedLoggerRecords, -#if FEATURE_XML_SCHEMA_VALIDATION ref needToValidateProject, ref schemaFile, -#endif ref cpuCount, ref multiThreaded, ref enableNodeReuse, @@ -818,35 +814,34 @@ public static ExitType Execute(string commandLine) loggers, verbosity, distributedLoggerRecords.ToArray(), -#if FEATURE_XML_SCHEMA_VALIDATION - needToValidateProject, schemaFile, -#endif - cpuCount, - multiThreaded, - enableNodeReuse, - preprocessWriter, - targetsWriter, - detailedSummary, - warningsAsErrors, - warningsNotAsErrors, - warningsAsMessages, - enableRestore, - profilerLogger, - enableProfiler, - interactive, - isolateProjects, - graphBuildOptions, - lowPriority, - question, - isBuildCheckEnabled, - inputResultsCaches, - outputResultsCache, - saveProjectResult: outputPropertiesItemsOrTargetResults, - ref result, + needToValidateProject, + schemaFile, + cpuCount, + multiThreaded, + enableNodeReuse, + preprocessWriter, + targetsWriter, + detailedSummary, + warningsAsErrors, + warningsNotAsErrors, + warningsAsMessages, + enableRestore, + profilerLogger, + enableProfiler, + interactive, + isolateProjects, + graphBuildOptions, + lowPriority, + question, + isBuildCheckEnabled, + inputResultsCaches, + outputResultsCache, + saveProjectResult: outputPropertiesItemsOrTargetResults, + ref result, #if FEATURE_REPORTFILEACCESSES - reportFileAccesses, + reportFileAccesses, #endif - commandLine)) + commandLine)) { exitType = ExitType.BuildError; } @@ -1223,10 +1218,8 @@ internal static bool BuildProject( ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, -#if FEATURE_XML_SCHEMA_VALIDATION bool needToValidateProject, string schemaFile, -#endif int cpuCount, bool multiThreaded, bool enableNodeReuse, @@ -1356,7 +1349,6 @@ internal static bool BuildProject( bool isSolution = FileUtilities.IsSolutionFilename(projectFile); -#if FEATURE_XML_SCHEMA_VALIDATION // If the user has requested that the schema be validated, do that here. if (needToValidateProject && !isSolution) { @@ -1374,7 +1366,6 @@ internal static bool BuildProject( // we can safely assume that the project successfully validated. projectCollection.UnloadProject(project); } -#endif if (isPreprocess) { @@ -2418,10 +2409,8 @@ private static bool ProcessCommandLineSwitches( ref LoggerVerbosity verbosity, ref LoggerVerbosity originalVerbosity, ref List distributedLoggerRecords, -#if FEATURE_XML_SCHEMA_VALIDATION ref bool needToValidateProject, ref string schemaFile, -#endif ref int cpuCount, ref bool multiThreaded, ref bool enableNodeReuse, @@ -2558,10 +2547,8 @@ private static bool ProcessCommandLineSwitches( ref verbosity, ref originalVerbosity, ref distributedLoggerRecords, -#if FEATURE_XML_SCHEMA_VALIDATION ref needToValidateProject, ref schemaFile, -#endif ref cpuCount, ref multiThreaded, ref enableNodeReuse, @@ -2707,11 +2694,9 @@ private static bool ProcessCommandLineSwitches( Console.WriteLine($"{Path.Combine(s_exePath, s_exeName)} {equivalentCommandLine} {projectFile}"); } -#if FEATURE_XML_SCHEMA_VALIDATION // figure out if the project needs to be validated against a schema needToValidateProject = commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Validate); schemaFile = ProcessValidateSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Validate]); -#endif invokeBuild = true; if (commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.WarningsNotAsErrors) && @@ -4516,7 +4501,6 @@ private static void ReplayBinaryLog( } } -#if FEATURE_XML_SCHEMA_VALIDATION /// /// Figures out if the project needs to be validated against a schema. /// @@ -4537,7 +4521,6 @@ private static string ProcessValidateSwitch(string[] parameters) return schemaFile; } -#endif /// /// Given an invalid ToolsVersion string and the collection of valid toolsets, From 1177dd78378c45b092e94e4233295bd5037ec584 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sun, 3 Aug 2025 18:53:05 +0300 Subject: [PATCH 8/8] Fix tests. --- src/MSBuild/ProjectSchemaValidationHandler.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/MSBuild/ProjectSchemaValidationHandler.cs b/src/MSBuild/ProjectSchemaValidationHandler.cs index a1035d673e9..fbb09c07f43 100644 --- a/src/MSBuild/ProjectSchemaValidationHandler.cs +++ b/src/MSBuild/ProjectSchemaValidationHandler.cs @@ -83,6 +83,9 @@ private void VerifyProjectSchema( validatorSettings.XmlResolver = null; validatorSettings.ValidationEventHandler += this.OnSchemaValidationError; + // On Core, resolving schemas from external URIs is not enabled by default. + validatorSettings.Schemas.XmlResolver = new XmlUrlResolver(); + XmlTextReader schemaReader = new XmlTextReader(schemaFile); schemaReader.DtdProcessing = DtdProcessing.Ignore;