From e46fc23572796de7c116a4a7f6398cd1cdee0504 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:01:10 +0300 Subject: [PATCH 1/5] 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 ++-- .../Instance/TaskFactoryEngineContext.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 | 3 +-- src/Shared/LoadedType.cs | 6 ++--- src/Shared/TaskLoader.cs | 9 ++++--- src/Shared/TaskParameter.cs | 7 +++--- 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, 95 insertions(+), 144 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 4df21d5d18a..df6d50f1a48 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs @@ -213,7 +213,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); @@ -715,7 +715,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 if (explicitlyLaunchTaskHost) { 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 b36206e3751..7a5c1ede374 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -1223,8 +1223,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); } @@ -1247,7 +1247,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 1e870839811..ad57990116f 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 7a70791f17b..e3064449a2d 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; @@ -3015,7 +3014,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); @@ -3035,7 +3034,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); @@ -3092,7 +3091,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 487c10b69b0..846c819e634 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingService.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingService.cs @@ -1022,7 +1022,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 2d2958b557d..41fb7bff82d 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs @@ -901,7 +901,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 14c3b5534dd..f2b7d880a70 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -944,13 +944,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 5cc3c9ca91d..b61cfd50d9e 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -511,7 +511,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 9c6afc433e2..de20a705586 100644 --- a/src/Build/Evaluation/Expander.cs +++ b/src/Build/Evaluation/Expander.cs @@ -4561,7 +4561,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 c51f2f78436..8c368ba8c5e 100644 --- a/src/Build/Instance/TaskFactories/TaskHostTask.cs +++ b/src/Build/Instance/TaskFactories/TaskHostTask.cs @@ -293,7 +293,7 @@ public bool Execute() ErrorUtilities.VerifyThrowInternalNull(_taskHostProvider, "taskHostProvider"); } - string taskLocation = AssemblyUtilities.GetAssemblyLocation(_taskType.Type.GetTypeInfo().Assembly); + string taskLocation = AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly); if (string.IsNullOrEmpty(taskLocation)) { // fall back to the AssemblyLoadInfo location for inline tasks loaded from bytes @@ -556,7 +556,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/TaskFactoryEngineContext.cs b/src/Build/Instance/TaskFactoryEngineContext.cs index 659e6f1e86e..8c03ff32fbe 100644 --- a/src/Build/Instance/TaskFactoryEngineContext.cs +++ b/src/Build/Instance/TaskFactoryEngineContext.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 @@ -384,7 +383,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 b0af558f603..0e715c6c822 100644 --- a/src/Build/Instance/TaskRegistry.cs +++ b/src/Build/Instance/TaskRegistry.cs @@ -647,8 +647,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); } @@ -1582,7 +1582,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 @@ -1830,13 +1830,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 d141991394f..f579aef14dd 100644 --- a/src/MSBuild/OutOfProcTaskHostNode.cs +++ b/src/MSBuild/OutOfProcTaskHostNode.cs @@ -1211,7 +1211,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 e5e12b80ae2..edb7189e7f4 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -4081,7 +4081,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); @@ -4140,7 +4140,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 6c90cde97d6..2678583879d 100644 --- a/src/Shared/CommunicationsUtilities.cs +++ b/src/Shared/CommunicationsUtilities.cs @@ -861,7 +861,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 005730b749c..2818a0f79aa 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; @@ -794,7 +793,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. diff --git a/src/Shared/LoadedType.cs b/src/Shared/LoadedType.cs index 27405b89265..8ba3e2c0bac 100644 --- a/src/Shared/LoadedType.cs +++ b/src/Shared/LoadedType.cs @@ -143,8 +143,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 } @@ -175,7 +175,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 6c54e0e8f06..292f838c39b 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Reflection; using Microsoft.Build.Collections; #if FEATURE_APPDOMAIN @@ -128,7 +127,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; @@ -144,7 +143,7 @@ public TaskParameter(object wrappedParameter) _wrappedParameter = taskItemArrayParameter; } - else if (wrappedParameterType.GetElementType().GetTypeInfo().IsValueType) + else if (wrappedParameterType.GetElementType().IsValueType) { _parameterType = TaskParameterType.ValueTypeArray; _wrappedParameter = wrappedParameter; @@ -179,7 +178,7 @@ public TaskParameter(object wrappedParameter) _parameterType = TaskParameterType.ITaskItem; _wrappedParameter = new TaskParameterTaskItem((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 c9854f90eab..ba759e4e0ed 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs @@ -89,7 +89,7 @@ public sealed class RoslynCodeTaskFactory : ITaskFactory, IOutOfProcTaskFactory /// /// 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 833f2e133200590fff81a7fb7eeb7a58d081d71e Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:32:43 +0300 Subject: [PATCH 2/5] 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 df6d50f1a48..029b8826cef 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs @@ -712,11 +712,7 @@ public void VerifySameFactoryCanGenerateDifferentTaskInstances() private void SetupTaskFactory(IDictionary factoryParameters, bool explicitlyLaunchTaskHost = false, bool isTaskHostFactory = false) { _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); if (explicitlyLaunchTaskHost) { factoryParameters ??= new Dictionary(); 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 ad57990116f..3340428bc8f 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 8c368ba8c5e..42fff47f595 100644 --- a/src/Build/Instance/TaskFactories/TaskHostTask.cs +++ b/src/Build/Instance/TaskFactories/TaskHostTask.cs @@ -293,7 +293,7 @@ public bool Execute() ErrorUtilities.VerifyThrowInternalNull(_taskHostProvider, "taskHostProvider"); } - string taskLocation = AssemblyUtilities.GetAssemblyLocation(_taskType.Type.Assembly); + string taskLocation = _taskType.Type.Assembly.Location; if (string.IsNullOrEmpty(taskLocation)) { // fall back to the AssemblyLoadInfo location for inline tasks loaded from bytes @@ -556,7 +556,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 db68730447e..23afc088245 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 edb7189e7f4..3ee004f3eaa 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1419,11 +1419,7 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger) 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 3a0c945eb7d..2d28cb00c85 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 2818a0f79aa..7486aa07b0c 100644 --- a/src/Shared/FileUtilities.cs +++ b/src/Shared/FileUtilities.cs @@ -793,7 +793,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 54d4d89efbabb4bba21b282cc734523d9c237d30 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 12 Jul 2025 22:33:48 +0300 Subject: [PATCH 3/5] 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 990e0e0478c..6851f6127e0 100644 --- a/src/Build.UnitTests/Evaluation/Expander_Tests.cs +++ b/src/Build.UnitTests/Evaluation/Expander_Tests.cs @@ -3488,11 +3488,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 23afc088245..796e212c30c 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 76029ff72d6e32e57d7eb6afd9322cf27ecc48f4 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sat, 26 Jul 2025 23:59:32 +0300 Subject: [PATCH 4/5] 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/Tasks/AssemblyResources.cs | 1 - src/Utilities/AssemblyResources.cs | 1 - 7 files changed, 5 insertions(+), 9 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 2d28cb00c85..35922fe0fa1 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/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 bb84e0aefb049dc230153986a2f3756bed58aed5 Mon Sep 17 00:00:00 2001 From: Theodore Tsirpanis Date: Sun, 27 Jul 2025 20:59:08 +0300 Subject: [PATCH 5/5] 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);